From ffb6bdc07ac97e0445fdd1c26d05c0e161888415 Mon Sep 17 00:00:00 2001 From: Sascha Herzinger <sascha.herzinger@uni.lu> Date: Thu, 25 Jul 2019 14:36:10 +0200 Subject: [PATCH] formatted *.java with eclipse style guide --- .../cdplugin/copypaste/CopyAction.java | 13 +- .../copypaste/CopyPasteAbstractAction.java | 18 +- .../cdplugin/copypaste/CopyPastePlugin.java | 22 +- .../cdplugin/copypaste/CopyPluginAction.java | 13 +- .../cdplugin/copypaste/PasteAction.java | 9 +- .../cdplugin/copypaste/PastePluginAction.java | 11 +- .../mapviewer/cdplugin/info/InfoFrame.java | 87 +- .../mapviewer/cdplugin/info/InfoPlugin.java | 33 +- .../mapviewer/cdplugin/CdPluginFunctions.java | 5 +- .../cdplugin/copypaste/CopyActionTest.java | 3 +- .../copypaste/CopyPastePluginTest.java | 4 +- .../cdplugin/copypaste/PasteActionTest.java | 5 +- .../cdplugin/info/InfoFrameTest.java | 7 +- .../cdplugin/info/InfoPluginTest.java | 3 +- .../annotation/SpringAnnotationConfig.java | 2 +- .../cache/ApplicationLevelCache.java | 57 +- .../annotation/cache/BigFileCache.java | 714 ++++--- .../annotation/cache/CachableInterface.java | 63 +- .../annotation/cache/CacheException.java | 26 +- .../annotation/cache/FtpClientFactory.java | 16 +- .../annotation/cache/GeneralCache.java | 23 +- .../cache/GeneralCacheWithExclusion.java | 5 +- .../cache/PermanentDatabaseLevelCache.java | 504 +++-- .../PermanentDatabaseLevelCacheInterface.java | 5 +- .../annotation/cache/QueryCacheInterface.java | 6 +- .../annotation/cache/SourceNotAvailable.java | 66 +- .../annotation/cache/WebPageDownloader.java | 319 ++- .../annotation/cache/XmlSerializer.java | 168 +- .../annotation/cache/package-info.java | 15 +- .../mapviewer/annotation/data/Article.java | 352 ++-- .../data/ArticleCitationComparator.java | 8 +- .../lcsb/mapviewer/annotation/data/Chebi.java | 451 +++-- .../annotation/data/ChebiRelation.java | 180 +- .../mapviewer/annotation/data/Chemical.java | 551 +++--- .../data/ChemicalDirectEvidence.java | 43 +- .../lcsb/mapviewer/annotation/data/Drug.java | 629 +++--- .../mapviewer/annotation/data/EntrezData.java | 261 +-- .../lcsb/mapviewer/annotation/data/Go.java | 128 +- .../lcsb/mapviewer/annotation/data/MeSH.java | 325 ++-- .../lcsb/mapviewer/annotation/data/MiRNA.java | 37 +- .../mapviewer/annotation/data/Target.java | 7 +- .../mapviewer/annotation/data/TargetType.java | 84 +- .../annotation/data/TargettingStructure.java | 22 +- .../annotation/data/package-info.java | 1 - .../annotation/services/ChEMBLParser.java | 231 +-- .../annotation/services/ChemicalParser.java | 136 +- .../services/ChemicalSearchException.java | 66 +- .../annotation/services/DrugAnnotation.java | 14 +- .../services/DrugSearchException.java | 66 +- .../services/DrugbankHTMLParser.java | 177 +- .../services/ExternalServiceStatus.java | 138 +- .../services/ExternalServiceStatusType.java | 100 +- .../annotation/services/IExternalService.java | 36 +- .../services/ImproperAnnotations.java | 100 +- .../annotation/services/MeSHParser.java | 57 +- .../annotation/services/MiRNAParser.java | 93 +- .../services/MiRNASearchException.java | 66 +- .../annotation/services/MiriamConnector.java | 38 +- .../services/MissingAnnotation.java | 42 +- .../services/MissingRequiredAnnotations.java | 90 +- .../annotation/services/ModelAnnotator.java | 28 +- .../services/ProblematicAnnotation.java | 12 +- .../annotation/services/PubmedParser.java | 82 +- .../services/PubmedSearchException.java | 48 +- .../annotation/services/TaxonomyBackend.java | 57 +- .../services/TaxonomySearchException.java | 32 +- .../WrongResponseCodeIOException.java | 54 +- .../services/annotators/BrendaAnnotator.java | 40 +- .../services/annotators/CazyAnnotator.java | 80 +- .../services/annotators/ChebiAnnotator.java | 141 +- .../services/annotators/ElementAnnotator.java | 776 ++++---- .../services/annotators/EnsemblAnnotator.java | 70 +- .../services/annotators/EntrezAnnotator.java | 121 +- .../services/annotators/GoAnnotator.java | 101 +- .../services/annotators/HgncAnnotator.java | 113 +- .../services/annotators/KeggAnnotator.java | 123 +- .../services/annotators/PdbAnnotator.java | 120 +- .../services/annotators/ReconAnnotator.java | 120 +- .../services/annotators/StitchAnnotator.java | 27 +- .../services/annotators/StringAnnotator.java | 72 +- .../services/annotators/TairAnnotator.java | 132 +- .../services/annotators/UniprotAnnotator.java | 138 +- .../services/annotators/package-info.java | 1 - .../AbstractReferenceGenomeConnector.java | 737 ++++--- .../genome/FileNotAvailableException.java | 66 +- .../genome/ReferenceGenomeConnector.java | 256 +-- .../ReferenceGenomeConnectorException.java | 66 +- .../genome/UcscReferenceGenomeConnector.java | 339 ++-- .../annotation/services/package-info.java | 1 - .../annotation/AllAnnotationTests.java | 12 +- .../annotation/AnnotationTestFunctions.java | 44 +- .../SpringAnnotationTestConfig.java | 4 +- .../annotation/cache/AllCacheTests.java | 14 +- .../annotation/cache/BigFileCacheTest.java | 5 +- .../cache/CachableInterfaceMock.java | 16 +- .../cache/CachableInterfaceTest.java | 4 +- .../annotation/cache/MockCacheInterface.java | 36 +- .../PermanentDatabaseLevelCacheTest.java | 2 +- .../cache/SourceNotAvailableTest.java | 33 +- .../cache/WebPageDownloaderTest.java | 2 +- .../annotation/data/AllDataTests.java | 24 +- .../data/ArticleCitationComparatorTest.java | 67 +- .../mapviewer/annotation/data/ChebiTest.java | 2 +- .../data/ChemicalDirectEvidenceTest.java | 35 +- .../annotation/data/ChemicalTest.java | 89 +- .../annotation/data/EntrezDataTest.java | 69 +- .../mapviewer/annotation/data/MeSHTest.java | 3 +- .../mapviewer/annotation/data/MiRNATest.java | 61 +- .../mapviewer/annotation/data/TargetTest.java | 2 +- .../annotation/data/TargetTypeTest.java | 43 +- .../annotation/services/AllServicesTests.java | 42 +- .../annotation/services/ChEMBLParserTest.java | 2 +- .../services/ChemicalParserTest.java | 6 +- .../services/ChemicalSearchExceptionTest.java | 35 +- .../services/DrugAnnotationTest.java | 2 +- .../services/DrugbankHTMLParserTest.java | 5 +- .../services/ExternalServiceStatusTest.java | 41 +- .../ExternalServiceStatusTypeTest.java | 45 +- .../services/ImproperAnnotationsTest.java | 2 +- .../annotation/services/MeSHParserTest.java | 7 +- .../annotation/services/MiRNAParserTest.java | 4 +- .../services/MiRNASearchExceptionTest.java | 51 +- .../services/MiriamConnectorTest.java | 5 +- .../services/MissingAnnotationTest.java | 33 +- .../MissingRequiredAnnotationsTest.java | 69 +- .../annotation/services/PubmedParserTest.java | 17 +- .../services/TaxonomyBackendTest.java | 5 +- .../annotators/AnnotatorExceptionTest.java | 5 +- .../annotators/BrendaAnnotatorTest.java | 8 +- .../annotators/CazyAnnotatorTest.java | 5 +- .../annotators/ChebiAnnotatorTest.java | 2 +- .../ElementAnnotatorImplementationsTest.java | 21 +- .../annotators/ElementAnnotatorTest.java | 11 +- .../annotators/EnsemblAnnotatorTest.java | 5 +- .../annotators/EntrezAnnotatorTest.java | 2 +- .../services/annotators/GoAnnotatorTest.java | 5 +- .../annotators/HgncAnnotatorTest.java | 5 +- .../annotators/KeggAnnotatorTest.java | 8 +- .../annotators/MultipleAnnotatorsTest.java | 2 +- .../services/annotators/PdbAnnotatorTest.java | 5 +- .../annotators/ReconAnnotatorTest.java | 3 +- .../annotators/StitchAnnotatorTest.java | 3 +- .../annotators/StringAnnotatorTest.java | 3 +- .../annotators/TairAnnotatorTest.java | 5 +- .../annotators/UniprotAnnotatorTest.java | 5 +- .../UcscReferenceGenomeConnectorTest.java | 2 +- .../lcsb/mapviewer/common/Comparator.java | 2 +- .../lcsb/mapviewer/common/Configuration.java | 73 +- .../mapviewer/common/FrameworkVersion.java | 134 +- .../mapviewer/common/IProgressUpdater.java | 30 +- .../common/MinervaLoggerAppender.java | 23 +- .../lcsb/mapviewer/common/ObjectUtils.java | 70 +- .../main/java/lcsb/mapviewer/common/Pair.java | 114 +- .../mapviewer/common/SystemClipboard.java | 90 +- .../lcsb/mapviewer/common/TextFileUtils.java | 5 +- .../java/lcsb/mapviewer/common/XmlParser.java | 43 +- .../common/comparator/BooleanComparator.java | 26 +- .../common/comparator/ColorComparator.java | 28 +- .../common/comparator/DoubleComparator.java | 80 +- .../common/comparator/EnumComparator.java | 28 +- .../common/comparator/LineComparator.java | 2 +- .../common/comparator/ListComparator.java | 3 +- .../common/comparator/PointComparator.java | 82 +- .../common/comparator/SetComparator.java | 3 +- .../common/comparator/StringComparator.java | 83 +- .../comparator/StringListComparator.java | 2 +- .../comparator/StringSetComparator.java | 3 +- .../common/comparator/package-info.java | 1 - .../exception/InvalidArgumentException.java | 90 +- .../exception/InvalidClassException.java | 49 +- .../exception/InvalidStateException.java | 78 +- .../exception/InvalidXmlSchemaException.java | 92 +- .../exception/NotImplementedException.java | 38 +- .../common/exception/package-info.java | 1 - .../common/geometry/ColorParser.java | 4 +- .../common/geometry/CompositeStroke.java | 53 +- .../geometry/EllipseTransformation.java | 3 +- .../common/geometry/LineTransformation.java | 6 +- .../common/geometry/PointTransformation.java | 4 +- .../common/geometry/TextAlignment.java | 24 +- .../common/geometry/package-info.java | 1 - .../lcsb/mapviewer/common/package-info.java | 1 - .../lcsb/mapviewer/common/AllCommonTests.java | 20 +- .../mapviewer/common/ConfigurationTest.java | 227 ++- .../common/GlobalLoggerAppenderTest.java | 3 +- .../lcsb/mapviewer/common/MimeTypeTest.java | 42 +- .../mapviewer/common/ObjectUtilsTest.java | 3 +- .../java/lcsb/mapviewer/common/PairTest.java | 106 +- .../mapviewer/common/SystemClipboardTest.java | 13 +- .../lcsb/mapviewer/common/XmlParserTest.java | 5 +- .../comparator/BooleanComparatorTest.java | 55 +- .../comparator/ColorComparatorTest.java | 57 +- .../comparator/DoubleComparatorTest.java | 71 +- .../comparator/IntegerComparatorTest.java | 49 +- .../common/comparator/LineComparatorTest.java | 7 +- .../common/comparator/ListComparatorTest.java | 5 +- .../comparator/PointComparatorTest.java | 68 +- .../common/comparator/SetComparatorTest.java | 9 +- .../comparator/StringComparatorTest.java | 71 +- .../comparator/StringListComparatorTest.java | 88 +- .../comparator/StringSetComparatorTest.java | 93 +- .../common/exception/AllExceptionTests.java | 5 +- .../InvalidArgumentExceptionTest.java | 60 +- .../exception/InvalidClassExceptionTest.java | 32 +- .../exception/InvalidStateExceptionTest.java | 60 +- .../InvalidXmlSchemaExceptionTest.java | 60 +- .../NotImplementedExceptionTest.java | 34 +- .../common/geometry/AllGeometryTests.java | 10 +- .../common/geometry/ColorParserTest.java | 4 +- .../common/geometry/CompositeStrokeTest.java | 28 +- .../geometry/EllipseTransformationTest.java | 139 +- .../geometry/LineTransformationTest.java | 34 +- .../geometry/PointTransformationTest.java | 16 +- .../common/geometry/TextAlignmentTest.java | 32 +- .../CellDesignerElementCollection.java | 51 +- .../celldesigner/CellDesignerXmlParser.java | 84 +- .../model/celldesigner/CommonXmlParser.java | 161 +- .../celldesigner/InvalidGroupException.java | 94 +- .../model/celldesigner/LayerXmlParser.java | 17 +- .../alias/AbstractAliasXmlParser.java | 9 +- .../alias/AliasCollectionXmlParser.java | 428 ++-- .../alias/CompartmentAliasXmlParser.java | 13 +- .../alias/ComplexAliasXmlParser.java | 97 +- .../alias/SpeciesAliasXmlParser.java | 63 +- .../celldesigner/alias/package-info.java | 1 - .../celldesigner/annotation/NoteField.java | 4 +- .../annotation/RestAnnotationParser.java | 22 +- .../celldesigner/annotation/package-info.java | 1 - .../CompartmentCollectionXmlParser.java | 11 +- .../CompartmentParserException.java | 13 +- .../compartment/CompartmentXmlParser.java | 87 +- .../compartment/package-info.java | 1 - .../function/FunctionXmlParser.java | 6 +- .../AbstractCellDesignerAliasConverter.java | 281 ++- ...ntisenseRnaCellDesignerAliasConverter.java | 75 +- .../geometry/CellDesignerAliasConverter.java | 71 +- .../ComplexCellDesignerAliasConverter.java | 96 +- .../DegradedCellDesignerAliasConverter.java | 154 +- .../DrugCellDesignerAliasConverter.java | 128 +- .../GeneCellDesignerAliasConverter.java | 80 +- .../IonCellDesignerAliasConverter.java | 73 +- .../PhenotypeCellDesignerAliasConverter.java | 135 +- .../ProteinCellDesignerAliasConverter.java | 418 ++-- .../ReactionCellDesignerConverter.java | 19 +- .../RnaCellDesignerAliasConverter.java | 81 +- ...pleMoleculeCellDesignerAliasConverter.java | 3 +- .../UnknownCellDesignerAliasConverter.java | 13 +- .../CellDesignerEllipseTransformation.java | 64 +- .../CellDesignerPointTransformation.java | 133 +- .../CellDesignerPolygonTransformation.java | 182 +- .../CellDesignerRectangleTransformation.java | 83 +- .../geometry/helper/package-info.java | 1 - .../celldesigner/geometry/package-info.java | 1 - .../model/celldesigner/package-info.java | 1 - .../ParameterCollectionXmlParser.java | 3 +- .../parameter/ParameterXmlParser.java | 5 +- .../reaction/KineticsXmlParser.java | 11 +- .../reaction/ReactionCollectionXmlParser.java | 4 +- .../reaction/ReactionFromXml.java | 68 +- .../reaction/ReactionLineData.java | 179 +- .../celldesigner/reaction/ReactionToXml.java | 49 +- .../reaction/ReactionXmlParser.java | 98 +- .../UnknownModifierClassException.java | 74 +- .../celldesigner/reaction/package-info.java | 1 - .../species/AbstractElementXmlParser.java | 49 +- .../species/AntisenseRnaXmlParser.java | 5 +- .../celldesigner/species/GeneXmlParser.java | 65 +- .../species/InternalModelSpeciesData.java | 382 ++-- .../species/ModificationResidueXmlParser.java | 17 +- .../celldesigner/species/ProteinMapping.java | 271 ++- .../species/ProteinXmlParser.java | 9 +- .../celldesigner/species/RnaXmlParser.java | 61 +- .../species/SpeciesCollection.java | 296 ++- .../species/SpeciesCollectionXmlParser.java | 31 +- .../celldesigner/species/SpeciesMapping.java | 108 +- .../species/SpeciesSbmlParser.java | 31 +- .../celldesigner/species/package-info.java | 1 - .../structure/CellDesignerAntisenseRna.java | 80 +- .../structure/CellDesignerChemical.java | 216 +-- .../structure/CellDesignerCompartment.java | 47 +- .../structure/CellDesignerComplexSpecies.java | 302 +-- .../structure/CellDesignerDegraded.java | 72 +- .../structure/CellDesignerDrug.java | 72 +- .../structure/CellDesignerElement.java | 83 +- .../structure/CellDesignerGene.java | 93 +- .../structure/CellDesignerGenericProtein.java | 12 +- .../CellDesignerIonChannelProtein.java | 74 +- .../structure/CellDesignerPhenotype.java | 73 +- .../structure/CellDesignerProtein.java | 71 +- .../CellDesignerReceptorProtein.java | 74 +- .../structure/CellDesignerRna.java | 60 +- .../structure/CellDesignerSimpleMolecule.java | 87 +- .../structure/CellDesignerSpecies.java | 261 +-- .../CellDesignerTruncatedProtein.java | 76 +- .../structure/CellDesignerUnknown.java | 64 +- .../CellDesignerModificationResidue.java | 105 +- .../structure/fields/ConnectScheme.java | 195 +- .../structure/fields/LineProperties.java | 2 +- .../structure/fields/ModificationType.java | 8 +- .../structure/fields/SingleLine.java | 38 +- .../structure/fields/SpeciesState.java | 60 +- .../celldesigner/structure/fields/View.java | 147 +- .../celldesigner/types/ModifierType.java | 370 ++-- .../celldesigner/types/ModifierTypeUtils.java | 521 +++-- .../celldesigner/types/OperatorType.java | 140 +- .../celldesigner/types/OperatorTypeUtils.java | 143 +- .../celldesigner/types/package-info.java | 1 - .../unit/UnitCollectionXmlParser.java | 2 +- .../celldesigner/unit/UnitXmlParser.java | 7 +- .../CellDesignerTestFunctions.java | 38 +- .../CellDesignerXmlParserTest.java | 5 +- .../celldesigner/ComplexParserTests.java | 33 +- .../InvalidGroupExceptionTest.java | 30 +- .../celldesigner/LayerXmlParserTest.java | 2 +- .../NestedComplexParsingTests.java | 3 +- .../celldesigner/SbmlValidationTests.java | 4 +- .../celldesigner/alias/AllAliasTests.java | 6 +- .../alias/ComplexAliasXmlParserTest.java | 5 +- .../alias/SpeciesAliasXmlParserTest.java | 5 +- .../annotation/NoteFieldTest.java | 43 +- .../compartment/AllCompartmentTests.java | 4 +- .../CompartmentCollectionXmlParserTest.java | 3 +- .../compartment/CompartmentParserTests.java | 2 +- .../FunctionCollectionXmlParserTest.java | 6 +- .../function/FunctionXmlParserTest.java | 7 +- ...bstractCellDesignerAliasConverterTest.java | 22 +- .../geometry/AllGeometryTests.java | 30 +- ...enseRnaCellDesignerAliasConverterTest.java | 79 +- .../geometry/ComplexConverterTest.java | 2 +- ...egradedCellDesignerAliasConverterTest.java | 79 +- .../GeneCellDesignerAliasConverterTest.java | 3 +- .../IonCellDesignerAliasConverterTest.java | 5 +- ...ProteinCellDesignerAliasConverterTest.java | 2 +- .../geometry/ProteinConverterTest.java | 2 +- .../ReactionCellDesignerConverterTest.java | 35 +- .../RnaCellDesignerAliasConverterTest.java | 79 +- ...oleculeCellDesignerAliasConverterTest.java | 3 +- ...UnknownCellDesignerAliasConverterTest.java | 5 +- .../geometry/helper/AllHelperTests.java | 12 +- .../helper/CellDesignerAnchorTest.java | 35 +- ...CellDesignerEllipseTransformationTest.java | 270 ++- .../CellDesignerPointTransformationTest.java | 3 +- ...llDesignerRectangleTransformationTest.java | 35 +- .../reaction/KineticsXmlParserTest.java | 33 +- .../reaction/ModificationReactionTest.java | 2 +- .../ReactionCollectionXmlParserTest.java | 335 ++-- .../reaction/ReactionLineDataTest.java | 3 +- .../reaction/ReactionParserExceptionTest.java | 59 +- .../reaction/ReactionParserTests.java | 5 +- .../UnknownModifierClassExceptionTest.java | 45 +- .../species/AntisenseRnaXmlParserTest.java | 3 +- .../species/ComplexParserTest.java | 2 +- .../species/InternalModelSpeciesDataTest.java | 2 +- .../ModificationResidueXmlParserTest.java | 2 +- .../species/ProteinMappingTest.java | 2 +- .../species/ProteinXmlParserTest.java | 3 +- .../species/SpeciesMappingTest.java | 2 +- .../species/SpeciesSbmlParserTest.java | 8 +- .../structure/AllStructureTests.java | 48 +- .../structure/CellDesignerChemicalTest.java | 59 +- .../structure/ComplexSpeciesTest.java | 3 +- .../structure/ConnectSchemeTest.java | 59 +- .../celldesigner/structure/DegradedTest.java | 2 +- .../celldesigner/structure/DrugTest.java | 2 +- .../celldesigner/structure/GeneTest.java | 3 +- .../structure/GenericProteinTest.java | 2 +- .../structure/IonChannelProteinTest.java | 2 +- .../model/celldesigner/structure/IonTest.java | 2 +- .../structure/LinePropertiesTest.java | 45 +- .../celldesigner/structure/PhenotypeTest.java | 2 +- .../celldesigner/structure/ProteinTest.java | 3 +- .../structure/ReceptorProteinTest.java | 2 +- .../structure/SimpleMoleculeTest.java | 2 +- .../structure/SpeciesStateTest.java | 2 +- .../structure/TruncatedProteinTest.java | 2 +- .../celldesigner/structure/UnknownTest.java | 2 +- .../celldesigner/structure/ViewTest.java | 45 +- .../CellDesignerModificationResidueTest.java | 33 +- .../celldesigner/types/AllTypesTests.java | 6 +- .../celldesigner/types/ModifierTypeTest.java | 35 +- .../types/ModifierTypeUtilsTest.java | 3 +- .../celldesigner/types/OperatorTypeTest.java | 37 +- .../types/OperatorTypeUtilsTest.java | 2 +- .../model/sbgnml/SbgnmlXmlConverter.java | 9 +- .../model/sbgnml/SbgnmlXmlExporter.java | 123 +- .../model/sbgnml/SbgnmlXmlParser.java | 96 +- .../converter/model/sbgnml/package-info.java | 3 +- .../model/sbgnml/structures/Process.java | 440 ++--- .../model/sbgnml/structures/package-info.java | 3 +- .../model/sbgnml/AllSbgnmlTests.java | 10 +- .../model/sbgnml/CellDesignerToSbgnTest.java | 3 +- .../model/sbgnml/DbSerializationTest.java | 8 +- .../model/sbgnml/SbgnmlTestFunctions.java | 2 +- .../model/sbgnml/SbgnmlXmlParserTest.java | 3 +- .../graphics/AbstractImageGenerator.java | 1719 ++++++++--------- .../converter/graphics/ConverterParams.java | 188 +- .../converter/graphics/DrawingException.java | 48 +- .../converter/graphics/ImageGenerators.java | 290 +-- .../converter/graphics/JpgImageGenerator.java | 112 +- .../converter/graphics/MapGenerator.java | 361 ++-- .../graphics/NormalImageGenerator.java | 91 +- .../converter/graphics/PdfFontMapper.java | 5 +- .../converter/graphics/PdfImageGenerator.java | 50 +- .../converter/graphics/PngImageGenerator.java | 143 +- .../converter/graphics/SvgImageGenerator.java | 159 +- .../bioEntity/BioEntityConverter.java | 28 +- .../bioEntity/BioEntityConverterImpl.java | 307 ++- .../bioEntity/element/ElementConverter.java | 3 +- .../BottomSquareCompartmentConverter.java | 134 +- .../compartment/CompartmentConverter.java | 304 ++- .../LeftSquareCompartmentConverter.java | 139 +- .../compartment/OvalCompartmentConverter.java | 149 +- .../PathwayCompartmentConverter.java | 5 +- .../RightSquareCompartmentConverter.java | 148 +- .../SquareCompartmentConverter.java | 166 +- .../TopSquareCompartmentConverter.java | 131 +- .../element/compartment/package-info.java | 4 +- .../species/AntisenseRnaConverter.java | 12 +- .../element/species/ComplexConverter.java | 25 +- .../element/species/DegradedConverter.java | 223 ++- .../element/species/DrugConverter.java | 197 +- .../element/species/GeneConverter.java | 9 +- .../element/species/IonConverter.java | 8 +- .../element/species/PhenotypeConverter.java | 120 +- .../element/species/ProteinConverter.java | 23 +- .../element/species/RnaConverter.java | 12 +- .../SBGNNucleicAcidFeatureConverter.java | 221 ++- .../species/SimpleMoleculeConverter.java | 11 +- .../element/species/SpeciesConverter.java | 122 +- .../element/species/UnknownConverter.java | 8 +- .../bioEntity/reaction/ReactionConverter.java | 93 +- .../bioEntity/reaction/package-info.java | 1 - .../geometry/ArrowTransformation.java | 23 +- .../graphics/geometry/FontFinder.java | 462 ++--- .../geometry/RectangleTooSmallException.java | 26 +- .../graphics/geometry/package-info.java | 1 - .../graphics/layer/LayerConverter.java | 10 +- .../graphics/layer/LayerLineConverter.java | 6 +- .../graphics/layer/LayerOvalConverter.java | 6 +- .../graphics/layer/LayerRectConverter.java | 6 +- .../graphics/layer/LayerTextConverter.java | 16 +- .../graphics/layer/package-info.java | 1 - .../converter/graphics/package-info.java | 5 +- .../graphics/placefinder/PlaceFinder.java | 915 +++++---- .../graphics/placefinder/package-info.java | 1 - .../graphics/AbstractImageGeneratorTest.java | 10 +- .../converter/graphics/AllGraphicsTests.java | 20 +- .../graphics/GraphicsTestFunctions.java | 4 +- .../graphics/ImageGeneratorsTest.java | 2 +- .../converter/graphics/MapGeneratorTest.java | 3 +- .../graphics/NormalImageGeneratorTest.java | 2 +- .../converter/graphics/PdfFontMapperTest.java | 2 +- .../graphics/PdfImageGeneratorTest.java | 11 +- .../graphics/SvgImageGeneratorTest.java | 14 +- .../bioEntity/BioEntityConverterImplTest.java | 18 +- .../PathwayCompartmentConverterTest.java | 5 +- .../element/species/ComplexConverterTest.java | 6 +- .../element/species/SpeciesConverterTest.java | 6 +- .../reaction/ReactionConverterTest.java | 24 +- .../geometry/ArrowTransformationTest.java | 5 +- .../graphics/geometry/FontFinderTest.java | 3 +- .../placefinder/AllPlaceFinderTest.java | 254 +-- .../model/sbml/SbmlBioEntityExporter.java | 46 +- .../model/sbml/SbmlBioEntityParser.java | 28 +- .../model/sbml/SbmlElementExporter.java | 28 +- .../model/sbml/SbmlElementParser.java | 17 +- .../converter/model/sbml/SbmlExporter.java | 16 +- .../model/sbml/SbmlFunctionExporter.java | 3 +- .../model/sbml/SbmlFunctionParser.java | 15 +- .../model/sbml/SbmlParameterExporter.java | 3 +- .../model/sbml/SbmlParameterParser.java | 13 +- .../converter/model/sbml/SbmlParser.java | 52 +- .../compartment/SbmlCompartmentExporter.java | 82 +- .../compartment/SbmlCompartmentParser.java | 39 +- .../extension/multi/BioEntityFeature.java | 7 +- .../multi/MultiPackageNamingUtils.java | 16 +- .../sbml/reaction/SBOTermModifierType.java | 13 +- .../sbml/reaction/SBOTermReactionType.java | 32 +- .../sbml/reaction/SbmlReactionExporter.java | 169 +- .../sbml/reaction/SbmlReactionParser.java | 53 +- .../model/sbml/species/ElementColorEnum.java | 21 +- .../sbml/species/SBOTermSpeciesType.java | 21 +- .../sbml/species/SbmlSpeciesExporter.java | 177 +- .../model/sbml/species/SbmlSpeciesParser.java | 180 +- .../model/sbml/units/SbmlUnitExporter.java | 3 +- .../model/sbml/units/SbmlUnitsParser.java | 13 +- .../model/sbml/units/UnitMapping.java | 1 + .../sbml/CellDesignerToMultiExportTest.java | 3 +- .../model/sbml/CopasiImportTest.java | 2 +- .../model/sbml/ElementPropertiesExport.java | 2 +- .../ElementPropertiesExportToLayoutTest.java | 2 +- .../ElementPropertiesExportToMultiTest.java | 2 +- .../model/sbml/GenericSbmlParserTest.java | 3 +- .../sbml/GenericSbmlToXmlParserTest.java | 3 +- .../converter/model/sbml/MultiParserTest.java | 3 +- .../ReactionPropertiesExportToMultiTest.java | 5 +- .../model/sbml/SbmlBioEntityExporterTest.java | 6 +- .../SbmlExporterFromCellDesignerTest.java | 2 +- .../model/sbml/SbmlExporterTest.java | 3 +- .../model/sbml/SbmlTestFunctions.java | 48 +- .../SbmlCompartmentParserTest.java | 3 +- .../reaction/SbmlReactionExportArrowType.java | 31 +- .../reaction/SbmlReactionExporterTest.java | 4 +- .../SbmlReactionParserExtractCurveTest.java | 23 +- .../sbml/species/SbmlSpeciesExporterTest.java | 12 +- .../sbml/species/SbmlSpeciesParserTest.java | 22 +- .../converter/ComplexZipConverter.java | 34 +- .../converter/ComplexZipConverterParams.java | 12 +- .../lcsb/mapviewer/converter/Converter.java | 150 +- .../converter/ConverterException.java | 82 +- .../mapviewer/converter/ConverterParams.java | 4 +- .../lcsb/mapviewer/converter/GlyphParser.java | 3 +- .../converter/InvalidCoordinatesFile.java | 72 +- .../converter/InvalidOverviewFile.java | 72 +- .../mapviewer/converter/OverviewParser.java | 24 +- .../mapviewer/converter/ProjectFactory.java | 22 +- .../mapviewer/converter/ZIndexPopulator.java | 11 +- .../annotation/XmlAnnotationParser.java | 20 +- .../mapviewer/converter/package-info.java | 1 - .../converter/zip/InputFileType.java | 56 +- .../converter/zip/ModelZipEntryFile.java | 366 ++-- .../mapviewer/converter/zip/ZipEntryFile.java | 126 +- .../converter/zip/ZipEntryFileFactory.java | 44 +- .../mapviewer/converter/zip/package-info.java | 1 - .../converter/ConverterTestFunctions.java | 35 +- .../mapviewer/converter/MockConverter.java | 19 +- .../converter/ZIndexPopulatorTest.java | 10 +- .../commands/ClearColorModelCommand.java | 63 +- .../mapviewer/commands/ColorExtractor.java | 166 +- .../mapviewer/commands/ColorModelCommand.java | 39 +- .../commands/CommandExecutionException.java | 78 +- .../lcsb/mapviewer/commands/CopyCommand.java | 45 +- .../commands/CreateHierarchyCommand.java | 38 +- .../commands/InvalidModelException.java | 26 +- .../lcsb/mapviewer/commands/ModelCommand.java | 401 ++-- .../commands/ModelCommandStatus.java | 24 +- .../lcsb/mapviewer/commands/MoveCommand.java | 99 +- .../commands/MoveElementsCommand.java | 16 +- .../mapviewer/commands/NewModelCommand.java | 70 +- .../commands/SemanticZoomLevelMatcher.java | 80 +- .../SetFixedHierarchyLevelCommand.java | 13 +- .../mapviewer/commands/SubModelCommand.java | 12 +- .../layout/ApplyLayoutModelCommand.java | 3 +- .../layout/ApplySimpleLayoutModelCommand.java | 58 +- .../lcsb/mapviewer/commands/package-info.java | 1 - .../AddElementFormerSymbolsCommand.java | 110 +- .../AddElementMiriamDataCommand.java | 89 +- .../AddElementPropertyListEntryCommand.java | 126 +- .../properties/AddElementSynonymsCommand.java | 89 +- .../ChangeElementAbbreviationCommand.java | 71 +- .../properties/ChangeElementColorCommand.java | 67 +- .../ChangeElementFontSizeCommand.java | 73 +- .../ChangeElementFormerSymbolCommand.java | 85 +- .../ChangeElementFormulaCommand.java | 71 +- .../ChangeElementFullNameCommand.java | 73 +- .../ChangeElementMiriamDataCommand.java | 91 +- .../properties/ChangeElementNameCommand.java | 65 +- .../properties/ChangeElementNotesCommand.java | 73 +- .../ChangeElementPropertyCommand.java | 180 +- ...ChangeElementPropertyListEntryCommand.java | 195 +- .../ChangeElementSymbolCommand.java | 73 +- .../ChangeElementSynonymCommand.java | 85 +- .../RemoveElementFormerSymbolsCommand.java | 90 +- .../RemoveElementMiriamDataCommand.java | 90 +- ...RemoveElementPropertyListEntryCommand.java | 127 +- .../RemoveElementSynonymsCommand.java | 90 +- .../commands/properties/package-info.java | 1 - .../mapviewer/commands/AllCommandsTests.java | 6 +- .../commands/ColorModelCommandTest.java | 3 +- .../commands/CommandTestFunctions.java | 19 +- .../commands/SubModelCommandTest.java | 3 +- .../properties/AllPropertyCommandTests.java | 22 +- .../ChangeElementColorCommandTest.java | 2 +- .../ChangeElementFormerSymbolCommandTest.java | 2 +- .../java/lcsb/mapviewer/model/Project.java | 24 +- .../mapviewer/model/cache/BigFileEntry.java | 4 +- .../mapviewer/model/cache/CacheQuery.java | 26 +- .../lcsb/mapviewer/model/cache/CacheType.java | 5 +- .../lcsb/mapviewer/model/cache/FileEntry.java | 10 +- .../model/cache/UploadedFileEntry.java | 5 +- .../mapviewer/model/cache/package-info.java | 1 - .../mapviewer/model/graphics/ArrowType.java | 16 +- .../graphics/ArrowTypeDataComparator.java | 3 +- .../mapviewer/model/graphics/LineType.java | 21 +- .../model/graphics/MapCanvasType.java | 3 +- .../model/graphics/PolylineData.java | 67 +- .../graphics/PolylineDataComparator.java | 3 +- .../model/graphics/package-info.java | 1 - .../lcsb/mapviewer/model/map/BioEntity.java | 44 +- .../lcsb/mapviewer/model/map/Comment.java | 33 +- .../lcsb/mapviewer/model/map/MiriamData.java | 66 +- .../model/map/MiriamRelationType.java | 18 +- .../lcsb/mapviewer/model/map/MiriamType.java | 112 +- .../mapviewer/model/map/OverviewImage.java | 9 +- .../model/map/OverviewImageComparator.java | 3 +- .../model/map/OverviewImageLink.java | 5 +- .../map/OverviewImageLinkComparator.java | 13 +- .../mapviewer/model/map/OverviewLink.java | 12 +- .../model/map/OverviewLinkComparator.java | 3 +- .../model/map/OverviewModelLink.java | 35 +- .../map/OverviewModelLinkComparator.java | 3 +- .../lcsb/mapviewer/model/map/SearchIndex.java | 9 +- .../model/map/compartment/Compartment.java | 32 +- .../compartment/CompartmentComparator.java | 15 +- .../map/compartment/PathwayCompartment.java | 2 +- .../compartment/RightSquareCompartment.java | 39 +- .../model/map/kinetics/SbmlFunction.java | 25 +- .../map/kinetics/SbmlFunctionComparator.java | 3 +- .../model/map/kinetics/SbmlKinetics.java | 31 +- .../map/kinetics/SbmlKineticsComparator.java | 3 +- .../model/map/kinetics/SbmlParameter.java | 19 +- .../model/map/kinetics/SbmlUnit.java | 21 +- .../map/kinetics/SbmlUnitComparator.java | 5 +- .../map/kinetics/SbmlUnitTypeFactor.java | 22 +- .../SbmlUnitTypeFactorComparator.java | 4 +- .../model/map/layout/BlockDiagram.java | 14 +- .../model/map/layout/ColorSchema.java | 7 +- .../map/layout/DataOverlayImageLayer.java | 20 +- .../model/map/layout/GeneVariation.java | 39 +- .../map/layout/GeneVariationColorSchema.java | 4 +- .../mapviewer/model/map/layout/Layout.java | 35 +- .../model/map/layout/LayoutStatus.java | 18 +- .../model/map/layout/ReferenceGenome.java | 11 +- .../layout/ReferenceGenomeGeneMapping.java | 7 +- .../model/map/layout/graphics/Glyph.java | 17 +- .../model/map/layout/graphics/Layer.java | 71 +- .../map/layout/graphics/LayerComparator.java | 7 +- .../model/map/layout/graphics/LayerOval.java | 132 +- .../layout/graphics/LayerOvalComparator.java | 4 +- .../model/map/layout/graphics/LayerRect.java | 136 +- .../layout/graphics/LayerRectComparator.java | 5 +- .../model/map/layout/graphics/LayerText.java | 164 +- .../layout/graphics/LayerTextComparator.java | 5 +- .../map/layout/graphics/package-info.java | 1 - .../model/map/layout/package-info.java | 1 - .../mapviewer/model/map/model/Author.java | 18 +- .../model/map/model/AuthorComparator.java | 3 +- .../map/model/ElementSubmodelConnection.java | 4 +- .../ElementSubmodelConnectionComparator.java | 3 +- .../lcsb/mapviewer/model/map/model/Model.java | 213 +- .../model/map/model/ModelComparator.java | 23 +- .../mapviewer/model/map/model/ModelData.java | 102 +- .../model/map/model/ModelFullIndexed.java | 305 ++- .../map/model/ModelSubmodelConnection.java | 15 +- .../ModelSubmodelConnectionComparator.java | 3 +- .../model/map/model/SubmodelConnection.java | 41 +- .../model/SubmodelConnectionComparator.java | 3 +- .../model/map/model/package-info.java | 1 - .../model/map/modifier/package-info.java | 5 +- .../mapviewer/model/map/package-info.java | 1 - .../model/map/reaction/AbstractNode.java | 14 +- .../map/reaction/AbstractNodeComparator.java | 3 +- .../model/map/reaction/AndOperator.java | 83 +- .../map/reaction/AssociationOperator.java | 75 +- .../map/reaction/DissociationOperator.java | 85 +- .../model/map/reaction/Modifier.java | 78 +- .../model/map/reaction/NandOperator.java | 85 +- .../model/map/reaction/NodeOperator.java | 13 +- .../map/reaction/NodeOperatorComparator.java | 13 +- .../model/map/reaction/OrOperator.java | 85 +- .../mapviewer/model/map/reaction/Product.java | 84 +- .../model/map/reaction/Reactant.java | 84 +- .../model/map/reaction/Reaction.java | 335 ++-- .../map/reaction/ReactionComparator.java | 11 +- .../model/map/reaction/ReactionNode.java | 6 +- .../map/reaction/ReactionNodeComparator.java | 11 +- .../model/map/reaction/SplitOperator.java | 85 +- .../map/reaction/TruncationOperator.java | 85 +- .../model/map/reaction/UnknownOperator.java | 85 +- .../model/map/reaction/package-info.java | 5 +- .../model/map/reaction/type/package-info.java | 1 - .../model/map/species/AntisenseRna.java | 25 +- .../map/species/AntisenseRnaComparator.java | 3 +- .../mapviewer/model/map/species/Chemical.java | 4 +- .../model/map/species/ChemicalComparator.java | 13 +- .../mapviewer/model/map/species/Complex.java | 13 +- .../model/map/species/ComplexComparator.java | 13 +- .../model/map/species/DegradedComparator.java | 13 +- .../model/map/species/DrugComparator.java | 3 +- .../mapviewer/model/map/species/Element.java | 655 +++---- .../model/map/species/ElementComparator.java | 11 +- .../mapviewer/model/map/species/Gene.java | 31 +- .../model/map/species/GeneComparator.java | 3 +- .../map/species/GenericProteinComparator.java | 3 +- .../species/IonChannelProteinComparator.java | 3 +- .../model/map/species/IonComparator.java | 3 +- .../map/species/PhenotypeComparator.java | 4 +- .../mapviewer/model/map/species/Protein.java | 15 +- .../model/map/species/ProteinComparator.java | 3 +- .../species/ReceptorProteinComparator.java | 3 +- .../lcsb/mapviewer/model/map/species/Rna.java | 32 +- .../model/map/species/RnaComparator.java | 3 +- .../map/species/SimpleMoleculeComparator.java | 3 +- .../mapviewer/model/map/species/Species.java | 52 +- .../model/map/species/SpeciesComparator.java | 6 +- .../species/TruncatedProteinComparator.java | 3 +- .../model/map/species/UnknownComparator.java | 3 +- .../field/AbstractSiteModification.java | 5 +- .../map/species/field/BindingRegion.java | 3 +- .../model/map/species/field/CodingRegion.java | 8 +- .../species/field/ModificationResidue.java | 19 +- .../map/species/field/ModificationSite.java | 5 +- .../map/species/field/ModificationState.java | 32 +- .../species/field/PositionToCompartment.java | 18 +- .../species/field/ProteinBindingDomain.java | 7 +- .../map/species/field/RegulatoryRegion.java | 3 +- .../field/SpeciesWithModificationSite.java | 2 +- .../map/species/field/SpeciesWithResidue.java | 3 +- .../model/map/species/field/Structure.java | 8 +- .../map/species/field/TranscriptionSite.java | 27 +- .../map/species/field/UniprotRecord.java | 40 +- .../model/map/statistics/SearchHistory.java | 8 +- .../model/map/statistics/package-info.java | 1 - .../lcsb/mapviewer/model/package-info.java | 13 +- .../lcsb/mapviewer/model/plugin/Plugin.java | 25 +- .../model/plugin/PluginDataEntry.java | 8 +- .../mapviewer/model/security/Privilege.java | 20 +- .../model/user/ConfigurationElementType.java | 3 +- .../model/user/ConfigurationOption.java | 7 +- .../java/lcsb/mapviewer/model/user/User.java | 2 +- .../model/user/UserAnnotationSchema.java | 21 +- .../model/user/UserClassAnnotators.java | 28 +- .../user/UserClassRequiredAnnotations.java | 44 +- .../model/user/UserClassValidAnnotations.java | 39 +- .../model/user/UserGuiPreference.java | 9 +- .../annotator/AnnotatorConfigParameter.java | 5 +- .../model/user/annotator/AnnotatorData.java | 9 +- .../annotator/AnnotatorInputParameter.java | 5 +- .../annotator/AnnotatorOutputParameter.java | 17 +- .../user/annotator/AnnotatorParameter.java | 11 +- .../model/user/annotator/BioEntityField.java | 2 +- .../mapviewer/model/user/package-info.java | 1 - .../modelutils/map/ElementUtils.java | 56 +- .../modelutils/map/RequireAnnotationMap.java | 9 +- .../modelutils/map/package-info.java | 1 - .../test/java/lcsb/mapviewer/AllTests.java | 6 +- .../mapviewer/model/ProjectStatusTest.java | 34 +- .../lcsb/mapviewer/model/ProjectTest.java | 3 +- .../mapviewer/model/cache/AllCacheTests.java | 8 +- .../model/cache/BigFileEntryTest.java | 2 +- .../mapviewer/model/cache/CacheQueryTest.java | 3 +- .../mapviewer/model/cache/CacheTypeTest.java | 3 +- .../model/graphics/AllGraphicsTests.java | 10 +- .../graphics/ArrowTypeDataComparatorTest.java | 3 +- .../model/graphics/ArrowTypeDataTest.java | 3 +- .../model/graphics/ArrowTypeTest.java | 34 +- .../model/graphics/LineTypeTest.java | 34 +- .../graphics/PolylineDataComparatorTest.java | 5 +- .../model/graphics/PolylineDataTest.java | 2 +- .../lcsb/mapviewer/model/map/CommentTest.java | 2 +- .../model/map/MiriamRelationTypeTest.java | 44 +- .../map/MiriamTypeNameComparatorTest.java | 3 +- .../map/OverviewImageComparatorTest.java | 4 +- .../map/OverviewImageLinkComparatorTest.java | 4 +- .../model/map/OverviewImageLinkTest.java | 3 +- .../model/map/OverviewImageTest.java | 4 +- .../model/map/OverviewLinkComparatorTest.java | 3 +- .../mapviewer/model/map/OverviewLinkTest.java | 3 +- .../map/OverviewModelLinkComparatorTest.java | 3 +- .../model/map/OverviewSearchLinkTest.java | 3 +- .../mapviewer/model/map/SearchIndexTest.java | 3 +- .../map/compartment/AllCompartmentTests.java | 16 +- .../BottomSquareCompartmentTest.java | 2 +- .../CompartmentComparatorTest.java | 5 +- .../LeftSquareCompartmentTest.java | 2 +- .../map/compartment/OvalCompartmentTest.java | 2 +- .../compartment/PathwayCompartmentTest.java | 3 +- .../RightSquareCompartmentTest.java | 3 +- .../compartment/SquareCompartmentTest.java | 3 +- .../compartment/TopSquareCompartmentTest.java | 2 +- .../model/map/kinetics/AllKineticsTests.java | 2 +- .../model/map/kinetics/SbmlFunctionTest.java | 2 +- .../model/map/kinetics/SbmlKineticsTest.java | 12 +- .../kinetics/SbmlParameterComparatorTest.java | 3 +- .../model/map/kinetics/SbmlParameterTest.java | 2 +- .../map/kinetics/SbmlUnitComparatorTest.java | 6 +- .../map/kinetics/SbmlUnitTypeFactorTest.java | 2 +- .../model/map/layout/AllLayoutTests.java | 22 +- .../model/map/layout/ColorSchemaTest.java | 5 +- .../model/map/layout/ElementGroupTest.java | 2 +- .../layout/GeneVariationColorSchemaTest.java | 3 +- .../model/map/layout/GeneVariationTest.java | 3 +- .../map/layout/GenericColorSchemaTest.java | 2 +- .../InvalidColorSchemaExceptionTest.java | 2 +- .../model/map/layout/LayoutStatusTest.java | 34 +- .../model/map/layout/LayoutTest.java | 1 - .../ReferenceGenomeGeneMappingTest.java | 2 +- .../model/map/layout/ReferenceGenomeTest.java | 2 +- .../map/layout/ReferenceGenomeTypeTest.java | 43 +- .../map/layout/graphics/AllGraphicsTests.java | 14 +- .../layout/graphics/LayerComparatorTest.java | 3 +- .../graphics/LayerOvalComparatorTest.java | 5 +- .../map/layout/graphics/LayerOvalTest.java | 2 +- .../graphics/LayerRectComparatorTest.java | 5 +- .../map/layout/graphics/LayerRectTest.java | 2 +- .../graphics/LayerTextComparatorTest.java | 5 +- .../model/map/model/AllModelTests.java | 18 +- ...ementSubmodelConnectionComparatorTest.java | 5 +- .../model/ElementSubmodelConnectionTest.java | 3 +- .../model/map/model/ModelComparatorTest.java | 5 +- .../model/map/model/ModelFullIndexedTest.java | 56 +- ...ModelSubmodelConnectionComparatorTest.java | 3 +- .../model/ModelSubmodelConnectionTest.java | 4 +- .../SubmodelConnectionComparatorTest.java | 3 +- .../model/map/model/SubmodelTypeTest.java | 34 +- .../model/map/modifier/AllModifierTests.java | 12 +- .../model/map/modifier/CatalysisTest.java | 2 +- .../model/map/modifier/InhibitionTest.java | 2 +- .../model/map/modifier/ModulationTest.java | 2 +- .../map/modifier/PhysicalStimulationTest.java | 2 +- .../model/map/modifier/TriggerTest.java | 2 +- .../map/modifier/UnknownCatalysisTest.java | 2 +- .../map/modifier/UnknownInhibitionTest.java | 2 +- .../reaction/AbstractNodeComparatorTest.java | 3 +- .../model/map/reaction/AllReactionTests.java | 38 +- .../map/reaction/AssociationOperatorTest.java | 3 +- .../reaction/DissociationOperatorTest.java | 3 +- .../model/map/reaction/ModifierTest.java | 2 +- .../model/map/reaction/NandOperatorTest.java | 3 +- .../reaction/NodeOperatorComparatorTest.java | 3 +- .../model/map/reaction/NodeOperatorMock.java | 44 +- .../model/map/reaction/OrOperatorTest.java | 3 +- .../model/map/reaction/ProductTest.java | 2 +- .../model/map/reaction/ReactantTest.java | 2 +- .../map/reaction/ReactionComparatorTest.java | 3 +- .../reaction/ReactionNodeComparatorTest.java | 3 +- .../model/map/reaction/SplitOperatorTest.java | 2 +- .../map/reaction/TruncationOperatorTest.java | 2 +- .../map/reaction/UnknownOperatorTest.java | 3 +- .../type/DissociationReactionTest.java | 2 +- .../HeterodimerAssociationReactionTest.java | 2 +- .../KnownTransitionOmittedReactionTest.java | 2 +- .../type/NegativeInfluenceReactionTest.java | 3 +- .../type/PositiveInfluenceReactionTest.java | 3 +- .../map/reaction/type/ReactionRectTest.java | 34 +- .../type/ReducedModulationReactionTest.java | 3 +- ...educedPhysicalStimulationReactionTest.java | 3 +- .../type/ReducedTriggerReactionTest.java | 3 +- .../type/StateTransitionReactionTest.java | 2 +- .../type/TranscriptionReactionTest.java | 2 +- .../type/TranslationReactionTest.java | 2 +- .../reaction/type/TransportReactionTest.java | 2 +- .../reaction/type/TruncationReactionTest.java | 2 +- .../UnknownNegativeInfluenceReactionTest.java | 3 +- .../UnknownPositiveInfluenceReactionTest.java | 3 +- .../UnknownReducedModulationReactionTest.java | 3 +- ...educedPhysicalStimulationReactionTest.java | 3 +- .../UnknownReducedTriggerReactionTest.java | 3 +- .../type/UnknownTransitionReactionTest.java | 2 +- .../model/map/species/AllSpeciesTests.java | 70 +- .../species/AntisenseRnaComparatorTest.java | 3 +- .../model/map/species/AntisenseRnaTest.java | 3 +- .../map/species/ChemicalComparatorTest.java | 3 +- .../map/species/ComplexComparatorTest.java | 7 +- .../model/map/species/ComplexTest.java | 3 +- .../map/species/DegradedComparatorTest.java | 3 +- .../model/map/species/DegradedTest.java | 2 +- .../model/map/species/DrugComparatorTest.java | 3 +- .../mapviewer/model/map/species/DrugTest.java | 2 +- .../map/species/ElementComparatorTest.java | 6 +- .../model/map/species/GeneComparatorTest.java | 3 +- .../mapviewer/model/map/species/GeneTest.java | 3 +- .../species/GenericProteinComparatorTest.java | 3 +- .../model/map/species/GenericProteinTest.java | 2 +- .../IonChannelProteinComparatorTest.java | 3 +- .../map/species/IonChannelProteinTest.java | 2 +- .../model/map/species/IonComparatorTest.java | 3 +- .../mapviewer/model/map/species/IonTest.java | 2 +- .../map/species/PhenotypeComparatorTest.java | 3 +- .../model/map/species/PhenotypeTest.java | 3 +- .../map/species/ProteinComparatorTest.java | 3 +- .../model/map/species/ProteinTest.java | 3 +- .../ReceptorProteinComparatorTest.java | 3 +- .../map/species/ReceptorProteinTest.java | 2 +- .../model/map/species/RnaComparatorTest.java | 5 +- .../mapviewer/model/map/species/RnaTest.java | 3 +- .../species/SimpleMoleculeComparatorTest.java | 3 +- .../model/map/species/SimpleMoleculeTest.java | 2 +- .../map/species/SpeciesComparatorTest.java | 7 +- .../model/map/species/SpeciesTest.java | 2 +- .../TruncatedProteinComparatorTest.java | 3 +- .../map/species/TruncatedProteinTest.java | 2 +- .../map/species/UnknownComparatorTest.java | 3 +- .../model/map/species/UnknownTest.java | 2 +- .../map/species/field/AllFieldTests.java | 12 +- .../map/species/field/CodingRegionTest.java | 3 +- .../species/field/ModificationStateTest.java | 56 +- .../field/PositionToCompartmentTest.java | 54 +- .../model/map/species/field/ResidueTest.java | 5 +- .../map/species/field/StructureTest.java | 3 +- .../map/species/field/UniprotRecordTest.java | 3 +- .../map/statistics/AllStatisticsTests.java | 2 +- .../map/statistics/SearchHistoryTest.java | 2 +- .../model/map/statistics/SearchTypeTest.java | 32 +- .../model/security/PrivilegeTypeTest.java | 35 +- .../ConfigurationElementEditTypeTest.java | 37 +- .../user/ConfigurationElementTypeTest.java | 38 +- .../model/user/ConfigurationTest.java | 2 +- .../model/user/UserAnnotationSchemaTest.java | 2 +- .../model/user/UserClassAnnotatorsTest.java | 2 +- .../lcsb/mapviewer/model/user/UserTest.java | 5 +- .../annotator/AnnotatorParameterTest.java | 12 +- .../modelutils/map/AllMapUtilTests.java | 4 +- .../modelutils/map/ClassTreeNodeTest.java | 2 +- .../map/RequireAnnotationMapTest.java | 32 +- .../lcsb/mapviewer/wikipathway/Activator.java | 30 +- .../mapviewer/wikipathway/ImportExport.java | 362 ++-- .../wikipathway/XML/BiopaxParser.java | 454 +++-- .../wikipathway/XML/CyclicEdgeException.java | 26 +- .../wikipathway/XML/DataNodeParser.java | 333 ++-- .../wikipathway/XML/EdgeLineParser.java | 132 +- .../mapviewer/wikipathway/XML/EdgeParser.java | 1103 ++++++----- .../wikipathway/XML/ElementGpmlParser.java | 221 ++- .../wikipathway/XML/GPMLToModel.java | 66 +- .../mapviewer/wikipathway/XML/GpmlParser.java | 1258 ++++++------ .../XML/GraphicalPathwayElementParser.java | 112 +- .../XML/InvalidElbowConnectorException.java | 26 +- .../wikipathway/XML/LabelParser.java | 292 +-- .../wikipathway/XML/ModelContructor.java | 207 +- .../wikipathway/XML/ModelToGPML.java | 48 +- .../wikipathway/XML/PointDataParser.java | 89 +- .../wikipathway/XML/ReferenceParser.java | 265 ++- .../wikipathway/XML/ShapeParser.java | 329 ++-- .../wikipathway/XML/StateParser.java | 280 ++- .../XML/UnknownAttributeValueException.java | 30 +- .../XML/UnknownChildClassException.java | 27 +- .../XML/UnknownMergingMethodException.java | 26 +- .../wikipathway/XML/package-info.java | 1 - .../mapviewer/wikipathway/model/DataNode.java | 392 ++-- .../wikipathway/model/Direction.java | 118 +- .../mapviewer/wikipathway/model/Edge.java | 893 ++++----- .../model/GpmlInteractionType.java | 248 +-- .../model/GpmlLineConnectorType.java | 110 +- .../wikipathway/model/GpmlLineType.java | 134 +- .../model/GpmlModificationType.java | 245 ++- .../wikipathway/model/GpmlStateType.java | 139 +- .../mapviewer/wikipathway/model/Graph.java | 1126 ++++++----- .../model/GraphicalPathwayElement.java | 465 ++--- .../mapviewer/wikipathway/model/Group.java | 242 +-- .../wikipathway/model/Interaction.java | 742 ++++--- .../wikipathway/model/InteractionMapping.java | 966 +++++---- .../mapviewer/wikipathway/model/Label.java | 320 +-- .../wikipathway/model/MergeMapping.java | 370 ++-- .../wikipathway/model/PathwayElement.java | 292 ++- .../wikipathway/model/PointData.java | 374 ++-- .../wikipathway/model/ReferenceMapping.java | 510 ++--- .../mapviewer/wikipathway/model/Shape.java | 424 ++-- .../mapviewer/wikipathway/model/State.java | 478 ++--- .../model/UnknownTypeException.java | 26 +- .../wikipathway/model/biopax/BiopaxData.java | 133 +- .../BiopaxOpenControlledVocabulary.java | 129 +- .../model/biopax/BiopaxPublication.java | 319 ++- .../model/biopax/package-info.java | 1 - .../wikipathway/model/package-info.java | 7 +- .../mapviewer/wikipathway/package-info.java | 8 +- .../lcsb/mapviewer/wikipathway/utils/Geo.java | 617 +++--- .../wikipathway/utils/package-info.java | 1 - .../wikipathway/AllWikipathwaysTests.java | 14 +- .../ComplexReactionToModelTest.java | 2 +- .../wikipathway/ReactionElbowsTest.java | 3 +- .../WikipathwaysTestFunctions.java | 43 +- .../wikipathway/XML/AllXmlTests.java | 20 +- .../mapviewer/wikipathway/XML/BugTest.java | 5 +- .../XML/ElementGpmlParserTest.java | 8 +- .../wikipathway/XML/LabelParserTest.java | 2 +- .../wikipathway/XML/ModelContructorTest.java | 3 +- .../wikipathway/XML/ReferenceParserTest.java | 3 +- .../wikipathway/XML/ShapeParserTest.java | 2 +- .../wikipathway/XML/StateParserTest.java | 3 +- .../wikipathway/model/AllModelTests.java | 22 +- .../persist/ApplicationContextLoader.java | 91 +- .../persist/ConfigurationHolder.java | 52 +- .../persist/CustomImplicitNamingStrategy.java | 7 +- .../java/lcsb/mapviewer/persist/DbUtils.java | 15 +- .../persist/SpringApplicationContext.java | 93 +- .../persist/SpringPersistConfig.java | 102 +- .../lcsb/mapviewer/persist/dao/BaseDao.java | 23 +- .../persist/dao/ConfigurationDao.java | 76 +- .../persist/dao/cache/BigFileEntryDao.java | 5 +- .../persist/dao/cache/CacheQueryDao.java | 86 +- .../persist/dao/cache/CacheTypeDao.java | 57 +- .../dao/cache/UploadedFileEntryDao.java | 37 +- .../persist/dao/cache/package-info.java | 1 - .../persist/dao/graphics/PolylineDao.java | 15 +- .../persist/dao/graphics/package-info.java | 1 - .../mapviewer/persist/dao/map/CommentDao.java | 221 +-- .../mapviewer/persist/dao/map/LayoutDao.java | 4 +- .../mapviewer/persist/dao/map/ModelDao.java | 177 +- .../persist/dao/map/ReactionDao.java | 15 +- .../dao/map/layout/ReferenceGenomeDao.java | 35 +- .../layout/ReferenceGenomeGeneMappingDao.java | 15 +- .../persist/dao/map/layout/package-info.java | 1 - .../persist/dao/map/package-info.java | 1 - .../persist/dao/map/species/ElementDao.java | 15 +- .../persist/dao/map/species/package-info.java | 1 - .../dao/map/statistics/SearchHistoryDao.java | 29 +- .../dao/map/statistics/package-info.java | 1 - .../mapviewer/persist/dao/package-info.java | 1 - .../persist/dao/plugin/PluginDao.java | 3 +- .../dao/plugin/PluginDataEntryDao.java | 3 +- .../persist/dao/security/PrivilegeDao.java | 8 +- .../mapviewer/persist/dao/user/UserDao.java | 3 +- .../persist/dao/user/package-info.java | 1 - .../persist/mapper/ArrowTypeDataMapper.java | 62 +- .../persist/mapper/Point2DMapper.java | 34 +- .../persist/mapper/package-info.java | 1 - .../V14_0_0_20190701__bcrypt_passwords.java | 6 +- .../lcsb/mapviewer/persist/package-info.java | 1 - .../persist/ApplicationContextLoaderTest.java | 3 +- .../lcsb/mapviewer/persist/DbUtilsTest.java | 3 +- .../mapviewer/persist/InitialStateTest.java | 4 +- .../persist/PersistTestFunctions.java | 16 +- .../persist/SpringApplicationContextTest.java | 40 +- .../persist/dao/ConfigurationDaoTest.java | 4 +- .../persist/dao/cache/AllCacheDbTests.java | 6 +- .../dao/cache/BigFileEntryDaoTest.java | 3 +- .../persist/dao/cache/CacheQueryDaoTest.java | 3 +- .../dao/cache/UploadedFileEntryDaoTest.java | 2 +- .../dao/graphics/PolylineDataTest.java | 14 +- .../persist/dao/map/CommentDaoTest.java | 5 +- .../persist/dao/map/LayoutDaoTest.java | 3 +- .../persist/dao/map/ModelDaoTest.java | 2 +- .../dao/map/layout/AllLayoutTests.java | 4 +- .../map/layout/ReferenceGenomeDaoTest.java | 2 +- .../ReferenceGenomeGeneMappingDaoTest.java | 2 +- .../map/statistics/SearchHistoryDaoTest.java | 2 +- .../persist/dao/plugin/PluginDaoTest.java | 4 +- .../dao/plugin/PluginDataEntryDaoTest.java | 14 +- .../persist/dao/user/UserDaoTest.java | 3 +- .../mapper/ArrowTypeDataMapperTest.java | 13 +- .../persist/mapper/Point2DMapperTest.java | 4 +- .../java/lcsb/mapviewer/api/BaseRestImpl.java | 47 +- .../api/ContentNegotiationConfig.java | 14 +- .../mapviewer/api/ElementIdentifierType.java | 24 +- .../api/ObjectNotFoundException.java | 48 +- .../lcsb/mapviewer/api/QueryException.java | 48 +- .../mapviewer/api/SpringRestApiConfig.java | 12 +- .../configuration/ConfigurationRestImpl.java | 20 +- .../api/convert/ConvertController.java | 76 +- .../api/convert/ConvertRestImpl.java | 288 ++- .../mapviewer/api/files/FileController.java | 2 +- .../genomics/ReferenceGenomeController.java | 15 +- .../api/genomics/ReferenceGenomeRestImpl.java | 23 +- .../mapviewer/api/mesh/MeshController.java | 7 +- .../lcsb/mapviewer/api/mesh/MeshRestImpl.java | 5 +- .../api/minervanet/MinervaNetController.java | 20 +- .../minervanet/ReportSubmissionException.java | 3 +- .../api/plugins/PluginController.java | 19 +- .../mapviewer/api/plugins/PluginRestImpl.java | 6 +- .../api/projects/ProjectRestImpl.java | 56 +- .../chemicals/ChemicalController.java | 7 +- .../projects/chemicals/ChemicalRestImpl.java | 106 +- .../projects/comments/CommentController.java | 35 +- .../api/projects/drugs/DrugController.java | 7 +- .../api/projects/drugs/DrugRestImpl.java | 9 +- .../api/projects/mirnas/MiRnaRestImpl.java | 35 +- .../api/projects/models/ModelController.java | 23 +- .../api/projects/models/ModelRestImpl.java | 45 +- .../bioEntities/BioEntitiesController.java | 12 +- .../bioEntities/BioEntitiesRestImpl.java | 11 +- .../elements/ElementsController.java | 46 +- .../elements/ElementsRestImpl.java | 206 +- .../reactions/ReactionsController.java | 41 +- .../reactions/ReactionsRestImpl.java | 135 +- .../models/functions/FunctionsController.java | 6 +- .../models/functions/FunctionsRestImpl.java | 21 +- .../parameters/ParametersController.java | 9 +- .../models/parameters/ParametersRestImpl.java | 14 +- .../publications/PublicationsController.java | 42 +- .../publications/PublicationsRestImpl.java | 49 +- .../models/units/UnitsController.java | 6 +- .../projects/models/units/UnitsRestImpl.java | 14 +- .../projects/overlays/OverlayController.java | 3 +- .../api/taxonomy/TaxonomyController.java | 7 +- .../api/taxonomy/TaxonomyRestImpl.java | 3 +- .../mapviewer/api/users/UserController.java | 7 +- .../mapviewer/api/users/UserRestImpl.java | 26 +- .../mapviewer/api/BaseControllerTest.java | 5 +- .../lcsb/mapviewer/api/BaseRestImplTest.java | 2 +- .../lcsb/mapviewer/api/RestTestFunctions.java | 9 +- .../api/SpringRestApiTestConfig.java | 7 +- .../ConfigurationRestImplTest.java | 5 +- .../api/convert/ConvertRestImplTest.java | 5 +- .../mapviewer/api/files/FileRestImplTest.java | 8 +- .../ReferenceGenomeControllerTest.java | 6 +- .../mapviewer/api/mesh/MeshRestImplTest.java | 3 +- .../api/projects/ProjectRestImplTest.java | 4 +- .../chemicals/ChemicalRestImplTest.java | 4 +- .../comments/CommentRestImplTest.java | 5 +- .../api/projects/drugs/DrugRestImplTest.java | 2 +- .../projects/mirnas/MiRnaRestImplTest.java | 2 +- .../projects/models/ModelRestImplTest.java | 6 +- .../BioEntitiesControllerTest.java | 5 +- .../elements/ElementRestImplTest.java | 2 +- .../reactions/ReactionsRestImplTest.java | 4 +- .../functions/FunctionsRestImplTest.java | 9 +- .../PublicationsRestImplTest.java | 18 +- .../overlays/OverlayRestImplTest.java | 2 +- .../mapviewer/api/users/UserRestImplTest.java | 3 +- .../AuthenticationTokenExpireException.java | 16 +- .../services/InvalidTokenException.java | 16 +- .../services/SpringServiceConfig.java | 14 +- .../services/UserAccessException.java | 16 +- .../services/impl/CommentService.java | 157 +- .../services/impl/ConfigurationService.java | 51 +- .../impl/CustomMd5PasswordEncoder.java | 70 +- .../mapviewer/services/impl/FileService.java | 7 +- .../services/impl/LayoutService.java | 628 +++--- .../mapviewer/services/impl/LdapService.java | 52 +- .../services/impl/MiriamService.java | 82 +- .../mapviewer/services/impl/ModelService.java | 81 +- .../services/impl/PrivilegeService.java | 7 +- .../services/impl/ProjectService.java | 542 +++--- .../services/impl/ReferenceGenomeService.java | 48 +- .../services/impl/SearchHistoryService.java | 76 +- .../services/impl/SearchService.java | 476 +++-- .../mapviewer/services/impl/UserService.java | 64 +- .../mapviewer/services/impl/package-info.java | 1 - .../services/interfaces/ILayoutService.java | 268 ++- .../services/interfaces/IMiriamService.java | 32 +- .../interfaces/IReferenceGenomeService.java | 4 +- .../interfaces/ISearchHistoryService.java | 26 +- .../services/interfaces/IUserService.java | 23 +- .../services/interfaces/package-info.java | 1 - .../overlay/AnnotatedObjectTreeRow.java | 555 +++--- .../services/overlay/package-info.java | 1 - .../services/search/DbSearchService.java | 54 +- .../services/search/ElementMatcher.java | 18 +- .../services/search/IDbSearchService.java | 64 +- .../search/chemical/ChemicalService.java | 55 +- .../services/search/drug/DrugService.java | 119 +- .../services/search/mirna/MiRNAService.java | 76 +- .../services/utils/ColorSchemaReader.java | 31 +- .../services/utils/CreateProjectParams.java | 22 +- .../mapviewer/services/utils/EmailSender.java | 38 +- .../utils/InvalidPrivilegeException.java | 26 +- .../utils/ReferenceGenomeExistsException.java | 26 +- .../services/utils/SearchIndexer.java | 318 ++- .../services/utils/data/BuildInLayout.java | 180 +- .../utils/data/ColorSchemaColumn.java | 38 +- .../services/utils/data/ExportColumn.java | 197 +- .../services/utils/data/ExportFileType.java | 64 +- .../services/utils/data/package-info.java | 1 - .../services/utils/package-info.java | 1 - .../services/ServiceTestFunctions.java | 13 +- .../services/SpringServiceTestConfig.java | 9 +- .../impl/CustomMd5PasswordEncoderTest.java | 3 +- .../services/impl/FailServiceMock.java | 16 +- .../services/impl/LayoutServiceTest.java | 7 +- .../services/impl/OkServiceMock.java | 16 +- .../services/impl/ProjectServiceTest.java | 8 +- .../services/search/DbSearchServiceTest.java | 1 - .../services/search/ElementMatcherTest.java | 13 +- .../search/mirna/MiRNAServiceTest.java | 6 +- .../services/utils/ColorSchemaReaderTest.java | 3 +- .../mapviewer/web/bean/utils/CORSFilter.java | 10 +- .../mapviewer/web/bean/utils/CacheFilter.java | 12 +- .../web/bean/utils/CustomFilter.java | 59 +- .../CustomHttpServletResponseWrapper.java | 439 +++-- .../mapviewer/web/bean/utils/StartupBean.java | 10 +- .../bean/utils/VersionResourceHandler.java | 41 +- .../web/bean/utils/XFrameFilter.java | 10 +- .../web/bean/utils/package-info.java | 1 - .../AuthenticationFailureHandlerImpl.java | 11 +- .../AuthenticationSuccessHandlerImpl.java | 6 +- .../config/LdapAuthenticationProvider.java | 4 +- .../config/LocalAuthenticationProvider.java | 12 +- .../web/config/LogoutSuccessHandlerImpl.java | 9 +- .../config/RefreshAuthoritiesInterceptor.java | 23 +- .../web/config/SpringSecurityConfig.java | 12 +- .../mapviewer/web/config/SpringWebConfig.java | 24 +- .../web/config/UserDetailsServiceImpl.java | 2 +- .../web/config/WebAppInitializer.java | 19 +- .../web/converter/MiriamTypeConverter.java | 72 +- .../mapviewer/web/converter/package-info.java | 1 - .../java/lcsb/mapviewer/web/events/Event.java | 1 - .../lcsb/mapviewer/web/events/Listener.java | 94 +- .../web/events/ObjectAddedEvent.java | 48 +- .../web/events/ObjectModifiedEvent.java | 48 +- .../web/events/ObjectRemovedEvent.java | 48 +- .../mapviewer/web/events/package-info.java | 1 - .../ChemicalControllerIntegrationTest.java | 8 +- .../web/CommentControllerIntegrationTest.java | 9 +- ...llerIntegrationTestWithoutTransaction.java | 7 +- ...onfigurationControllerIntegrationTest.java | 15 +- .../web/ControllerIntegrationTest.java | 14 +- .../web/DrugControllerIntegrationTest.java | 8 +- .../web/EndPointsInputValidationTests.java | 8 +- .../web/FileControllerIntegrationTest.java | 6 +- ...llerIntegrationTestWithoutTransaction.java | 4 +- .../web/LdapServiceTestConfiguration.java | 8 +- .../web/MapControllerIntegrationTest.java | 7 +- .../web/MiRnaControllerIntegrationTest.java | 8 +- .../web/OverlayControllerIntegrationTest.java | 22 +- ...llerIntegrationTestWithoutTransaction.java | 9 +- .../web/PluginControllerIntegrationTest.java | 23 +- .../web/ProjectControllerIntegrationTest.java | 11 +- ...ontrollerIntegrationTestForAsyncCalls.java | 12 +- ...PublicationsControllerIntegrationTest.java | 4 +- .../ReactionControllerIntegrationTest.java | 6 +- .../SpringSecurityGeneralIntegrationTest.java | 7 +- .../SpringSecurityLdapIntegrationTest.java | 9 +- .../TaxonomiesControllerIntegrationTest.java | 8 +- ...serControllerAnonymousIntegrationTest.java | 8 +- .../web/UserControllerIntegrationTest.java | 14 +- ...llerIntegrationTestWithoutTransaction.java | 22 +- 1206 files changed, 33651 insertions(+), 36667 deletions(-) diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyAction.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyAction.java index 9d55234612..9f9e088de4 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyAction.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyAction.java @@ -1,18 +1,15 @@ package lcsb.mapviewer.cdplugin.copypaste; -import org.apache.logging.log4j.*; +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 jp.sbi.celldesigner.plugin.*; import lcsb.mapviewer.common.SystemClipboard; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; /** - * CD Plugin action responsible for translating annotation stored in notes to xml - * format stored in annotations. + * CD Plugin action responsible for translating annotation stored in notes to + * xml format stored in annotations. * * @author Piotr Gawron * 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 176851f392..8514450eb4 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 @@ -3,14 +3,13 @@ package lcsb.mapviewer.cdplugin.copypaste; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +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.model.map.*; /** * This abstract class defines common function for {@link CopyAction} and @@ -20,17 +19,16 @@ import lcsb.mapviewer.model.map.MiriamType; * */ public class CopyPasteAbstractAction { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(CopyPasteAbstractAction.class); - /** * Prefix used for serialization/deserialization of {@link MiriamData} to string * stored in system clipboard. */ private static final String PREFIX = "[MIRIAM]"; + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(CopyPasteAbstractAction.class); /** * Serializes {@link MiriamData} into string that will be stored into system diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePlugin.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePlugin.java index c14384bf52..8b881dd562 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePlugin.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePlugin.java @@ -1,10 +1,10 @@ package lcsb.mapviewer.cdplugin.copypaste; -import java.awt.KeyEventDispatcher; -import java.awt.KeyboardFocusManager; +import java.awt.*; import java.awt.event.KeyEvent; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import jp.sbi.celldesigner.MainWindow; import jp.sbi.celldesigner.plugin.CellDesignerPlugin; @@ -94,6 +94,10 @@ public class CopyPastePlugin extends CellDesignerPlugin { }; } + @Override + public void addPluginMenu() { + } + // CHECKSTYLE:OFF @Override public void SBaseAdded(PluginSBase arg0) { @@ -105,28 +109,24 @@ public class CopyPastePlugin extends CellDesignerPlugin { } - @Override - public void SBaseDeleted(PluginSBase arg0) { - } - // CHECKSTYLE:ON @Override - public void addPluginMenu() { + public void SBaseDeleted(PluginSBase arg0) { } @Override - public void modelClosed(PluginSBase arg0) { + public void modelOpened(PluginSBase arg0) { } @Override - public void modelOpened(PluginSBase arg0) { + public void modelSelectChanged(PluginSBase arg0) { } @Override - public void modelSelectChanged(PluginSBase arg0) { + public void modelClosed(PluginSBase arg0) { } diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPluginAction.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPluginAction.java index fa0f5126a9..ac2a954872 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPluginAction.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/CopyPluginAction.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.cdplugin.copypaste; import java.awt.event.ActionEvent; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import jp.sbi.celldesigner.MainWindow; import jp.sbi.celldesigner.plugin.PluginAction; @@ -18,15 +19,13 @@ import jp.sbi.celldesigner.plugin.PluginListOf; public class CopyPluginAction extends PluginAction { /** - * Default class logger. + * */ - private Logger logger = LogManager.getLogger(PasteAction.class.getName()); - + private static final long serialVersionUID = 1L; /** - * + * Default class logger. */ - private static final long serialVersionUID = 1L; - + private Logger logger = LogManager.getLogger(PasteAction.class.getName()); /** * Plugin that access this action. */ 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 2cc400ea97..c200f0e7a0 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 @@ -2,13 +2,10 @@ package lcsb.mapviewer.cdplugin.copypaste; import java.util.Set; -import org.apache.logging.log4j.*; +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 jp.sbi.celldesigner.plugin.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.SystemClipboard; import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PastePluginAction.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PastePluginAction.java index f69c2f31e4..f8ef0d8abf 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PastePluginAction.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/copypaste/PastePluginAction.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.cdplugin.copypaste; import java.awt.event.ActionEvent; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import jp.sbi.celldesigner.MainWindow; import jp.sbi.celldesigner.plugin.PluginAction; @@ -18,13 +19,13 @@ import jp.sbi.celldesigner.plugin.PluginListOf; public class PastePluginAction extends PluginAction { /** - * Default class logger. + * */ - private Logger logger = LogManager.getLogger(PasteAction.class.getName()); + private static final long serialVersionUID = 1L; /** - * + * Default class logger. */ - private static final long serialVersionUID = 1L; + private Logger logger = LogManager.getLogger(PasteAction.class.getName()); /** * Plugin that access this action. */ diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoFrame.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoFrame.java index 050427adde..fc8f9cffa7 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoFrame.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoFrame.java @@ -1,24 +1,13 @@ package lcsb.mapviewer.cdplugin.info; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.GridLayout; -import java.awt.Toolkit; +import java.awt.*; import java.util.ArrayList; import java.util.List; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; +import javax.swing.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; @@ -61,24 +50,20 @@ public final class InfoFrame { * Font size of the caption label. */ private static final int CAPTION_FONT_SIZE = 18; - + /** + * Singleton instance of this class (there can be only one instance of the + * frame). + */ + private static InfoFrame instance = null; /** * Default class logger. */ @SuppressWarnings("unused") private final Logger logger = LogManager.getLogger(InfoFrame.class); - /** * Instance of the JFrame representation of windows. */ private JFrame frame = null; - - /** - * Singleton instance of this class (there can be only one instance of the - * frame). - */ - private static InfoFrame instance = null; - /** * Font used for captions. */ @@ -130,27 +115,6 @@ public final class InfoFrame { return instance; } - /** - * Set visible flag for {@link #frame}. - * - * @param visible - * should the frame be visible or not - */ - public void setVisible(boolean visible) { - frame.setVisible(visible); - } - - /** - * This method assign a set of species to this form. - * - * @param species - * - species to be shown in the form - */ - public void setSpecies(List<PluginSpeciesAlias> species) { - this.species = species; - updateSpecies(); - } - /** * Updates information about species in the form. */ @@ -186,7 +150,7 @@ public final class InfoFrame { /** * This method create a panel for a species with all information to be * presented. - * + * * @param species * CellDesigner species alias * @return {@link JPanel} object with information about species @@ -225,16 +189,26 @@ public final class InfoFrame { /** * Returns info if the frame is visible. - * + * * @return info if the frame is visible */ public boolean isVisible() { return frame.isVisible(); } + /** + * Set visible flag for {@link #frame}. + * + * @param visible + * should the frame be visible or not + */ + public void setVisible(boolean visible) { + frame.setVisible(visible); + } + /** * Sets frame title. - * + * * @param title * title of the frame */ @@ -244,7 +218,7 @@ public final class InfoFrame { /** * Returns frame title. - * + * * @return frame title */ public JFrame getFrame() { @@ -253,7 +227,7 @@ public final class InfoFrame { /** * Set {@link JFrame#defaultCloseOperation}. - * + * * @param type * new {@link JFrame#defaultCloseOperation} value */ @@ -263,7 +237,7 @@ public final class InfoFrame { /** * Set {@link JFrame#setAlwaysOnTop(boolean)}. - * + * * @param always * new {@link JFrame#isAlwaysOnTop()} value */ @@ -275,4 +249,15 @@ public final class InfoFrame { return species; } + /** + * This method assign a set of species to this form. + * + * @param species + * - species to be shown in the form + */ + public void setSpecies(List<PluginSpeciesAlias> species) { + this.species = species; + updateSpecies(); + } + } diff --git a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoPlugin.java b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoPlugin.java index 92fa61f158..9243d57fd8 100644 --- a/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoPlugin.java +++ b/CellDesigner-plugin/src/main/java/lcsb/mapviewer/cdplugin/info/InfoPlugin.java @@ -1,21 +1,16 @@ package lcsb.mapviewer.cdplugin.info; -import java.awt.KeyEventDispatcher; -import java.awt.KeyboardFocusManager; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; +import java.awt.*; +import java.awt.event.*; import java.util.ArrayList; import java.util.List; -import javax.swing.Timer; +import javax.swing.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import jp.sbi.celldesigner.plugin.CellDesignerPlugin; -import jp.sbi.celldesigner.plugin.PluginListOf; -import jp.sbi.celldesigner.plugin.PluginSBase; -import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; +import jp.sbi.celldesigner.plugin.*; /** * This class represent a plugin to CellDesigner that add info text box with @@ -127,6 +122,10 @@ public class InfoPlugin extends CellDesignerPlugin { } } + @Override + public void addPluginMenu() { + } + // CHECKSTYLE:OFF @Override public void SBaseAdded(PluginSBase arg0) { @@ -138,28 +137,24 @@ public class InfoPlugin extends CellDesignerPlugin { } - @Override - public void SBaseDeleted(PluginSBase arg0) { - } - // CHECKSTYLE:ON @Override - public void addPluginMenu() { + public void SBaseDeleted(PluginSBase arg0) { } @Override - public void modelClosed(PluginSBase arg0) { + public void modelOpened(PluginSBase arg0) { } @Override - public void modelOpened(PluginSBase arg0) { + public void modelSelectChanged(PluginSBase arg0) { } @Override - public void modelSelectChanged(PluginSBase arg0) { + public void modelClosed(PluginSBase arg0) { } diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java index e1b62ea3aa..75859c684c 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/CdPluginFunctions.java @@ -6,10 +6,7 @@ import org.apache.logging.log4j.core.LogEvent; import org.junit.*; import org.mockito.Mockito; -import jp.sbi.celldesigner.plugin.PluginListOf; -import jp.sbi.celldesigner.plugin.PluginReaction; -import jp.sbi.celldesigner.plugin.PluginSpecies; -import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; +import jp.sbi.celldesigner.plugin.*; import lcsb.mapviewer.common.MinervaLoggerAppender; import lcsb.mapviewer.common.UnitTestFailedWatcher; diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyActionTest.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyActionTest.java index d4ce487f08..4f16d2b0d1 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyActionTest.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyActionTest.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.cdplugin.copypaste; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.mockito.Mockito; diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePluginTest.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePluginTest.java index ddde8a7350..d4c8612f4a 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePluginTest.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/CopyPastePluginTest.java @@ -38,7 +38,7 @@ public class CopyPastePluginTest extends CdPluginFunctions { PluginListOf list = createPluginListWithSpecies(1); when(copyPastePlugin.getSelectedAllNode()).thenReturn(list); plugin.getCopyPluginAction().setPlugin(copyPastePlugin); - + plugin.createKeyEventDispatcher().dispatchKeyEvent(event); String newData = cp.getClipboardContents(); @@ -60,7 +60,7 @@ public class CopyPastePluginTest extends CdPluginFunctions { PluginListOf list = createPluginListWithSpecies(1); when(copyPastePlugin.getSelectedAllNode()).thenReturn(list); plugin.getPastePluginAction().setPlugin(copyPastePlugin); - + plugin.createKeyEventDispatcher().dispatchKeyEvent(event); } diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/PasteActionTest.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/PasteActionTest.java index 0094f211ba..6027c65078 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/PasteActionTest.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/copypaste/PasteActionTest.java @@ -8,10 +8,7 @@ import static org.mockito.Mockito.times; import org.junit.Test; import org.mockito.Mockito; -import jp.sbi.celldesigner.plugin.PluginListOf; -import jp.sbi.celldesigner.plugin.PluginReaction; -import jp.sbi.celldesigner.plugin.PluginSpecies; -import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; +import jp.sbi.celldesigner.plugin.*; import lcsb.mapviewer.cdplugin.CdPluginFunctions; import lcsb.mapviewer.common.SystemClipboard; diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoFrameTest.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoFrameTest.java index 29dd1d8ba5..fe277a1212 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoFrameTest.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoFrameTest.java @@ -2,11 +2,10 @@ package lcsb.mapviewer.cdplugin.info; import static org.junit.Assert.assertEquals; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; diff --git a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoPluginTest.java b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoPluginTest.java index 6a5190e039..1408d25997 100644 --- a/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoPluginTest.java +++ b/CellDesigner-plugin/src/test/java/lcsb/mapviewer/cdplugin/info/InfoPluginTest.java @@ -5,7 +5,8 @@ import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import jp.sbi.celldesigner.plugin.PluginSpeciesAlias; diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/SpringAnnotationConfig.java b/annotation/src/main/java/lcsb/mapviewer/annotation/SpringAnnotationConfig.java index 5f829e5c27..7b3ec73faf 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/SpringAnnotationConfig.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/SpringAnnotationConfig.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration -@ComponentScan(basePackages = {"lcsb.mapviewer.annotation"}) +@ComponentScan(basePackages = { "lcsb.mapviewer.annotation" }) public class SpringAnnotationConfig { } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCache.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCache.java index ac69ec6114..fc7fa4a55b 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCache.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/ApplicationLevelCache.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.annotation.cache; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.w3c.dom.Node; @@ -48,9 +49,16 @@ public final class ApplicationLevelCache implements QueryCacheInterface { */ private static ApplicationLevelCache cache = null; + /** + * Default constructor. Prevents instantiation. + */ + private ApplicationLevelCache() { + + } + /** * Returns single instance of global application cache (singleton pattern). - * + * * @return single instance of global application cache */ public static ApplicationLevelCache getInstance() { @@ -64,13 +72,6 @@ public final class ApplicationLevelCache implements QueryCacheInterface { } } - /** - * Default constructor. Prevents instantiation. - */ - private ApplicationLevelCache() { - - } - @Override public synchronized Node getXmlNodeByQuery(String query, CacheType type) { Node result = null; @@ -89,7 +90,7 @@ public final class ApplicationLevelCache implements QueryCacheInterface { public synchronized void setCachedQuery(String query, CacheType type, Object object) { setCachedQuery(query, type, object, 0); } - + @Override public synchronized void setCachedQuery(String query, CacheType type, Object object, int validDays) { performMemoryBalance(); @@ -105,6 +106,24 @@ public final class ApplicationLevelCache implements QueryCacheInterface { } } + @Override + public synchronized void clearCache() { + logger.info("Clearing application cache"); + cachedQueryNodes.clear(); + cachedQueryString.clear(); + } + + @Override + public synchronized void removeByQuery(String query, CacheType type) { + cachedQueryString.remove(type.getId() + "\n" + query); + cachedQueryNodes.remove(type.getId() + "\n" + query); + } + + @Override + public void invalidateByQuery(String query, CacheType type) { + removeByQuery(query, type); + } + /** * Method that clean cache if memory usage is too high. */ @@ -129,22 +148,4 @@ public final class ApplicationLevelCache implements QueryCacheInterface { } } - @Override - public synchronized void removeByQuery(String query, CacheType type) { - cachedQueryString.remove(type.getId() + "\n" + query); - cachedQueryNodes.remove(type.getId() + "\n" + query); - } - - @Override - public synchronized void clearCache() { - logger.info("Clearing application cache"); - cachedQueryNodes.clear(); - cachedQueryString.clear(); - } - - @Override - public void invalidateByQuery(String query, CacheType type) { - removeByQuery(query, type); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/BigFileCache.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/BigFileCache.java index 44c205e061..21ba35a919 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/BigFileCache.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/BigFileCache.java @@ -1,34 +1,19 @@ package lcsb.mapviewer.annotation.cache; -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; +import java.io.*; +import java.net.*; import java.util.Calendar; import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; +import java.util.concurrent.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.output.CountingOutputStream; -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.logging.log4j.*; +import org.apache.commons.net.ftp.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.IProgressUpdater; @@ -38,7 +23,6 @@ import lcsb.mapviewer.model.user.ConfigurationElementType; import lcsb.mapviewer.persist.DbUtils; import lcsb.mapviewer.persist.dao.ConfigurationDao; import lcsb.mapviewer.persist.dao.cache.BigFileEntryDao; -import org.springframework.stereotype.Service; /** * Interface for accessing and storing big files. They are stored in local file @@ -254,244 +238,11 @@ public class BigFileCache { return entry; } - /** - * Task that will be able to fetch file from ftp server. - * - * @author Piotr Gawron - * - */ - private final class GetFtpFileTask implements Callable<Void> { - - /** - * Url to the file that we want to download. - * - */ - private String url; - - /** - * Callback listener that will receive information about upload progress. - * - */ - private IProgressUpdater updater; - - /** - * Default constructor. - * - * @param url - * {@link #url} - * @param updater - * {@link #updater} - */ - private GetFtpFileTask(String url, IProgressUpdater updater) { - this.url = url; - if (updater != null) { - this.updater = updater; - } else { - this.updater = new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }; - } - } - - @Override - public Void call() throws Exception { - dbUtils.createSessionForCurrentThread(); - FTPClient ftp = ftpClientFactory.createFtpClient(); - try { - try { - if (getAbsolutePathForFile(url) != null) { - logger.warn("File already downloaded. Skipping..."); - return null; - } - } catch (FileNotFoundException e) { - removeFile(url); - } - - BigFileEntry entry = createEntryForBigFile(url); - entry.setDownloadThreadId(Thread.currentThread().getId()); - bigFileEntryDao.update(entry); - - String server = getDomainName(url); - ftp.connect(server); - // After connection attempt, you should check the reply code to verify - // success. - int reply = ftp.getReplyCode(); - - if (!FTPReply.isPositiveCompletion(reply)) { - throw new IOException("FTP server refused connection."); - } - ftp.enterLocalPassiveMode(); - ftp.login("anonymous", ""); - ftp.setFileType(FTP.BINARY_FILE_TYPE); - - long fileSize = -1; - String remotePath = getFilePath(url); - FTPFile[] files = ftp.listFiles(remotePath); - if (files.length == 1 && files[0].isFile()) { - fileSize = files[0].getSize(); - } - final long size = fileSize; - - OutputStream output = new FileOutputStream(Configuration.getWebAppDir() + entry.getLocalPath()); - CountingOutputStream cos = new CountingOutputStream(output) { - private double lastProgress = -1; - - protected void beforeWrite(int n) { - super.beforeWrite(n); - double newProgress = ((double) getCount()) / ((double) size) * IProgressUpdater.MAX_PROGRESS; - if (newProgress - lastProgress >= IProgressUpdater.PROGRESS_BAR_UPDATE_RESOLUTION) { - lastProgress = newProgress; - entry.setDownloadProgress(lastProgress); - bigFileEntryDao.update(entry); - bigFileEntryDao.commit(); - updater.setProgress(lastProgress); - } - } - }; - ftp.retrieveFile(remotePath, cos); - - entry.setDownloadProgress(IProgressUpdater.MAX_PROGRESS); - bigFileEntryDao.update(entry); - bigFileEntryDao.commit(); - updater.setProgress(IProgressUpdater.MAX_PROGRESS); - - output.close(); - - ftp.logout(); - - return null; - } finally { - bigFileEntryDao.commit(); - // close the transaction for this thread - dbUtils.closeSessionForCurrentThread(); - if (ftp.isConnected()) { - ftp.disconnect(); - } - - } - } - - } - - /** - * Class that describes task of downloading http file. - * - * @author Piotr Gawron - * - */ - private final class GetHttpFileTask implements Callable<Void> { - - /** - * Url to the file that we want to download. - * - */ - private String url; - - /** - * Callback listener that will receive information about upload progress. - * - */ - private IProgressUpdater updater; - - /** - * Default constructor. - * - * @param url - * {@link #url} - * @param updater - * {@link #updater} - */ - private GetHttpFileTask(String url, IProgressUpdater updater) { - this.url = url; - if (updater != null) { - this.updater = updater; - } else { - this.updater = new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }; - } - } - - @Override - public Void call() throws Exception { - dbUtils.createSessionForCurrentThread(); - BufferedInputStream in = null; - CountingOutputStream cos = null; - try { - try { - if (getAbsolutePathForFile(url) != null) { - logger.warn("File already downloaded. Skipping..."); - return null; - } - } catch (FileNotFoundException e) { - removeFile(url); - } - BigFileEntry entry = createEntryForBigFile(url); - entry.setDownloadThreadId(Thread.currentThread().getId()); - bigFileEntryDao.update(entry); - - final long size = getRemoteHttpFileSize(url); - - OutputStream output = new FileOutputStream(Configuration.getWebAppDir() + entry.getLocalPath()); - cos = new CountingOutputStream(output) { - private double lastProgress = -1; - - protected void beforeWrite(int n) { - super.beforeWrite(n); - double newProgress = ((double) getCount()) / ((double) size) * IProgressUpdater.MAX_PROGRESS; - if (newProgress - lastProgress >= IProgressUpdater.PROGRESS_BAR_UPDATE_RESOLUTION) { - lastProgress = newProgress; - entry.setDownloadProgress(lastProgress); - bigFileEntryDao.update(entry); - bigFileEntryDao.commit(); - updater.setProgress(lastProgress); - } - } - }; - URL website = new URL(url); - in = new BufferedInputStream(website.openStream()); - - final byte[] data = new byte[DOWNLOAD_BUFFER_SIZE]; - int count; - while ((count = in.read(data, 0, DOWNLOAD_BUFFER_SIZE)) != -1) { - cos.write(data, 0, count); - } - - entry.setDownloadProgress(IProgressUpdater.MAX_PROGRESS); - bigFileEntryDao.update(entry); - bigFileEntryDao.commit(); - updater.setProgress(IProgressUpdater.MAX_PROGRESS); - - output.close(); - - return null; - } catch (Exception e) { - logger.error(e, e); - throw e; - } finally { - bigFileEntryDao.commit(); - // close the transaction for this thread - dbUtils.closeSessionForCurrentThread(); - // close opened streams - if (in != null) { - in.close(); - } - if (cos != null) { - cos.close(); - } - } - } - } - /** * Checks if local file for given url is up to date. The check is based on file * size check (ftp doesn't provide checksums for files, so we cannot compare it * differently without downloading file). - * + * * @param url * url to ftp file * @return <code>true</code> if file is up to date, <code>false</code> in other @@ -513,7 +264,7 @@ public class BigFileCache { /** * Checks if local file fetched from ftp is up to date. - * + * * @param url * url to remote file * @return <code>true</code> if file is up to date, <code>false</code> otherwise @@ -571,7 +322,7 @@ public class BigFileCache { /** * Checks if local file fetched from http is up to date. - * + * * @param url * url to remote file * @return <code>true</code> if file is up to date, <code>false</code> otherwise @@ -600,7 +351,7 @@ public class BigFileCache { /** * Returns size of the remote file access via http url. - * + * * @param url * url address to the file * @return size of the remote file access via http url @@ -626,7 +377,7 @@ public class BigFileCache { /** * Removes local file copy of a file given in a parameter. - * + * * @param url * ftp url of a file * @throws IOException @@ -649,105 +400,18 @@ public class BigFileCache { } /** - * Task that describes updating file from ftp. - * - * @author Piotr Gawron + * Updates local copy of a file that can be downloaded from a url given in + * parameter. * - */ - private final class UpdateFtpFileTask implements Callable<Void> { - - /** - * Url to file. - */ - private String url; - - /** - * Default constructor. - * - * @param url - * {@link #url} - */ - private UpdateFtpFileTask(String url) { - this.url = url; - } - - @Override - public Void call() throws Exception { - dbUtils.createSessionForCurrentThread(); - FTPClient ftp = ftpClientFactory.createFtpClient(); - try { - BigFileEntry localEntryCopy = bigFileEntryDao.getByUrl(url); - localEntryCopy.setDownloadThreadId(Thread.currentThread().getId()); - localEntryCopy.setDownloadProgress(0.0); - bigFileEntryDao.update(localEntryCopy); - - // remove current version - new File(Configuration.getWebAppDir() + localEntryCopy.getLocalPath()).delete(); - - String server = getDomainName(url); - ftp.connect(server); - // After connection attempt, you should check the reply code to - // verify success. - int reply = ftp.getReplyCode(); - - if (!FTPReply.isPositiveCompletion(reply)) { - throw new IOException("FTP server refused connection."); - } - ftp.enterLocalPassiveMode(); - ftp.login("anonymous", ""); - ftp.setFileType(FTP.BINARY_FILE_TYPE); - - long fileSize = -1; - String remotePath = getFilePath(url); - FTPFile[] files = ftp.listFiles(remotePath); - if (files.length == 1 && files[0].isFile()) { - fileSize = files[0].getSize(); - } - final long size = fileSize; - - OutputStream output = new FileOutputStream(localEntryCopy.getLocalPath()); - CountingOutputStream cos = new CountingOutputStream(output) { - private double lastProgress = -1; - - protected void beforeWrite(int n) { - super.beforeWrite(n); - double newProgress = ((double) getCount()) / ((double) size) * IProgressUpdater.MAX_PROGRESS; - if (newProgress - lastProgress >= IProgressUpdater.PROGRESS_BAR_UPDATE_RESOLUTION) { - lastProgress = newProgress; - localEntryCopy.setDownloadProgress(lastProgress); - bigFileEntryDao.update(localEntryCopy); - } - } - }; - ftp.retrieveFile(remotePath, cos); - - output.close(); - - ftp.logout(); - return null; - } finally { - dbUtils.closeSessionForCurrentThread(); - if (ftp.isConnected()) { - ftp.disconnect(); - } - } - } - - } - - /** - * Updates local copy of a file that can be downloaded from a url given in - * parameter. - * - * @param url - * url to an ftp file to be updated - * @param async - * <code>true</code> if update should be done asynchronously, - * <code>false</code> otherwise - * @throws IOException - * thrown when there is a problem with accessing remote file - * @throws URISyntaxException - * thrown when url is invalid + * @param url + * url to an ftp file to be updated + * @param async + * <code>true</code> if update should be done asynchronously, + * <code>false</code> otherwise + * @throws IOException + * thrown when there is a problem with accessing remote file + * @throws URISyntaxException + * thrown when url is invalid */ public void updateFile(String url, boolean async) throws URISyntaxException, IOException { if (isLocalFileUpToDate(url)) { @@ -765,7 +429,7 @@ public class BigFileCache { /** * Executes download/update task. - * + * * @param task * task to be executed * @throws URISyntaxException @@ -791,7 +455,7 @@ public class BigFileCache { /** * Returns server domain name from url. - * + * * @param url * url to be processed * @return server domain name from url @@ -810,7 +474,7 @@ public class BigFileCache { /** * Returns path to file on server without server domain name from url. - * + * * @param url * url to be processed * @return path to file on server without server domain name from url @@ -824,7 +488,7 @@ public class BigFileCache { /** * Returns simple file name from url. - * + * * @param url * url to be processed * @return simple file name from url @@ -838,7 +502,7 @@ public class BigFileCache { /** * Checks if the file identified by url is cached. - * + * * @param sourceUrl * url that identifies file * @return <code>true</code> if the file is cached, <code>false</code> otherwise @@ -870,7 +534,7 @@ public class BigFileCache { /** * Return number of tasks that are executed or are waiting for execution. - * + * * @return number of tasks that are executed or are waiting for execution */ public int getDownloadThreadCount() { @@ -906,4 +570,324 @@ public class BigFileCache { this.configurationDao = configurationDao; } + /** + * Task that will be able to fetch file from ftp server. + * + * @author Piotr Gawron + * + */ + private final class GetFtpFileTask implements Callable<Void> { + + /** + * Url to the file that we want to download. + * + */ + private String url; + + /** + * Callback listener that will receive information about upload progress. + * + */ + private IProgressUpdater updater; + + /** + * Default constructor. + * + * @param url + * {@link #url} + * @param updater + * {@link #updater} + */ + private GetFtpFileTask(String url, IProgressUpdater updater) { + this.url = url; + if (updater != null) { + this.updater = updater; + } else { + this.updater = new IProgressUpdater() { + @Override + public void setProgress(double progress) { + } + }; + } + } + + @Override + public Void call() throws Exception { + dbUtils.createSessionForCurrentThread(); + FTPClient ftp = ftpClientFactory.createFtpClient(); + try { + try { + if (getAbsolutePathForFile(url) != null) { + logger.warn("File already downloaded. Skipping..."); + return null; + } + } catch (FileNotFoundException e) { + removeFile(url); + } + + BigFileEntry entry = createEntryForBigFile(url); + entry.setDownloadThreadId(Thread.currentThread().getId()); + bigFileEntryDao.update(entry); + + String server = getDomainName(url); + ftp.connect(server); + // After connection attempt, you should check the reply code to verify + // success. + int reply = ftp.getReplyCode(); + + if (!FTPReply.isPositiveCompletion(reply)) { + throw new IOException("FTP server refused connection."); + } + ftp.enterLocalPassiveMode(); + ftp.login("anonymous", ""); + ftp.setFileType(FTP.BINARY_FILE_TYPE); + + long fileSize = -1; + String remotePath = getFilePath(url); + FTPFile[] files = ftp.listFiles(remotePath); + if (files.length == 1 && files[0].isFile()) { + fileSize = files[0].getSize(); + } + final long size = fileSize; + + OutputStream output = new FileOutputStream(Configuration.getWebAppDir() + entry.getLocalPath()); + CountingOutputStream cos = new CountingOutputStream(output) { + private double lastProgress = -1; + + protected void beforeWrite(int n) { + super.beforeWrite(n); + double newProgress = ((double) getCount()) / ((double) size) * IProgressUpdater.MAX_PROGRESS; + if (newProgress - lastProgress >= IProgressUpdater.PROGRESS_BAR_UPDATE_RESOLUTION) { + lastProgress = newProgress; + entry.setDownloadProgress(lastProgress); + bigFileEntryDao.update(entry); + bigFileEntryDao.commit(); + updater.setProgress(lastProgress); + } + } + }; + ftp.retrieveFile(remotePath, cos); + + entry.setDownloadProgress(IProgressUpdater.MAX_PROGRESS); + bigFileEntryDao.update(entry); + bigFileEntryDao.commit(); + updater.setProgress(IProgressUpdater.MAX_PROGRESS); + + output.close(); + + ftp.logout(); + + return null; + } finally { + bigFileEntryDao.commit(); + // close the transaction for this thread + dbUtils.closeSessionForCurrentThread(); + if (ftp.isConnected()) { + ftp.disconnect(); + } + + } + } + + } + + /** + * Class that describes task of downloading http file. + * + * @author Piotr Gawron + * + */ + private final class GetHttpFileTask implements Callable<Void> { + + /** + * Url to the file that we want to download. + * + */ + private String url; + + /** + * Callback listener that will receive information about upload progress. + * + */ + private IProgressUpdater updater; + + /** + * Default constructor. + * + * @param url + * {@link #url} + * @param updater + * {@link #updater} + */ + private GetHttpFileTask(String url, IProgressUpdater updater) { + this.url = url; + if (updater != null) { + this.updater = updater; + } else { + this.updater = new IProgressUpdater() { + @Override + public void setProgress(double progress) { + } + }; + } + } + + @Override + public Void call() throws Exception { + dbUtils.createSessionForCurrentThread(); + BufferedInputStream in = null; + CountingOutputStream cos = null; + try { + try { + if (getAbsolutePathForFile(url) != null) { + logger.warn("File already downloaded. Skipping..."); + return null; + } + } catch (FileNotFoundException e) { + removeFile(url); + } + BigFileEntry entry = createEntryForBigFile(url); + entry.setDownloadThreadId(Thread.currentThread().getId()); + bigFileEntryDao.update(entry); + + final long size = getRemoteHttpFileSize(url); + + OutputStream output = new FileOutputStream(Configuration.getWebAppDir() + entry.getLocalPath()); + cos = new CountingOutputStream(output) { + private double lastProgress = -1; + + protected void beforeWrite(int n) { + super.beforeWrite(n); + double newProgress = ((double) getCount()) / ((double) size) * IProgressUpdater.MAX_PROGRESS; + if (newProgress - lastProgress >= IProgressUpdater.PROGRESS_BAR_UPDATE_RESOLUTION) { + lastProgress = newProgress; + entry.setDownloadProgress(lastProgress); + bigFileEntryDao.update(entry); + bigFileEntryDao.commit(); + updater.setProgress(lastProgress); + } + } + }; + URL website = new URL(url); + in = new BufferedInputStream(website.openStream()); + + final byte[] data = new byte[DOWNLOAD_BUFFER_SIZE]; + int count; + while ((count = in.read(data, 0, DOWNLOAD_BUFFER_SIZE)) != -1) { + cos.write(data, 0, count); + } + + entry.setDownloadProgress(IProgressUpdater.MAX_PROGRESS); + bigFileEntryDao.update(entry); + bigFileEntryDao.commit(); + updater.setProgress(IProgressUpdater.MAX_PROGRESS); + + output.close(); + + return null; + } catch (Exception e) { + logger.error(e, e); + throw e; + } finally { + bigFileEntryDao.commit(); + // close the transaction for this thread + dbUtils.closeSessionForCurrentThread(); + // close opened streams + if (in != null) { + in.close(); + } + if (cos != null) { + cos.close(); + } + } + } + } + + /** + * Task that describes updating file from ftp. + * + * @author Piotr Gawron + * + */ + private final class UpdateFtpFileTask implements Callable<Void> { + + /** + * Url to file. + */ + private String url; + + /** + * Default constructor. + * + * @param url + * {@link #url} + */ + private UpdateFtpFileTask(String url) { + this.url = url; + } + + @Override + public Void call() throws Exception { + dbUtils.createSessionForCurrentThread(); + FTPClient ftp = ftpClientFactory.createFtpClient(); + try { + BigFileEntry localEntryCopy = bigFileEntryDao.getByUrl(url); + localEntryCopy.setDownloadThreadId(Thread.currentThread().getId()); + localEntryCopy.setDownloadProgress(0.0); + bigFileEntryDao.update(localEntryCopy); + + // remove current version + new File(Configuration.getWebAppDir() + localEntryCopy.getLocalPath()).delete(); + + String server = getDomainName(url); + ftp.connect(server); + // After connection attempt, you should check the reply code to + // verify success. + int reply = ftp.getReplyCode(); + + if (!FTPReply.isPositiveCompletion(reply)) { + throw new IOException("FTP server refused connection."); + } + ftp.enterLocalPassiveMode(); + ftp.login("anonymous", ""); + ftp.setFileType(FTP.BINARY_FILE_TYPE); + + long fileSize = -1; + String remotePath = getFilePath(url); + FTPFile[] files = ftp.listFiles(remotePath); + if (files.length == 1 && files[0].isFile()) { + fileSize = files[0].getSize(); + } + final long size = fileSize; + + OutputStream output = new FileOutputStream(localEntryCopy.getLocalPath()); + CountingOutputStream cos = new CountingOutputStream(output) { + private double lastProgress = -1; + + protected void beforeWrite(int n) { + super.beforeWrite(n); + double newProgress = ((double) getCount()) / ((double) size) * IProgressUpdater.MAX_PROGRESS; + if (newProgress - lastProgress >= IProgressUpdater.PROGRESS_BAR_UPDATE_RESOLUTION) { + lastProgress = newProgress; + localEntryCopy.setDownloadProgress(lastProgress); + bigFileEntryDao.update(localEntryCopy); + } + } + }; + ftp.retrieveFile(remotePath, cos); + + output.close(); + + ftp.logout(); + return null; + } finally { + dbUtils.closeSessionForCurrentThread(); + if (ftp.isConnected()) { + ftp.disconnect(); + } + } + } + + } + } \ No newline at end of file diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CachableInterface.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CachableInterface.java index 53b8eef6c2..01b15a9d52 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CachableInterface.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CachableInterface.java @@ -25,35 +25,6 @@ public abstract class CachableInterface { * Default class logger. */ private static Logger logger = LogManager.getLogger(CachableInterface.class); - - /** - * Refresh cache data from original source. - * - * @param query - * text used to identify the resource - * @return newly obtained data from the source - * @throws SourceNotAvailable - * thrown when original source is unavailable - */ - public Object refreshCacheQuery(Object query) throws SourceNotAvailable { - String result = null; - try { - if (query instanceof String) { - String name = (String) query; - if (name.startsWith("http")) { - result = getWebPageContent(name); - } else { - throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\""); - } - } else { - throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); - } - } catch (IOException e) { - throw new SourceNotAvailable(e); - } - return result; - } - /** * String containing class name of the class that extends * {@link CachableInterface}. String name is used because cache layer doesn't @@ -61,24 +32,20 @@ public abstract class CachableInterface { * it. */ private String cacheIdentifier; - /** * Type of the cache elements associated with this interface. */ private CacheType cacheType; - /** * Cache mechanism used to speed up computation. */ @Autowired private GeneralCacheInterface cache; - /** * Cache mechanism used to speed up computation. */ @Autowired private CacheTypeDao cacheTypeDao; - /** * This object downloads web pages. */ @@ -86,7 +53,7 @@ public abstract class CachableInterface { /** * Default constructor. - * + * * @param clazz * type that defines this interface */ @@ -94,6 +61,34 @@ public abstract class CachableInterface { this.cacheIdentifier = clazz.getCanonicalName(); } + /** + * Refresh cache data from original source. + * + * @param query + * text used to identify the resource + * @return newly obtained data from the source + * @throws SourceNotAvailable + * thrown when original source is unavailable + */ + public Object refreshCacheQuery(Object query) throws SourceNotAvailable { + String result = null; + try { + if (query instanceof String) { + String name = (String) query; + if (name.startsWith("http")) { + result = getWebPageContent(name); + } else { + throw new InvalidArgumentException("Don't know what to do with string \"" + query + "\""); + } + } else { + throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); + } + } catch (IOException e) { + throw new SourceNotAvailable(e); + } + return result; + } + /** * Puts some string value into cache. * diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CacheException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CacheException.java index b171e2a1cc..1f3701d9b0 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CacheException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/CacheException.java @@ -7,19 +7,19 @@ package lcsb.mapviewer.annotation.cache; * */ public class CacheException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor receives some kind of message. - * - * @param string - * message associated with exception - */ - public CacheException(final String string) { - super(string); - } + /** + * Constructor receives some kind of message. + * + * @param string + * message associated with exception + */ + public CacheException(final String string) { + super(string); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/FtpClientFactory.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/FtpClientFactory.java index 1d18378679..38ad4b0141 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/FtpClientFactory.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/FtpClientFactory.java @@ -10,12 +10,12 @@ import org.apache.commons.net.ftp.FTPClient; */ public class FtpClientFactory { - /** - * Creates new instance of {@link FTPClient}. - * - * @return new instance of {@link FTPClient} - */ - public FTPClient createFtpClient() { - return new FTPClient(); - } + /** + * Creates new instance of {@link FTPClient}. + * + * @return new instance of {@link FTPClient} + */ + public FTPClient createFtpClient() { + return new FTPClient(); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCache.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCache.java index 360a50c391..97031ec889 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCache.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCache.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.annotation.cache; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @@ -48,16 +49,6 @@ public class GeneralCache implements GeneralCacheInterface { this.cache2 = cache2; } - @Override - public void clearCache() { - if (cache1 != null) { - cache1.clearCache(); - } - if (cache2 != null) { - cache2.clearCache(); - } - } - @Override public Node getXmlNodeByQuery(String query, CacheType type) { if (type == null) { @@ -116,6 +107,16 @@ public class GeneralCache implements GeneralCacheInterface { } } + @Override + public void clearCache() { + if (cache1 != null) { + cache1.clearCache(); + } + if (cache2 != null) { + cache2.clearCache(); + } + } + @Override public void removeByQuery(String query, CacheType type) { if (type == null) { diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusion.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusion.java index 1a82107082..f0c2863a39 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusion.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/GeneralCacheWithExclusion.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.annotation.cache; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -74,7 +75,7 @@ public class GeneralCacheWithExclusion implements GeneralCacheInterface { public void setCachedQuery(String identifier, CacheType type, Object value) { cache.setCachedQuery(identifier, type, value); } - + @Override public void setCachedQuery(String identifier, CacheType type, Object value, int validDays) { cache.setCachedQuery(identifier, type, value, validDays); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java index 5d5059a89a..de3f74fdbc 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCache.java @@ -1,19 +1,12 @@ package lcsb.mapviewer.annotation.cache; -import java.util.Calendar; -import java.util.Collection; -import java.util.LinkedList; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; +import java.util.*; +import java.util.concurrent.*; import javax.annotation.PostConstruct; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -47,6 +40,248 @@ import lcsb.mapviewer.persist.dao.cache.CacheQueryDao; @Service public class PermanentDatabaseLevelCache implements PermanentDatabaseLevelCacheInterface, ApplicationContextAware { + /** + * Spring application context. + */ + private static ApplicationContext applicationContext; + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(PermanentDatabaseLevelCache.class); + /** + * Data access object for query entries accessed by string key. + */ + private CacheQueryDao cacheQueryDao; + /** + * Utility that help to manage the sessions in custom multithreaded + * implementation. + */ + private DbUtils dbUtils; + /** + * Service used for executing database tasks in separate thread. + */ + private ExecutorService service; + /** + * This service is used for execution and queue of the refresh entries in the + * database. + */ + private ExecutorService cacheRefreshService; + + @Autowired + public PermanentDatabaseLevelCache(CacheQueryDao cacheQueryDao, DbUtils dbUtils) { + this.cacheQueryDao = cacheQueryDao; + this.dbUtils = dbUtils; + } + + /** + * http://forum.spring.io/forum/spring-projects/aop/52011-need-to-unwrap-a-proxy-to-get-the-object-being-proxied + * + * @param bean + * @return + * @throws Exception + */ + private final Object unwrapProxy(Object bean) throws Exception { + + /* + * If the given object is a proxy, set the return value as the object being + * proxied, otherwise return the given object. + */ + if (AopUtils.isAopProxy(bean) && bean instanceof Advised) { + + Advised advised = (Advised) bean; + + bean = advised.getTargetSource().getTarget(); + } + + return bean; + } + + /** + * Post init spring method used for initialization of {@link #service} used for + * execution of db tasks. + */ + @PostConstruct + public void init() { + // the executor is a daemon thread so that it will get killed automatically + // when the main program exits + service = Executors.newScheduledThreadPool(1, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }); + cacheRefreshService = Executors.newScheduledThreadPool(1, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }); + + // put in the queue empty task to make sure that everything was initialized + // (additional managing thread was created) + service.submit(new Callable<Object>() { + @Override + public Object call() throws Exception { + return null; + } + }); + cacheRefreshService.submit(new Callable<Object>() { + @Override + public Object call() throws Exception { + return null; + } + }); + } + + @Override + public Node getXmlNodeByQuery(String query, CacheType type) { + final Future<CacheQuery> task = service.submit(new QueryTask(query, type)); + CacheQuery entry = executeTask(task); + + if (entry == null) { + return null; + } + try { + Document document = XmlParser.getXmlDocumentFromString(entry.getValue()); + Calendar currentDate = Calendar.getInstance(); + if (currentDate.after(entry.getExpires())) { + cacheRefreshService.submit(new RefreshTask(query, type)); + } + Node result = null; + if (document != null) { + result = document.getFirstChild(); + } + return result; + } catch (InvalidXmlSchemaException e) { + logger.warn("Invalid xml for query: " + query); + logger.warn("xml: " + entry.getValue()); + removeByQuery(query, type); + return null; + } + } + + @Override + public String getStringByQuery(String query, CacheType type) { + Calendar currentDate = Calendar.getInstance(); + final Future<CacheQuery> task = service.submit(new QueryTask(query, type)); + CacheQuery entry = executeTask(task); + if (entry == null) { + return null; + } + if (currentDate.before(entry.getExpires())) { + return entry.getValue(); + } else { + cacheRefreshService.submit(new RefreshTask(query, type)); + return entry.getValue(); + } + } + + @Override + public void setCachedQuery(String query, CacheType type, Object object) { + setCachedQuery(query, type, object, type.getValidity()); + } + + @Override + public void setCachedQuery(String query, CacheType type, Object object, int validDays) { + String value = null; + if (object instanceof String) { + value = (String) object; + } else if (object instanceof Node) { + value = XmlParser.nodeToString((Node) object, true); + } else if (object == null) { + value = null; + } else { + throw new CacheException("Unknown object type: " + object.getClass()); + } + if (value == null) { + removeByQuery(query, type); + } else { + final Future<CacheQuery> task = service.submit(new AddTask(query, type, value, validDays)); + executeTask(task); + } + } + + @Override + public void clearCache() { + cacheQueryDao.clearTable(); + } + + @Override + public void removeByQuery(String query, CacheType type) { + final Future<CacheQuery> task = service.submit(new RemoveTask(query, type)); + executeTask(task); + } + + @Override + public void invalidateByQuery(String query, CacheType type) { + final Future<CacheQuery> task = service.submit(new InvalidateTask(query, type)); + executeTask(task); + } + + /** + * Executes and returns result of the task provided in the parameter. This + * method is blocking (it's waiting for the results). + * + * @param task + * task to be executed + * @return value returned by the task + */ + private CacheQuery executeTask(final Future<CacheQuery> task) { + try { + return task.get(); + } catch (InterruptedException e1) { + logger.error(e1, e1); + } catch (ExecutionException e1) { + logger.error(e1, e1); + } + return null; + } + + @Override + public void setApplicationContext(ApplicationContext arg0) { + applicationContext = arg0; + } + + @Override + public int getRefreshPendingQueueSize() { + return ((ScheduledThreadPoolExecutor) cacheRefreshService).getQueue().size(); + } + + @Override + public void waitToFinishTasks() throws InterruptedException, ExecutionException { + Collection<Future<?>> futures = new LinkedList<Future<?>>(); + futures.add(cacheRefreshService.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + return null; + } + })); + futures.add(service.submit(new Callable<Void>() { + @Override + public Void call() throws Exception { + return null; + } + })); + + for (Future<?> future : futures) { + future.get(); + } + } + + @Override + public CacheQueryDao getCacheQueryDao() { + return cacheQueryDao; + } + + @Override + public void setCacheQueryDao(CacheQueryDao cacheQueryDao) { + this.cacheQueryDao = cacheQueryDao; + } + /** * This class represents new thread task for querying database. * @@ -184,29 +419,6 @@ public class PermanentDatabaseLevelCache implements PermanentDatabaseLevelCacheI } - /** - * http://forum.spring.io/forum/spring-projects/aop/52011-need-to-unwrap-a-proxy-to-get-the-object-being-proxied - * - * @param bean - * @return - * @throws Exception - */ - private final Object unwrapProxy(Object bean) throws Exception { - - /* - * If the given object is a proxy, set the return value as the object being - * proxied, otherwise return the given object. - */ - if (AopUtils.isAopProxy(bean) && bean instanceof Advised) { - - Advised advised = (Advised) bean; - - bean = advised.getTargetSource().getTarget(); - } - - return bean; - } - /** * This class represents new thread task for adding entry to database. * @@ -398,228 +610,4 @@ public class PermanentDatabaseLevelCache implements PermanentDatabaseLevelCacheI } - /** - * Spring application context. - */ - private static ApplicationContext applicationContext; - - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(PermanentDatabaseLevelCache.class); - - /** - * Data access object for query entries accessed by string key. - */ - private CacheQueryDao cacheQueryDao; - - /** - * Utility that help to manage the sessions in custom multithreaded - * implementation. - */ - private DbUtils dbUtils; - - /** - * Service used for executing database tasks in separate thread. - */ - private ExecutorService service; - - /** - * This service is used for execution and queue of the refresh entries in the - * database. - */ - private ExecutorService cacheRefreshService; - - @Autowired - public PermanentDatabaseLevelCache(CacheQueryDao cacheQueryDao, DbUtils dbUtils) { - this.cacheQueryDao = cacheQueryDao; - this.dbUtils = dbUtils; - } - - /** - * Post init spring method used for initialization of {@link #service} used for - * execution of db tasks. - */ - @PostConstruct - public void init() { - // the executor is a daemon thread so that it will get killed automatically - // when the main program exits - service = Executors.newScheduledThreadPool(1, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }); - cacheRefreshService = Executors.newScheduledThreadPool(1, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }); - - // put in the queue empty task to make sure that everything was initialized - // (additional managing thread was created) - service.submit(new Callable<Object>() { - @Override - public Object call() throws Exception { - return null; - } - }); - cacheRefreshService.submit(new Callable<Object>() { - @Override - public Object call() throws Exception { - return null; - } - }); - } - - @Override - public void clearCache() { - cacheQueryDao.clearTable(); - } - - @Override - public Node getXmlNodeByQuery(String query, CacheType type) { - final Future<CacheQuery> task = service.submit(new QueryTask(query, type)); - CacheQuery entry = executeTask(task); - - if (entry == null) { - return null; - } - try { - Document document = XmlParser.getXmlDocumentFromString(entry.getValue()); - Calendar currentDate = Calendar.getInstance(); - if (currentDate.after(entry.getExpires())) { - cacheRefreshService.submit(new RefreshTask(query, type)); - } - Node result = null; - if (document != null) { - result = document.getFirstChild(); - } - return result; - } catch (InvalidXmlSchemaException e) { - logger.warn("Invalid xml for query: " + query); - logger.warn("xml: " + entry.getValue()); - removeByQuery(query, type); - return null; - } - } - - @Override - public String getStringByQuery(String query, CacheType type) { - Calendar currentDate = Calendar.getInstance(); - final Future<CacheQuery> task = service.submit(new QueryTask(query, type)); - CacheQuery entry = executeTask(task); - if (entry == null) { - return null; - } - if (currentDate.before(entry.getExpires())) { - return entry.getValue(); - } else { - cacheRefreshService.submit(new RefreshTask(query, type)); - return entry.getValue(); - } - } - - @Override - public void setCachedQuery(String query, CacheType type, Object object) { - setCachedQuery(query, type, object, type.getValidity()); - } - - @Override - public void setCachedQuery(String query, CacheType type, Object object, int validDays) { - String value = null; - if (object instanceof String) { - value = (String) object; - } else if (object instanceof Node) { - value = XmlParser.nodeToString((Node) object, true); - } else if (object == null) { - value = null; - } else { - throw new CacheException("Unknown object type: " + object.getClass()); - } - if (value == null) { - removeByQuery(query, type); - } else { - final Future<CacheQuery> task = service.submit(new AddTask(query, type, value, validDays)); - executeTask(task); - } - } - - @Override - public void removeByQuery(String query, CacheType type) { - final Future<CacheQuery> task = service.submit(new RemoveTask(query, type)); - executeTask(task); - } - - @Override - public void invalidateByQuery(String query, CacheType type) { - final Future<CacheQuery> task = service.submit(new InvalidateTask(query, type)); - executeTask(task); - } - - /** - * Executes and returns result of the task provided in the parameter. This - * method is blocking (it's waiting for the results). - * - * @param task - * task to be executed - * @return value returned by the task - */ - private CacheQuery executeTask(final Future<CacheQuery> task) { - try { - return task.get(); - } catch (InterruptedException e1) { - logger.error(e1, e1); - } catch (ExecutionException e1) { - logger.error(e1, e1); - } - return null; - } - - @Override - public void setApplicationContext(ApplicationContext arg0) { - applicationContext = arg0; - } - - @Override - public int getRefreshPendingQueueSize() { - return ((ScheduledThreadPoolExecutor) cacheRefreshService).getQueue().size(); - } - - @Override - public CacheQueryDao getCacheQueryDao() { - return cacheQueryDao; - } - - @Override - public void setCacheQueryDao(CacheQueryDao cacheQueryDao) { - this.cacheQueryDao = cacheQueryDao; - } - - @Override - public void waitToFinishTasks() throws InterruptedException, ExecutionException { - Collection<Future<?>> futures = new LinkedList<Future<?>>(); - futures.add(cacheRefreshService.submit(new Callable<Void>() { - @Override - public Void call() throws Exception { - return null; - } - })); - futures.add(service.submit(new Callable<Void>() { - @Override - public Void call() throws Exception { - return null; - } - })); - - for (Future<?> future : futures) { - future.get(); - } - } - } \ No newline at end of file diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java index 59099aedab..bea55aba3f 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheInterface.java @@ -23,8 +23,9 @@ public interface PermanentDatabaseLevelCacheInterface extends QueryCacheInterfac /** * Waits for all tasks in the cache to finish (refresh/get/etc). - * @throws ExecutionException - * @throws InterruptedException + * + * @throws ExecutionException + * @throws InterruptedException */ void waitToFinishTasks() throws InterruptedException, ExecutionException; diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/QueryCacheInterface.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/QueryCacheInterface.java index 6c84091a5c..ab8a03536d 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/QueryCacheInterface.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/QueryCacheInterface.java @@ -1,9 +1,9 @@ package lcsb.mapviewer.annotation.cache; -import lcsb.mapviewer.model.cache.CacheType; - import org.w3c.dom.Node; +import lcsb.mapviewer.model.cache.CacheType; + /** * This interface describes general functionality of the cache interface. * @@ -47,7 +47,7 @@ public interface QueryCacheInterface { * value to be stored in the cache */ void setCachedQuery(String identifier, CacheType type, Object value); - + void setCachedQuery(String identifier, CacheType type, Object value, int validDays); /** diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/SourceNotAvailable.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/SourceNotAvailable.java index 29c7bf36fb..771996e563 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/SourceNotAvailable.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/SourceNotAvailable.java @@ -9,41 +9,41 @@ package lcsb.mapviewer.annotation.cache; */ public class SourceNotAvailable extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - public SourceNotAvailable(Exception e) { - super(e); - } + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + public SourceNotAvailable(Exception e) { + super(e); + } - /** - * Constructor receives some kind of message. - * - * @param message - * message associated with exception - */ - public SourceNotAvailable(String message) { - super(message); - } + /** + * Constructor receives some kind of message. + * + * @param message + * message associated with exception + */ + public SourceNotAvailable(String message) { + super(message); + } - /** - * Public constructor with parent exception that was catched. - * - * @param message - * message associated with exception - * @param e - * parent exception - */ - public SourceNotAvailable(String message, Exception e) { - super(message, e); - } + /** + * Public constructor with parent exception that was catched. + * + * @param message + * message associated with exception + * @param e + * parent exception + */ + public SourceNotAvailable(String message, Exception e) { + super(message, e); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/WebPageDownloader.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/WebPageDownloader.java index f22b0530b3..c6302e8ced 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/WebPageDownloader.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/WebPageDownloader.java @@ -1,21 +1,12 @@ package lcsb.mapviewer.annotation.cache; -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.DataOutputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; +import java.io.*; +import java.net.*; +import java.util.concurrent.*; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; @@ -33,159 +24,151 @@ import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; */ public class WebPageDownloader { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(WebPageDownloader.class); - - /** - * Hard timeout (threads are terminated) of http connection that access data - * across Internet. - */ - private static final int HTTP_CONNECTION_TIMEOUT_SEC = 120; - - /** - * How much time should the thread sleep before another try to access the - * web page that thrown INTERNAL SERVER ERROR http response. - */ - private static final int HTTP_INTERNAL_ERROR_RECONNECT_SLEEP_TIME = 2000; - - /** - * How many times should the thread retry to connect to the server after - * receiving INTERNAL SERVER ERROR http response. - */ - private static final int HTTP_INTERNAL_ERROR_RECONNECT_TIMES = 2; - - - - /** - * Returns content of the web page identified by url. - * - * @param accessUrl - * url of a web page - * @return content of the web page identified by url - * @throws IOException - * thrown when there is any problem with accessing webpage - */ - public String getFromNetwork(String accessUrl) throws IOException { - return getFromNetwork(accessUrl, "GET", null); - } - - - /** - * Returns content of the webpage identified by url. The HTTP query is done - * using the provided POST if postData is not null. - * - * - * @param accessUrl - * url of a webpage - * @param httpRequestMethod - * type of HTTP request (GET, POST, PUT, PATCH, DELETE, ...) - * @param data - * string to be sent in the body of the - * @return content of the webpage identified by url - * @throws IOException - * thrown when there is any problem with accessing webpage - */ - public String getFromNetwork(String accessUrl, String httpRequestMethod, String data) throws IOException { - - /** - * Tasks that retrieves content from web page - * - * @author Piotr Gawron - * - */ - class Task implements Callable<String> { - private volatile String result = null; - - @Override - public String call() throws Exception { - int tries = 0; - int code = HttpURLConnection.HTTP_INTERNAL_ERROR; - HttpURLConnection urlConn = null; - - // connect to the server, if HTTP_INTERNAL_ERROR occurred then try to - // reconnect HTTP_INTERNAL_ERROR_RECONNECT_TIMES times - while (code == HttpURLConnection.HTTP_INTERNAL_ERROR || code == HttpURLConnection.HTTP_NOT_FOUND) { - urlConn = openConnection(accessUrl); - urlConn.addRequestProperty("User-Agent", "minerva-framework"); - - urlConn.setRequestMethod(httpRequestMethod); - if (data != null) { - urlConn.setDoOutput(true); - DataOutputStream wr = new DataOutputStream(urlConn.getOutputStream()); - wr.writeBytes(data); - wr.close(); - } - - try { - urlConn.connect(); - code = urlConn.getResponseCode(); - } catch (FileNotFoundException e) { - code = HttpURLConnection.HTTP_NOT_FOUND; - } catch (IOException e) { - code = HttpURLConnection.HTTP_INTERNAL_ERROR; - } - tries++; - if (tries > HTTP_INTERNAL_ERROR_RECONNECT_TIMES) { - break; - } - if (code == HttpURLConnection.HTTP_INTERNAL_ERROR || code == HttpURLConnection.HTTP_NOT_FOUND) { - logger.debug("Problem with webpage: " + accessUrl); - logger.debug("Retrying: " + accessUrl); - try { - Thread.sleep(HTTP_INTERNAL_ERROR_RECONNECT_SLEEP_TIME); - } catch (InterruptedException e) { - } - } - } - try { - BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); - result = IOUtils.toString(in); - } catch (IOException e) { - if (e.getClass().equals(IOException.class) || e.getClass().equals(FileNotFoundException.class)) { - throw new WrongResponseCodeIOException(e, code); - } else { - throw e; - } - } - return result; - } - - } - - ExecutorService executor = Executors.newSingleThreadExecutor(); - Future<String> future = executor.submit(new Task()); - - try { - String result = future.get(HTTP_CONNECTION_TIMEOUT_SEC, TimeUnit.SECONDS); - executor.shutdownNow(); - return result; - } catch (Exception e) { - if (e.getCause() instanceof IOException) { - throw (IOException) e.getCause(); - } - throw new IOException("Problem with accessing webpage: " + accessUrl, e); - } - } - - /** - * Opens {@link HttpURLConnection connection} to the url given in the - * argument. - * - * @param accessUrl - * url to the web page - * @return {@link HttpURLConnection connection} to the url given in the - * argument - * @throws MalformedURLException - * thrown when url is invalid - * @throws IOException - * thrown when there is problem with opening connection - */ - HttpURLConnection openConnection(String accessUrl) throws MalformedURLException, IOException { - URL url = new URL(accessUrl); - HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); - return urlConn; - } + /** + * Hard timeout (threads are terminated) of http connection that access data + * across Internet. + */ + private static final int HTTP_CONNECTION_TIMEOUT_SEC = 120; + /** + * How much time should the thread sleep before another try to access the web + * page that thrown INTERNAL SERVER ERROR http response. + */ + private static final int HTTP_INTERNAL_ERROR_RECONNECT_SLEEP_TIME = 2000; + /** + * How many times should the thread retry to connect to the server after + * receiving INTERNAL SERVER ERROR http response. + */ + private static final int HTTP_INTERNAL_ERROR_RECONNECT_TIMES = 2; + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(WebPageDownloader.class); + + /** + * Returns content of the web page identified by url. + * + * @param accessUrl + * url of a web page + * @return content of the web page identified by url + * @throws IOException + * thrown when there is any problem with accessing webpage + */ + public String getFromNetwork(String accessUrl) throws IOException { + return getFromNetwork(accessUrl, "GET", null); + } + + /** + * Returns content of the webpage identified by url. The HTTP query is done + * using the provided POST if postData is not null. + * + * + * @param accessUrl + * url of a webpage + * @param httpRequestMethod + * type of HTTP request (GET, POST, PUT, PATCH, DELETE, ...) + * @param data + * string to be sent in the body of the + * @return content of the webpage identified by url + * @throws IOException + * thrown when there is any problem with accessing webpage + */ + public String getFromNetwork(String accessUrl, String httpRequestMethod, String data) throws IOException { + + /** + * Tasks that retrieves content from web page + * + * @author Piotr Gawron + * + */ + class Task implements Callable<String> { + private volatile String result = null; + + @Override + public String call() throws Exception { + int tries = 0; + int code = HttpURLConnection.HTTP_INTERNAL_ERROR; + HttpURLConnection urlConn = null; + + // connect to the server, if HTTP_INTERNAL_ERROR occurred then try to + // reconnect HTTP_INTERNAL_ERROR_RECONNECT_TIMES times + while (code == HttpURLConnection.HTTP_INTERNAL_ERROR || code == HttpURLConnection.HTTP_NOT_FOUND) { + urlConn = openConnection(accessUrl); + urlConn.addRequestProperty("User-Agent", "minerva-framework"); + + urlConn.setRequestMethod(httpRequestMethod); + if (data != null) { + urlConn.setDoOutput(true); + DataOutputStream wr = new DataOutputStream(urlConn.getOutputStream()); + wr.writeBytes(data); + wr.close(); + } + + try { + urlConn.connect(); + code = urlConn.getResponseCode(); + } catch (FileNotFoundException e) { + code = HttpURLConnection.HTTP_NOT_FOUND; + } catch (IOException e) { + code = HttpURLConnection.HTTP_INTERNAL_ERROR; + } + tries++; + if (tries > HTTP_INTERNAL_ERROR_RECONNECT_TIMES) { + break; + } + if (code == HttpURLConnection.HTTP_INTERNAL_ERROR || code == HttpURLConnection.HTTP_NOT_FOUND) { + logger.debug("Problem with webpage: " + accessUrl); + logger.debug("Retrying: " + accessUrl); + try { + Thread.sleep(HTTP_INTERNAL_ERROR_RECONNECT_SLEEP_TIME); + } catch (InterruptedException e) { + } + } + } + try { + BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); + result = IOUtils.toString(in); + } catch (IOException e) { + if (e.getClass().equals(IOException.class) || e.getClass().equals(FileNotFoundException.class)) { + throw new WrongResponseCodeIOException(e, code); + } else { + throw e; + } + } + return result; + } + + } + + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future<String> future = executor.submit(new Task()); + + try { + String result = future.get(HTTP_CONNECTION_TIMEOUT_SEC, TimeUnit.SECONDS); + executor.shutdownNow(); + return result; + } catch (Exception e) { + if (e.getCause() instanceof IOException) { + throw (IOException) e.getCause(); + } + throw new IOException("Problem with accessing webpage: " + accessUrl, e); + } + } + + /** + * Opens {@link HttpURLConnection connection} to the url given in the argument. + * + * @param accessUrl + * url to the web page + * @return {@link HttpURLConnection connection} to the url given in the argument + * @throws MalformedURLException + * thrown when url is invalid + * @throws IOException + * thrown when there is problem with opening connection + */ + HttpURLConnection openConnection(String accessUrl) throws MalformedURLException, IOException { + URL url = new URL(accessUrl); + HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); + return urlConn; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/XmlSerializer.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/XmlSerializer.java index 3f4189908b..c9ccf48fb3 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/XmlSerializer.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/XmlSerializer.java @@ -2,13 +2,11 @@ package lcsb.mapviewer.annotation.cache; import java.io.StringWriter; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; +import javax.xml.bind.*; import org.apache.commons.lang3.SerializationException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; /** @@ -21,91 +19,91 @@ import org.w3c.dom.Node; * type of the object to serialize */ public class XmlSerializer<T> { - - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(XmlSerializer.class); - /** - * Class of the object that DAO works on. - */ - private Class<? extends T> clazz; + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(XmlSerializer.class); - /** - * Java Architecture for XML Binding (JAXB) class that allows transforming T - * object into xml. - */ - private Marshaller jaxbMarshaller; + /** + * Class of the object that DAO works on. + */ + private Class<? extends T> clazz; - /** - * Java Architecture for XML Binding (JAXB) class that allows transforming xml - * describing T into T object. - */ - private Unmarshaller jaxbUnmarshaller; + /** + * Java Architecture for XML Binding (JAXB) class that allows transforming T + * object into xml. + */ + private Marshaller jaxbMarshaller; - /** - * Default constructor. - * - * @param theClass - * class of the object that DAO will work on - */ - public XmlSerializer(Class<? extends T> theClass) { - this.clazz = theClass; - try { - JAXBContext jaxbContext; - jaxbContext = JAXBContext.newInstance(clazz); - jaxbMarshaller = jaxbContext.createMarshaller(); - jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - jaxbUnmarshaller = jaxbContext.createUnmarshaller(); - } catch (JAXBException e) { - throw new SerializationException(e); - } - } + /** + * Java Architecture for XML Binding (JAXB) class that allows transforming xml + * describing T into T object. + */ + private Unmarshaller jaxbUnmarshaller; - /** - * Transforms object into xml string. - * - * @param object - * object to transform - * @return xml string representing object - */ - public String objectToString(T object) { - if (object == null) { - return null; - } - StringWriter sw = new StringWriter(); - try { - jaxbMarshaller.marshal(object, sw); - } catch (JAXBException e) { - throw new SerializationException(e); - } catch (Exception e) { - logger.error(e, e); - return null; - } - return sw.toString(); - } + /** + * Default constructor. + * + * @param theClass + * class of the object that DAO will work on + */ + public XmlSerializer(Class<? extends T> theClass) { + this.clazz = theClass; + try { + JAXBContext jaxbContext; + jaxbContext = JAXBContext.newInstance(clazz); + jaxbMarshaller = jaxbContext.createMarshaller(); + jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + jaxbUnmarshaller = jaxbContext.createUnmarshaller(); + } catch (JAXBException e) { + throw new SerializationException(e); + } + } - /** - * Creates object from xml node. - * - * @param node - * xml node - * @return object corresponding to xml node - */ - @SuppressWarnings("unchecked") - public T xmlToObject(Node node) { - if (node == null) { - return null; - } - try { - return (T) jaxbUnmarshaller.unmarshal(node); - } catch (JAXBException e) { - throw new SerializationException(e); - } catch (Exception e) { // the library can throw NPE sometimes... - logger.error(e, e); - return null; - } - } + /** + * Transforms object into xml string. + * + * @param object + * object to transform + * @return xml string representing object + */ + public String objectToString(T object) { + if (object == null) { + return null; + } + StringWriter sw = new StringWriter(); + try { + jaxbMarshaller.marshal(object, sw); + } catch (JAXBException e) { + throw new SerializationException(e); + } catch (Exception e) { + logger.error(e, e); + return null; + } + return sw.toString(); + } + + /** + * Creates object from xml node. + * + * @param node + * xml node + * @return object corresponding to xml node + */ + @SuppressWarnings("unchecked") + public T xmlToObject(Node node) { + if (node == null) { + return null; + } + try { + return (T) jaxbUnmarshaller.unmarshal(node); + } catch (JAXBException e) { + throw new SerializationException(e); + } catch (Exception e) { // the library can throw NPE sometimes... + logger.error(e, e); + return null; + } + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/package-info.java b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/package-info.java index 64f1ec2089..016987a387 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/cache/package-info.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/cache/package-info.java @@ -1,20 +1,22 @@ /** * This package contains implementation of cache utils. General interface of - * cache is defined in {@link lcsb.mapviewer.annotation.cache.QueryCacheInterface + * cache is defined in + * {@link lcsb.mapviewer.annotation.cache.QueryCacheInterface * QueryCacheInterface}. There are three known implementations of this * interface: * <ul> - * <li> {@link lcsb.mapviewer.annotation.cache.ApplicationLevelCache + * <li>{@link lcsb.mapviewer.annotation.cache.ApplicationLevelCache * ApplicationLevelCache} - allows to cache data within application scope. After * application restart everything is lost,</li> - * <li> {@link lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache + * <li>{@link lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCache * PermanentDatabaseLevelCache} - allows to cache data in the database. It's * slower than {@link lcsb.mapviewer.annotation.cache.ApplicationLevelCache * ApplicationLevelCache} cache, but the data is available until they are * removed from the database,</li> - * <li> {@link lcsb.mapviewer.annotation.cache.GeneralCache GeneralCache} - it's a mix - * of above methods. When query to cache is send, first local application cache - * is looked up and if it's not found there the database cache is checked.</li> + * <li>{@link lcsb.mapviewer.annotation.cache.GeneralCache GeneralCache} - it's + * a mix of above methods. When query to cache is send, first local application + * cache is looked up and if it's not found there the database cache is + * checked.</li> * </ul> * The data stored in cache has * {@link lcsb.mapviewer.db.model.reactome.CacheQuery#expires validity date} @@ -24,4 +26,3 @@ * information from original source when expire date is reached. */ package lcsb.mapviewer.annotation.cache; - diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Article.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Article.java index 5909001a86..31f84391f8 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Article.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Article.java @@ -16,180 +16,180 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement public class Article implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Title of the article. - */ - private String title; - - /** - * List of authors. - */ - private List<String> authors = new ArrayList<>(); - - /** - * Journal. - */ - private String journal; - - /** - * Year of issue. - */ - private Integer year; - - /** - * Url that points to this article. - */ - private String link; - - /** - * Pubmed identifier of the article. - */ - private String id; - - /** - * How many citiations were made to this article. - */ - private int citationCount; - - /** - * - * @return {@link #title} - */ - public String getTitle() { - return title; - } - - /** - * - * @param title - * new {@link #title} value - */ - @XmlElement - public void setTitle(String title) { - this.title = title; - } - - /** - * - * @return {@link #authors} - */ - public List<String> getAuthors() { - return authors; - } - - /** - * - * @param authors - * new {@link #title} value - */ - public void setAuthors(List<String> authors) { - this.authors = authors; - } - - /** - * - * @return {@link #journal} - */ - public String getJournal() { - return journal; - } - - /** - * - * @param journal - * new {@link #journal} value - */ - @XmlElement - public void setJournal(String journal) { - this.journal = journal; - } - - /** - * - * @return {@link #year} - */ - public Integer getYear() { - return year; - } - - /** - * - * @param year - * new {@link #year} - */ - @XmlElement - public void setYear(Integer year) { - this.year = year; - } - - /** - * - * @return comma separated string with authors - */ - public String getStringAuthors() { - String result = ""; - for (String string : authors) { - if (!result.equalsIgnoreCase("")) { - result += ", "; - } - result += string; - } - return result; - } - - /** - * - * @return {@link #link} - */ - public String getLink() { - return link; - } - - /** - * - * @param link - * new {@link #link} - */ - public void setLink(String link) { - this.link = link; - } - - /** - * - * @return {@link #id} - */ - public String getId() { - return id; - } - - /** - * - * @param id - * new {@link #id} value - */ - public void setId(String id) { - this.id = id; - } - - /** - * - * @return {@link #citationCount} - */ - public int getCitationCount() { - return citationCount; - } - - /** - * - * @param citationCount - * new {@link #citationCount} value - */ - public void setCitationCount(int citationCount) { - this.citationCount = citationCount; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Title of the article. + */ + private String title; + + /** + * List of authors. + */ + private List<String> authors = new ArrayList<>(); + + /** + * Journal. + */ + private String journal; + + /** + * Year of issue. + */ + private Integer year; + + /** + * Url that points to this article. + */ + private String link; + + /** + * Pubmed identifier of the article. + */ + private String id; + + /** + * How many citiations were made to this article. + */ + private int citationCount; + + /** + * + * @return {@link #title} + */ + public String getTitle() { + return title; + } + + /** + * + * @param title + * new {@link #title} value + */ + @XmlElement + public void setTitle(String title) { + this.title = title; + } + + /** + * + * @return {@link #authors} + */ + public List<String> getAuthors() { + return authors; + } + + /** + * + * @param authors + * new {@link #title} value + */ + public void setAuthors(List<String> authors) { + this.authors = authors; + } + + /** + * + * @return {@link #journal} + */ + public String getJournal() { + return journal; + } + + /** + * + * @param journal + * new {@link #journal} value + */ + @XmlElement + public void setJournal(String journal) { + this.journal = journal; + } + + /** + * + * @return {@link #year} + */ + public Integer getYear() { + return year; + } + + /** + * + * @param year + * new {@link #year} + */ + @XmlElement + public void setYear(Integer year) { + this.year = year; + } + + /** + * + * @return comma separated string with authors + */ + public String getStringAuthors() { + String result = ""; + for (String string : authors) { + if (!result.equalsIgnoreCase("")) { + result += ", "; + } + result += string; + } + return result; + } + + /** + * + * @return {@link #link} + */ + public String getLink() { + return link; + } + + /** + * + * @param link + * new {@link #link} + */ + public void setLink(String link) { + this.link = link; + } + + /** + * + * @return {@link #id} + */ + public String getId() { + return id; + } + + /** + * + * @param id + * new {@link #id} value + */ + public void setId(String id) { + this.id = id; + } + + /** + * + * @return {@link #citationCount} + */ + public int getCitationCount() { + return citationCount; + } + + /** + * + * @param citationCount + * new {@link #citationCount} value + */ + public void setCitationCount(int citationCount) { + this.citationCount = citationCount; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/ArticleCitationComparator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/ArticleCitationComparator.java index 6725ec2b98..63284f4ff5 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/ArticleCitationComparator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/ArticleCitationComparator.java @@ -11,9 +11,9 @@ import java.util.Comparator; */ public class ArticleCitationComparator implements Comparator<Article> { - @Override - public int compare(Article o1, Article o2) { - return -((Integer) o1.getCitationCount()).compareTo(o2.getCitationCount()); - } + @Override + public int compare(Article o1, Article o2) { + return -((Integer) o1.getCitationCount()).compareTo(o2.getCitationCount()); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chebi.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chebi.java index 00e4d1f0fc..282181424d 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chebi.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chebi.java @@ -6,11 +6,10 @@ import java.util.List; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import uk.ac.ebi.chebi.webapps.chebiWS.model.DataItem; -import uk.ac.ebi.chebi.webapps.chebiWS.model.Entity; -import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; +import uk.ac.ebi.chebi.webapps.chebiWS.model.*; /** * This class represents <a href="http://www.ebi.ac.uk/chebi/">chebi</a> object. @@ -21,227 +20,227 @@ import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; @XmlRootElement public class Chebi implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(Chebi.class); - - /** - * Name of the object. - */ - private String name; - /** - * Chebi identifier. - */ - private String chebiId; - /** - * <a href = - * "http://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system" - * >Smiles</a> description. - */ - private String smiles; - - /** - * <a href = "http://en.wikipedia.org/wiki/International_Chemical_Identifier" - * >InChI</a> description. - */ - private String inchi; - - /** - * Key for the - * <a href = "http://en.wikipedia.org/wiki/International_Chemical_Identifier" - * >InChI</a> description. It's a hashed value of InChI. - */ - private String inchiKey; - - /** - * List of synonyms. - */ - private List<String> synonyms = new ArrayList<>(); - - /** - * List of elements that stands above this object in chebi ontology. - */ - private List<ChebiRelation> incomingChebi = new ArrayList<>(); - - /** - * List of elements that stands below this object in chebi ontology. - */ - private List<ChebiRelation> outgoingChebi = new ArrayList<>(); - - /** - * Default constructor. - */ - public Chebi() { - - } - - /** - * Constructor that initilizes object from the data taken from entity acquired - * from Chebi API. - * - * @param entity - * object received from Chebi API representing chebi object - */ - public Chebi(Entity entity) { - this.chebiId = entity.getChebiId(); - this.name = entity.getChebiAsciiName().trim(); - this.smiles = entity.getSmiles(); - this.inchi = entity.getInchi(); - this.inchiKey = entity.getInchiKey(); - for (DataItem di : entity.getSynonyms()) { - synonyms.add(di.getData()); - } - for (OntologyDataItem item : entity.getOntologyParents()) { - ChebiRelation relation = new ChebiRelation(item); - incomingChebi.add(relation); - } - for (OntologyDataItem item : entity.getOntologyChildren()) { - ChebiRelation relation = new ChebiRelation(item); - outgoingChebi.add(relation); - } - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the chebiId - * @see #chebiId - */ - public String getChebiId() { - return chebiId; - } - - /** - * @param chebiId - * the chebiId to set - * @see #chebiId - */ - public void setChebiId(String chebiId) { - this.chebiId = chebiId; - } - - /** - * @return the smiles - * @see #smiles - */ - public String getSmiles() { - return smiles; - } - - /** - * @param smiles - * the smiles to set - * @see #smiles - */ - public void setSmiles(String smiles) { - this.smiles = smiles; - } - - /** - * @return the inchi - * @see #inchi - */ - public String getInchi() { - return inchi; - } - - /** - * @param inchi - * the inchi to set - * @see #inchi - */ - public void setInchi(String inchi) { - this.inchi = inchi; - } - - /** - * @return the inchiKey - * @see #inchiKey - */ - public String getInchiKey() { - return inchiKey; - } - - /** - * @param inchiKey - * the inchiKey to set - * @see #inchiKey - */ - public void setInchiKey(String inchiKey) { - this.inchiKey = inchiKey; - } - - /** - * @return the synonyms - * @see #synonyms - */ - public List<String> getSynonyms() { - return synonyms; - } - - /** - * @param synonyms - * the synonyms to set - * @see #synonyms - */ - public void setSynonyms(List<String> synonyms) { - this.synonyms = synonyms; - } - - /** - * @return the incomingChebi - * @see #incomingChebi - */ - public List<ChebiRelation> getIncomingChebi() { - return incomingChebi; - } - - /** - * @param incomingChebi - * the incomingChebi to set - * @see #incomingChebi - */ - public void setIncomingChebi(List<ChebiRelation> incomingChebi) { - this.incomingChebi = incomingChebi; - } - - /** - * @return the outgoingChebi - * @see #outgoingChebi - */ - public List<ChebiRelation> getOutgoingChebi() { - return outgoingChebi; - } - - /** - * @param outgoingChebi - * the outgoingChebi to set - * @see #outgoingChebi - */ - public void setOutgoingChebi(List<ChebiRelation> outgoingChebi) { - this.outgoingChebi = outgoingChebi; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(Chebi.class); + + /** + * Name of the object. + */ + private String name; + /** + * Chebi identifier. + */ + private String chebiId; + /** + * <a href = + * "http://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system" + * >Smiles</a> description. + */ + private String smiles; + + /** + * <a href = "http://en.wikipedia.org/wiki/International_Chemical_Identifier" + * >InChI</a> description. + */ + private String inchi; + + /** + * Key for the + * <a href = "http://en.wikipedia.org/wiki/International_Chemical_Identifier" + * >InChI</a> description. It's a hashed value of InChI. + */ + private String inchiKey; + + /** + * List of synonyms. + */ + private List<String> synonyms = new ArrayList<>(); + + /** + * List of elements that stands above this object in chebi ontology. + */ + private List<ChebiRelation> incomingChebi = new ArrayList<>(); + + /** + * List of elements that stands below this object in chebi ontology. + */ + private List<ChebiRelation> outgoingChebi = new ArrayList<>(); + + /** + * Default constructor. + */ + public Chebi() { + + } + + /** + * Constructor that initilizes object from the data taken from entity acquired + * from Chebi API. + * + * @param entity + * object received from Chebi API representing chebi object + */ + public Chebi(Entity entity) { + this.chebiId = entity.getChebiId(); + this.name = entity.getChebiAsciiName().trim(); + this.smiles = entity.getSmiles(); + this.inchi = entity.getInchi(); + this.inchiKey = entity.getInchiKey(); + for (DataItem di : entity.getSynonyms()) { + synonyms.add(di.getData()); + } + for (OntologyDataItem item : entity.getOntologyParents()) { + ChebiRelation relation = new ChebiRelation(item); + incomingChebi.add(relation); + } + for (OntologyDataItem item : entity.getOntologyChildren()) { + ChebiRelation relation = new ChebiRelation(item); + outgoingChebi.add(relation); + } + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the chebiId + * @see #chebiId + */ + public String getChebiId() { + return chebiId; + } + + /** + * @param chebiId + * the chebiId to set + * @see #chebiId + */ + public void setChebiId(String chebiId) { + this.chebiId = chebiId; + } + + /** + * @return the smiles + * @see #smiles + */ + public String getSmiles() { + return smiles; + } + + /** + * @param smiles + * the smiles to set + * @see #smiles + */ + public void setSmiles(String smiles) { + this.smiles = smiles; + } + + /** + * @return the inchi + * @see #inchi + */ + public String getInchi() { + return inchi; + } + + /** + * @param inchi + * the inchi to set + * @see #inchi + */ + public void setInchi(String inchi) { + this.inchi = inchi; + } + + /** + * @return the inchiKey + * @see #inchiKey + */ + public String getInchiKey() { + return inchiKey; + } + + /** + * @param inchiKey + * the inchiKey to set + * @see #inchiKey + */ + public void setInchiKey(String inchiKey) { + this.inchiKey = inchiKey; + } + + /** + * @return the synonyms + * @see #synonyms + */ + public List<String> getSynonyms() { + return synonyms; + } + + /** + * @param synonyms + * the synonyms to set + * @see #synonyms + */ + public void setSynonyms(List<String> synonyms) { + this.synonyms = synonyms; + } + + /** + * @return the incomingChebi + * @see #incomingChebi + */ + public List<ChebiRelation> getIncomingChebi() { + return incomingChebi; + } + + /** + * @param incomingChebi + * the incomingChebi to set + * @see #incomingChebi + */ + public void setIncomingChebi(List<ChebiRelation> incomingChebi) { + this.incomingChebi = incomingChebi; + } + + /** + * @return the outgoingChebi + * @see #outgoingChebi + */ + public List<ChebiRelation> getOutgoingChebi() { + return outgoingChebi; + } + + /** + * @param outgoingChebi + * the outgoingChebi to set + * @see #outgoingChebi + */ + public void setOutgoingChebi(List<ChebiRelation> outgoingChebi) { + this.outgoingChebi = outgoingChebi; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChebiRelation.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChebiRelation.java index c4cce63e7e..9b3aa6be01 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChebiRelation.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChebiRelation.java @@ -12,95 +12,95 @@ import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; * */ public class ChebiRelation implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Name of the chebi object pointed by this relation. - */ - private String name; - - /** - * Type of the relation. - */ - private String type; - - /** - * Chebi identifier of object pointef by this relation. - */ - private String id; - - /** - * Default constructor. - */ - public ChebiRelation() { - - } - - /** - * Constructor that creates relation from object retrieved by Chebi API. - * - * @param item - * object from Chebi API - */ - public ChebiRelation(OntologyDataItem item) { - name = item.getChebiName(); - type = item.getType(); - id = item.getChebiId(); - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the type - * @see #type - */ - public String getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return the id - * @see #id - */ - public String getId() { - return id; - } - - /** - * @param id - * the id to set - * @see #id - */ - public void setId(String id) { - this.id = id; - } + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Name of the chebi object pointed by this relation. + */ + private String name; + + /** + * Type of the relation. + */ + private String type; + + /** + * Chebi identifier of object pointef by this relation. + */ + private String id; + + /** + * Default constructor. + */ + public ChebiRelation() { + + } + + /** + * Constructor that creates relation from object retrieved by Chebi API. + * + * @param item + * object from Chebi API + */ + public ChebiRelation(OntologyDataItem item) { + name = item.getChebiName(); + type = item.getType(); + id = item.getChebiId(); + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the type + * @see #type + */ + public String getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return the id + * @see #id + */ + public String getId() { + return id; + } + + /** + * @param id + * the id to set + * @see #id + */ + public void setId(String id) { + this.id = id; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chemical.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chemical.java index a5bb9ba78f..f2b8141847 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chemical.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Chemical.java @@ -1,10 +1,7 @@ package lcsb.mapviewer.annotation.data; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; +import java.util.*; import javax.xml.bind.annotation.XmlRootElement; @@ -22,274 +19,257 @@ import lcsb.mapviewer.model.map.MiriamData; @XmlRootElement public class Chemical implements Serializable, TargettingStructure { - /** - * - */ - private static final long serialVersionUID = 3892326511802845188L; - - /** - * Name. - */ - private String chemicalName; - - /** - * Toxigenomic database chemcial ID (MeSH). - */ - private MiriamData chemicalId; - - /** - * Toxigenomic database ID (CAS). - */ - private MiriamData casID; - - /** - * Evidence evidence either marker/mechanism and/or T therapeutic. - */ - private ChemicalDirectEvidence directEvidence; - - /** - * direct Evidence Publication. - */ - private List<MiriamData> directEvidencePublication = new ArrayList<>(); - - /** - * Genes interacting with the chemical plus publications. - */ - private List<Target> inferenceNetwork = new ArrayList<>(); - - /** - * Inference score. - */ - private Float inferenceScore; - - /** - * Reference count. - */ - private Integer refScore; - - /** - * Known synonyms. - */ - private List<String> synonyms = new ArrayList<>(); - - /** - * default constructor. - */ - public Chemical() { - super(); - } - - /** - * @param chemicalName - * name. - * @param chemicalId - * id. - * @param casID - * cas id. - * @param directEvidence - * string value for direct Evidence. - * @param inferenceNetwork - * inference network. - * @param directEvidencePublication - * publications associated with evidence publications. - * @param inferenceScore - * score. - * @param refScore - * number of references. - */ - public Chemical(String chemicalName, MiriamData chemicalId, MiriamData casID, ChemicalDirectEvidence directEvidence, List<Target> inferenceNetwork, - List<MiriamData> directEvidencePublication, Float inferenceScore, Integer refScore) { - super(); - this.chemicalName = chemicalName; - this.chemicalId = chemicalId; - this.casID = casID; - this.directEvidence = directEvidence; - this.inferenceNetwork = inferenceNetwork; - this.directEvidencePublication = directEvidencePublication; - this.inferenceScore = inferenceScore; - this.refScore = refScore; - } - - /** - * @return the chemicalName - */ - public String getChemicalName() { - return chemicalName; - } - - /** - * @param chemicalName - * the chemicalName to set - */ - public void setChemicalName(String chemicalName) { - this.chemicalName = chemicalName; - } - - /** - * @return the chemicalId - */ - public MiriamData getChemicalId() { - return chemicalId; - } - - /** - * @param chemicalId - * the chemicalId to set - */ - public void setChemicalId(MiriamData chemicalId) { - this.chemicalId = chemicalId; - } - - /** - * @return the casType - */ - public MiriamData getCasID() { - return casID; - } - - /** - * @param casID - * the casType to set - */ - public void setCasID(MiriamData casID) { - this.casID = casID; - } - - /** - * @return the directEvidence - */ - public ChemicalDirectEvidence getDirectEvidence() { - return directEvidence; - } - - /** - * @param directEvidence - * the directEvidence to set - */ - public void setDirectEvidence(ChemicalDirectEvidence directEvidence) { - this.directEvidence = directEvidence; - } - - /** - * @return the inferenceNetwork - */ - public List<Target> getInferenceNetwork() { - return inferenceNetwork; - } - - /** - * @param inferenceNetwork - * the inferenceNetwork to set - */ - public void setInferenceNetwork(List<Target> inferenceNetwork) { - this.inferenceNetwork = inferenceNetwork; - } - - /** - * @return the inferenceScore - */ - public Float getInferenceScore() { - return inferenceScore; - } - - /** - * @param inferenceScore - * the inferenceScore to set - */ - public void setInferenceScore(Float inferenceScore) { - this.inferenceScore = inferenceScore; - } - - /** - * @return the refScore - */ - public Integer getRefScore() { - return refScore; - } - - /** - * @param refScore - * the refScore to set - */ - public void setRefScore(Integer refScore) { - this.refScore = refScore; - } - - /** - * @return the directEvidencePublication - */ - public List<MiriamData> getDirectEvidencePublication() { - return directEvidencePublication; - } - - /** - * @param directEvidencePublication - * the directEvidencePublication to set - */ - public void setDirectEvidencePublication(List<MiriamData> directEvidencePublication) { - this.directEvidencePublication = directEvidencePublication; - } - - /** - * @return list of synonyms. - */ - public List<String> getSynonyms() { - return synonyms; - } - - /** - * @return list of synonyms as string. - */ - public String getSynonymsString() { - return StringUtils.join(synonyms, ","); - } - - /** - * @param synonyms - * list of all names that are synonyms. - */ - public void setSynonyms(List<String> synonyms) { - this.synonyms = synonyms; - } - - @Override - public String toString() { - StringBuffer result = new StringBuffer(); - result.append("\nname: " + chemicalName + "\nchemicalId:" + chemicalId + "\ncasID:" + casID); - result.append("\nsynonyms:" + getSynonymsString()); - result.append("\ninferenceScore:" + inferenceScore + "\nrefScore:" + refScore); - result.append("\ninferenceNetwork: "); - for (Target item : getInferenceNetwork()) { - if (item != null) { - result.append(item.toString()); - } - } - result.append("\ndirectEvidence:" + directEvidence + "\ndirectEvidencePublication:\n"); - for (MiriamData publication : directEvidencePublication) { - result.append("publication DB: " + publication.getDataType() + ", publication Id: " + publication.getResource() + "\n"); - } - - return result.toString(); - } - - /** - * Comparator of the objects by their name. - * - * @author Piotr Gawron - * - */ - public static class NameComparator implements Comparator<Chemical> { - /** - * Default string comparator. - */ - private StringComparator stringComparator = new StringComparator(); - - @Override - public int compare(Chemical arg0, Chemical arg1) { - return stringComparator.compare(arg0.getChemicalName(), arg1.getChemicalName()); - } - - } + /** + * + */ + private static final long serialVersionUID = 3892326511802845188L; + + /** + * Name. + */ + private String chemicalName; + + /** + * Toxigenomic database chemcial ID (MeSH). + */ + private MiriamData chemicalId; + + /** + * Toxigenomic database ID (CAS). + */ + private MiriamData casID; + + /** + * Evidence evidence either marker/mechanism and/or T therapeutic. + */ + private ChemicalDirectEvidence directEvidence; + + /** + * direct Evidence Publication. + */ + private List<MiriamData> directEvidencePublication = new ArrayList<>(); + + /** + * Genes interacting with the chemical plus publications. + */ + private List<Target> inferenceNetwork = new ArrayList<>(); + + /** + * Inference score. + */ + private Float inferenceScore; + + /** + * Reference count. + */ + private Integer refScore; + + /** + * Known synonyms. + */ + private List<String> synonyms = new ArrayList<>(); + + /** + * default constructor. + */ + public Chemical() { + super(); + } + + /** + * @param chemicalName + * name. + * @param chemicalId + * id. + * @param casID + * cas id. + * @param directEvidence + * string value for direct Evidence. + * @param inferenceNetwork + * inference network. + * @param directEvidencePublication + * publications associated with evidence publications. + * @param inferenceScore + * score. + * @param refScore + * number of references. + */ + public Chemical(String chemicalName, MiriamData chemicalId, MiriamData casID, ChemicalDirectEvidence directEvidence, + List<Target> inferenceNetwork, + List<MiriamData> directEvidencePublication, Float inferenceScore, Integer refScore) { + super(); + this.chemicalName = chemicalName; + this.chemicalId = chemicalId; + this.casID = casID; + this.directEvidence = directEvidence; + this.inferenceNetwork = inferenceNetwork; + this.directEvidencePublication = directEvidencePublication; + this.inferenceScore = inferenceScore; + this.refScore = refScore; + } + + /** + * @return the chemicalName + */ + public String getChemicalName() { + return chemicalName; + } + + /** + * @param chemicalName + * the chemicalName to set + */ + public void setChemicalName(String chemicalName) { + this.chemicalName = chemicalName; + } + + /** + * @return the chemicalId + */ + public MiriamData getChemicalId() { + return chemicalId; + } + + /** + * @param chemicalId + * the chemicalId to set + */ + public void setChemicalId(MiriamData chemicalId) { + this.chemicalId = chemicalId; + } + + /** + * @return the casType + */ + public MiriamData getCasID() { + return casID; + } + + /** + * @param casID + * the casType to set + */ + public void setCasID(MiriamData casID) { + this.casID = casID; + } + + /** + * @return the directEvidence + */ + public ChemicalDirectEvidence getDirectEvidence() { + return directEvidence; + } + + /** + * @param directEvidence + * the directEvidence to set + */ + public void setDirectEvidence(ChemicalDirectEvidence directEvidence) { + this.directEvidence = directEvidence; + } + + /** + * @return the inferenceNetwork + */ + public List<Target> getInferenceNetwork() { + return inferenceNetwork; + } + + /** + * @param inferenceNetwork + * the inferenceNetwork to set + */ + public void setInferenceNetwork(List<Target> inferenceNetwork) { + this.inferenceNetwork = inferenceNetwork; + } + + /** + * @return the inferenceScore + */ + public Float getInferenceScore() { + return inferenceScore; + } + + /** + * @param inferenceScore + * the inferenceScore to set + */ + public void setInferenceScore(Float inferenceScore) { + this.inferenceScore = inferenceScore; + } + + /** + * @return the refScore + */ + public Integer getRefScore() { + return refScore; + } + + /** + * @param refScore + * the refScore to set + */ + public void setRefScore(Integer refScore) { + this.refScore = refScore; + } + + /** + * @return the directEvidencePublication + */ + public List<MiriamData> getDirectEvidencePublication() { + return directEvidencePublication; + } + + /** + * @param directEvidencePublication + * the directEvidencePublication to set + */ + public void setDirectEvidencePublication(List<MiriamData> directEvidencePublication) { + this.directEvidencePublication = directEvidencePublication; + } + + /** + * @return list of synonyms. + */ + public List<String> getSynonyms() { + return synonyms; + } + + /** + * @param synonyms + * list of all names that are synonyms. + */ + public void setSynonyms(List<String> synonyms) { + this.synonyms = synonyms; + } + + /** + * @return list of synonyms as string. + */ + public String getSynonymsString() { + return StringUtils.join(synonyms, ","); + } + + @Override + public String toString() { + StringBuffer result = new StringBuffer(); + result.append("\nname: " + chemicalName + "\nchemicalId:" + chemicalId + "\ncasID:" + casID); + result.append("\nsynonyms:" + getSynonymsString()); + result.append("\ninferenceScore:" + inferenceScore + "\nrefScore:" + refScore); + result.append("\ninferenceNetwork: "); + for (Target item : getInferenceNetwork()) { + if (item != null) { + result.append(item.toString()); + } + } + result.append("\ndirectEvidence:" + directEvidence + "\ndirectEvidencePublication:\n"); + for (MiriamData publication : directEvidencePublication) { + result.append( + "publication DB: " + publication.getDataType() + ", publication Id: " + publication.getResource() + "\n"); + } + + return result.toString(); + } @Override public Collection<MiriamData> getSources() { @@ -303,13 +283,32 @@ public class Chemical implements Serializable, TargettingStructure { return sources; } - @Override - public Collection<Target> getTargets() { - return getInferenceNetwork(); - } + @Override + public Collection<Target> getTargets() { + return getInferenceNetwork(); + } public void addSynonyms(List<String> synonyms) { this.synonyms.addAll(synonyms); } + /** + * Comparator of the objects by their name. + * + * @author Piotr Gawron + * + */ + public static class NameComparator implements Comparator<Chemical> { + /** + * Default string comparator. + */ + private StringComparator stringComparator = new StringComparator(); + + @Override + public int compare(Chemical arg0, Chemical arg1) { + return stringComparator.compare(arg0.getChemicalName(), arg1.getChemicalName()); + } + + } + } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidence.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidence.java index c5e3895247..754c0f65c3 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidence.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidence.java @@ -8,30 +8,31 @@ package lcsb.mapviewer.annotation.data; */ public enum ChemicalDirectEvidence { - /** - * Values. - */ - MARKER("marker/mechanism"), THERAPEUTIC("therapeutic"); + /** + * Values. + */ + MARKER("marker/mechanism"), + THERAPEUTIC("therapeutic"); - /** - * Value. - */ - private String value; + /** + * Value. + */ + private String value; - /** - * @param value - * string to set the value. - */ - ChemicalDirectEvidence(String value) { + /** + * @param value + * string to set the value. + */ + ChemicalDirectEvidence(String value) { - this.value = value; - } + this.value = value; + } - /** - * @return the value - */ - public String getValue() { - return value; - } + /** + * @return the value + */ + public String getValue() { + return value; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Drug.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Drug.java index d4e786a065..f308e36325 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Drug.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Drug.java @@ -1,14 +1,13 @@ package lcsb.mapviewer.annotation.data; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; +import java.util.*; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.comparator.StringComparator; import lcsb.mapviewer.model.map.MiriamData; @@ -22,315 +21,315 @@ import lcsb.mapviewer.model.map.MiriamData; @XmlRootElement public class Drug implements Serializable, TargettingStructure { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(Drug.class); - - /** - * Source of the data. - */ - private List<MiriamData> sources = new ArrayList<>(); - - /** - * Name of the drug. - */ - private String name; - - /** - * Description of the drug. - */ - private String description; - - /** - * Status of blood brain barries for the drug. - */ - private String bloodBrainBarrier = "N/A"; - - /** - * Is the drug approved. - */ - private Boolean approved; - - /** - * Known brand names. - */ - private List<String> brandNames = new ArrayList<>(); - - /** - * Known targets. - */ - private List<Target> targets = new ArrayList<>(); - - /** - * Known synonyms. - */ - private List<String> synonyms = new ArrayList<>(); - - /** - * Default constructor. - */ - public Drug() { - - } - - /** - * Constructor that initializes object with the same information as parameter. - * - * @param drug - * original drug - */ - public Drug(Drug drug) { - if (drug == null) { - return; - } - this.sources.addAll(drug.getSources()); - this.description = drug.description; - this.brandNames.addAll(drug.getBrandNames()); - this.synonyms.addAll(drug.getSynonyms()); - this.targets.addAll(drug.getTargets()); - this.bloodBrainBarrier = drug.getBloodBrainBarrier(); - this.setApproved(drug.getApproved()); - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder(""); - for (MiriamData md : sources) { - result.append("source: " + md.getDataType() + ", drugId: " + md.getResource() + "\n"); - } - result.append(", name: " + name + "\nDescription:\n" + description + "\nSynonyms:"); - for (String s : synonyms) { - result.append(s + "|"); - } - result.append("\nTargets:"); - for (Target t : targets) { - if (t.getSource() != null) { - result.append(t.getSource().getResource() + "|" + t.getName() + "|" + t.getGenes()); - } else { - result.append("N/A |" + t.getName() + "|" + t.getGenes()); - } - result.append(" (References:"); - for (MiriamData md : t.getReferences()) { - result.append(md.getResource() + ","); - } - result.append(")+\n"); - - } - return result.toString(); - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the description - * @see #description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * @see #description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the bloodBrainBarrier - * @see #bloodBrainBarrier - */ - public String getBloodBrainBarrier() { - return bloodBrainBarrier; - } - - /** - * @param bloodBrainBarrier - * the bloodBrainBarrier to set - * @see #bloodBrainBarrier - */ - public void setBloodBrainBarrier(String bloodBrainBarrier) { - this.bloodBrainBarrier = bloodBrainBarrier; - } - - /** - * @return the brandNames - * @see #brandNames - */ - public List<String> getBrandNames() { - return brandNames; - } - - /** - * @param brandNames - * the brandNames to set - * @see #brandNames - */ - public void setBrandNames(List<String> brandNames) { - this.brandNames = brandNames; - } - - /** - * @return the targets - * @see #targets - */ - @XmlElement(name = "target") - public List<Target> getTargets() { - return targets; - } - - /** - * @param targets - * the targets to set - * @see #targets - */ - public void setTargets(List<Target> targets) { - this.targets = targets; - } - - /** - * @return the synonyms - * @see #synonyms - */ - public List<String> getSynonyms() { - return synonyms; - } - - /** - * @param synonyms - * the synonyms to set - * @see #synonyms - */ - public void setSynonyms(List<String> synonyms) { - this.synonyms = synonyms; - } - - /** - * Adds brand name into {@link #brandNames}. - * - * @param brandName - * object to add - */ - public void addBrandName(String brandName) { - this.brandNames.add(brandName); - } - - /** - * Adds synonym into {@link #synonyms}. - * - * @param synonym - * object to add - */ - public void addSynonym(String synonym) { - if (synonyms.contains(synonym)) { - logger.warn("Synonym already exists in the drug: " + synonym); - } else { - this.synonyms.add(synonym); - } - } - - /** - * Adds target into {@link #targets} list. - * - * @param target - * object to add - */ - public void addTarget(Target target) { - this.targets.add(target); - } - - /** - * @param source - * the source to add - * @see #sources - */ - public void addSource(MiriamData source) { - this.sources.add(source); - } - - /** - * @return the sources - * @see #sources - */ - public List<MiriamData> getSources() { - return sources; - } - - /** - * @param sources - * the sources to set - * @see #sources - */ - public void setSources(List<MiriamData> sources) { - this.sources = sources; - } - - /** - * Adds targets to the drug. - * - * @param targets2 - * list of targets to add - */ - public void addTargets(List<Target> targets2) { - this.targets.addAll(targets2); - } - - /** - * @return the approved - * @see #approved - */ - public Boolean getApproved() { - return approved; - } - - /** - * @param approved - * the approved to set - * @see #approved - */ - public void setApproved(Boolean approved) { - this.approved = approved; - } - - /** - * Comparator of the objects by their name. - * - * @author Piotr Gawron - * - */ - public static class NameComparator implements Comparator<Drug> { - /** - * Default string comparator. - */ - private StringComparator stringComparator = new StringComparator(); - - @Override - public int compare(Drug arg0, Drug arg1) { - return stringComparator.compare(arg0.getName(), arg1.getName()); - } - - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(Drug.class); + + /** + * Source of the data. + */ + private List<MiriamData> sources = new ArrayList<>(); + + /** + * Name of the drug. + */ + private String name; + + /** + * Description of the drug. + */ + private String description; + + /** + * Status of blood brain barries for the drug. + */ + private String bloodBrainBarrier = "N/A"; + + /** + * Is the drug approved. + */ + private Boolean approved; + + /** + * Known brand names. + */ + private List<String> brandNames = new ArrayList<>(); + + /** + * Known targets. + */ + private List<Target> targets = new ArrayList<>(); + + /** + * Known synonyms. + */ + private List<String> synonyms = new ArrayList<>(); + + /** + * Default constructor. + */ + public Drug() { + + } + + /** + * Constructor that initializes object with the same information as parameter. + * + * @param drug + * original drug + */ + public Drug(Drug drug) { + if (drug == null) { + return; + } + this.sources.addAll(drug.getSources()); + this.description = drug.description; + this.brandNames.addAll(drug.getBrandNames()); + this.synonyms.addAll(drug.getSynonyms()); + this.targets.addAll(drug.getTargets()); + this.bloodBrainBarrier = drug.getBloodBrainBarrier(); + this.setApproved(drug.getApproved()); + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(""); + for (MiriamData md : sources) { + result.append("source: " + md.getDataType() + ", drugId: " + md.getResource() + "\n"); + } + result.append(", name: " + name + "\nDescription:\n" + description + "\nSynonyms:"); + for (String s : synonyms) { + result.append(s + "|"); + } + result.append("\nTargets:"); + for (Target t : targets) { + if (t.getSource() != null) { + result.append(t.getSource().getResource() + "|" + t.getName() + "|" + t.getGenes()); + } else { + result.append("N/A |" + t.getName() + "|" + t.getGenes()); + } + result.append(" (References:"); + for (MiriamData md : t.getReferences()) { + result.append(md.getResource() + ","); + } + result.append(")+\n"); + + } + return result.toString(); + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the description + * @see #description + */ + public String getDescription() { + return description; + } + + /** + * @param description + * the description to set + * @see #description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the bloodBrainBarrier + * @see #bloodBrainBarrier + */ + public String getBloodBrainBarrier() { + return bloodBrainBarrier; + } + + /** + * @param bloodBrainBarrier + * the bloodBrainBarrier to set + * @see #bloodBrainBarrier + */ + public void setBloodBrainBarrier(String bloodBrainBarrier) { + this.bloodBrainBarrier = bloodBrainBarrier; + } + + /** + * @return the brandNames + * @see #brandNames + */ + public List<String> getBrandNames() { + return brandNames; + } + + /** + * @param brandNames + * the brandNames to set + * @see #brandNames + */ + public void setBrandNames(List<String> brandNames) { + this.brandNames = brandNames; + } + + /** + * @return the synonyms + * @see #synonyms + */ + public List<String> getSynonyms() { + return synonyms; + } + + /** + * @param synonyms + * the synonyms to set + * @see #synonyms + */ + public void setSynonyms(List<String> synonyms) { + this.synonyms = synonyms; + } + + /** + * Adds brand name into {@link #brandNames}. + * + * @param brandName + * object to add + */ + public void addBrandName(String brandName) { + this.brandNames.add(brandName); + } + + /** + * Adds synonym into {@link #synonyms}. + * + * @param synonym + * object to add + */ + public void addSynonym(String synonym) { + if (synonyms.contains(synonym)) { + logger.warn("Synonym already exists in the drug: " + synonym); + } else { + this.synonyms.add(synonym); + } + } + + /** + * Adds target into {@link #targets} list. + * + * @param target + * object to add + */ + public void addTarget(Target target) { + this.targets.add(target); + } + + /** + * @param source + * the source to add + * @see #sources + */ + public void addSource(MiriamData source) { + this.sources.add(source); + } + + /** + * @return the sources + * @see #sources + */ + public List<MiriamData> getSources() { + return sources; + } + + /** + * @return the targets + * @see #targets + */ + @XmlElement(name = "target") + public List<Target> getTargets() { + return targets; + } + + /** + * @param targets + * the targets to set + * @see #targets + */ + public void setTargets(List<Target> targets) { + this.targets = targets; + } + + /** + * @param sources + * the sources to set + * @see #sources + */ + public void setSources(List<MiriamData> sources) { + this.sources = sources; + } + + /** + * Adds targets to the drug. + * + * @param targets2 + * list of targets to add + */ + public void addTargets(List<Target> targets2) { + this.targets.addAll(targets2); + } + + /** + * @return the approved + * @see #approved + */ + public Boolean getApproved() { + return approved; + } + + /** + * @param approved + * the approved to set + * @see #approved + */ + public void setApproved(Boolean approved) { + this.approved = approved; + } + + /** + * Comparator of the objects by their name. + * + * @author Piotr Gawron + * + */ + public static class NameComparator implements Comparator<Drug> { + /** + * Default string comparator. + */ + private StringComparator stringComparator = new StringComparator(); + + @Override + public int compare(Drug arg0, Drug arg1) { + return stringComparator.compare(arg0.getName(), arg1.getName()); + } + + } } \ No newline at end of file diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/EntrezData.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/EntrezData.java index b826b8c412..8f5f10dfd5 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/EntrezData.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/EntrezData.java @@ -18,135 +18,136 @@ import lcsb.mapviewer.model.map.MiriamData; @XmlRootElement public class EntrezData implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Symbol of a gene. - */ - private String symbol = null; - - /** - * Full name of a gene. - */ - private String fullName = null; - - /** - * Synonyms of a gene. - */ - private List<String> synonyms = new ArrayList<>(); - - /** - * Description of a gene. - */ - private String description = null; - - /** - * Miriam annotations of a gene. - */ - private List<MiriamData> miriamData = new ArrayList<>(); - - /** - * @return the symbol - * @see #symbol - */ - public String getSymbol() { - return symbol; - } - - /** - * @param symbol - * the symbol to set - * @see #symbol - */ - public void setSymbol(String symbol) { - this.symbol = symbol; - } - - /** - * @return the fullName - * @see #fullName - */ - public String getFullName() { - return fullName; - } - - /** - * @param fullName - * the fullName to set - * @see #fullName - */ - public void setFullName(String fullName) { - this.fullName = fullName; - } - - /** - * @return the synonyms - * @see #synonyms - */ - public List<String> getSynonyms() { - return synonyms; - } - - /** - * @param synonyms - * the synonyms to set - * @see #synonyms - */ - public void setSynonyms(List<String> synonyms) { - this.synonyms = synonyms; - } - - /** - * @return the description - * @see #description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * @see #description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the miriamData - * @see #miriamData - */ - public List<MiriamData> getMiriamData() { - return miriamData; - } - - /** - * Adds {@link MiriamData} to the list of annotations. - * - * @param miriamData2 - * object to add - */ - public void addMiriamData(MiriamData miriamData2) { - this.miriamData.add(miriamData2); - } - - @Override - public String toString() { - String result = "Symbol: " + symbol + "\tFull name: " + fullName + "\tSynonyms: " + synonyms + "\tDescription: " + description + "\tMiriam: " + miriamData; - return result; - } - - /** - * @param miriamData - * the miriamData to set - * @see #miriamData - */ - public void setMiriamData(List<MiriamData> miriamData) { - this.miriamData = miriamData; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Symbol of a gene. + */ + private String symbol = null; + + /** + * Full name of a gene. + */ + private String fullName = null; + + /** + * Synonyms of a gene. + */ + private List<String> synonyms = new ArrayList<>(); + + /** + * Description of a gene. + */ + private String description = null; + + /** + * Miriam annotations of a gene. + */ + private List<MiriamData> miriamData = new ArrayList<>(); + + /** + * @return the symbol + * @see #symbol + */ + public String getSymbol() { + return symbol; + } + + /** + * @param symbol + * the symbol to set + * @see #symbol + */ + public void setSymbol(String symbol) { + this.symbol = symbol; + } + + /** + * @return the fullName + * @see #fullName + */ + public String getFullName() { + return fullName; + } + + /** + * @param fullName + * the fullName to set + * @see #fullName + */ + public void setFullName(String fullName) { + this.fullName = fullName; + } + + /** + * @return the synonyms + * @see #synonyms + */ + public List<String> getSynonyms() { + return synonyms; + } + + /** + * @param synonyms + * the synonyms to set + * @see #synonyms + */ + public void setSynonyms(List<String> synonyms) { + this.synonyms = synonyms; + } + + /** + * @return the description + * @see #description + */ + public String getDescription() { + return description; + } + + /** + * @param description + * the description to set + * @see #description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the miriamData + * @see #miriamData + */ + public List<MiriamData> getMiriamData() { + return miriamData; + } + + /** + * @param miriamData + * the miriamData to set + * @see #miriamData + */ + public void setMiriamData(List<MiriamData> miriamData) { + this.miriamData = miriamData; + } + + /** + * Adds {@link MiriamData} to the list of annotations. + * + * @param miriamData2 + * object to add + */ + public void addMiriamData(MiriamData miriamData2) { + this.miriamData.add(miriamData2); + } + + @Override + public String toString() { + String result = "Symbol: " + symbol + "\tFull name: " + fullName + "\tSynonyms: " + synonyms + "\tDescription: " + + description + "\tMiriam: " + miriamData; + return result; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Go.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Go.java index 8031d370f4..93ce1220e4 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Go.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Go.java @@ -12,75 +12,75 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement public class Go implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Human readable name. - */ - private String commonName; - - /** - * Description of the object. - */ - private String description; - - /** - * Go identifier. - */ - private String goTerm; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * @return the commonName - * @see #commonName - */ - public String getCommonName() { - return commonName; - } + /** + * Human readable name. + */ + private String commonName; - /** - * @param commonName - * the commonName to set - * @see #commonName - */ - public void setCommonName(String commonName) { - this.commonName = commonName; - } + /** + * Description of the object. + */ + private String description; - /** - * @return the description - * @see #description - */ - public String getDescription() { - return description; - } + /** + * Go identifier. + */ + private String goTerm; - /** - * @param description - * the description to set - * @see #description - */ - public void setDescription(String description) { - this.description = description; - } + /** + * @return the commonName + * @see #commonName + */ + public String getCommonName() { + return commonName; + } - /** - * @return the goTerm - * @see #goTerm - */ - public String getGoTerm() { - return goTerm; - } + /** + * @param commonName + * the commonName to set + * @see #commonName + */ + public void setCommonName(String commonName) { + this.commonName = commonName; + } - /** - * @param goTerm - * the goTerm to set - * @see #goTerm - */ - public void setGoTerm(String goTerm) { - this.goTerm = goTerm; - } + /** + * @return the description + * @see #description + */ + public String getDescription() { + return description; + } + + /** + * @param description + * the description to set + * @see #description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the goTerm + * @see #goTerm + */ + public String getGoTerm() { + return goTerm; + } + + /** + * @param goTerm + * the goTerm to set + * @see #goTerm + */ + public void setGoTerm(String goTerm) { + this.goTerm = goTerm; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/MeSH.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/MeSH.java index dfe74c5eb9..6cae7710f6 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/MeSH.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/MeSH.java @@ -1,14 +1,13 @@ package lcsb.mapviewer.annotation.data; import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; +import java.util.*; import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * This class represents <a href="http://www.nlm.nih.gov/cgi/mesh//">MeSH</a> @@ -20,164 +19,164 @@ import org.apache.logging.log4j.*; @XmlRootElement public class MeSH implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(MeSH.class); - - /** - * short name. - */ - private String name; - - /** - * MeSH identifier. - */ - private String meSHId; - - /** - * Detailed description of the MeSH object. - */ - private String description; - - /** - * List of synonyms. - */ - private List<String> synonyms = new ArrayList<>(); - - /** - * Default constructor. - */ - public MeSH() { - - } - - /** - * @param name - * short name. - * @param meSHId - * database identifier. - * @param description - * long description. - * @param synonyms - * list of terms used as names for this object. - */ - public MeSH(String meSHId, String name, String description, List<String> synonyms) { - super(); - this.name = name; - this.meSHId = meSHId; - this.description = description; - this.synonyms = synonyms; - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the synonyms - * @see #synonyms - */ - public List<String> getSynonyms() { - return synonyms; - } - - /** - * @param synonyms - * the synonyms to set - * @see #synonyms - */ - public void setSynonyms(List<String> synonyms) { - this.synonyms = synonyms; - } - - /** - * @return database identifier. - */ - public String getMeSHId() { - return meSHId; - } - - /** - * @return description of the object. - */ - public String getDescription() { - return description; - } - - /** - * @param meSHId - * database identifier - */ - public void setMeSHId(String meSHId) { - this.meSHId = meSHId; - } - - /** - * @param description - * long description. - */ - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - StringBuffer result = new StringBuffer(); - result.append("\nid: " + meSHId); - result.append("\nname: " + name); - result.append("\ndescription:" + description); - result.append("\nsynonyms:" + getSynonymsString()); - return result.toString(); - } - - /** - * @return list of synonyms as string. - */ - public String getSynonymsString() { - return StringUtils.join(synonyms, ","); - } - - /** - * Adds synonym to the synonym list. - * - * @param synonym - * synonym to add - */ - public void addSynonym(String synonym) { - synonyms.add(synonym); - } - - /** - * Adds synonyms to the synonym list. - * - * @param synonymsToAdd - * synonyms to add - */ - public void addSynonyms(Set<String> synonymsToAdd) { - for (String synonym : synonymsToAdd) { - this.synonyms.add(synonym); - } - - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(MeSH.class); + + /** + * short name. + */ + private String name; + + /** + * MeSH identifier. + */ + private String meSHId; + + /** + * Detailed description of the MeSH object. + */ + private String description; + + /** + * List of synonyms. + */ + private List<String> synonyms = new ArrayList<>(); + + /** + * Default constructor. + */ + public MeSH() { + + } + + /** + * @param name + * short name. + * @param meSHId + * database identifier. + * @param description + * long description. + * @param synonyms + * list of terms used as names for this object. + */ + public MeSH(String meSHId, String name, String description, List<String> synonyms) { + super(); + this.name = name; + this.meSHId = meSHId; + this.description = description; + this.synonyms = synonyms; + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the synonyms + * @see #synonyms + */ + public List<String> getSynonyms() { + return synonyms; + } + + /** + * @param synonyms + * the synonyms to set + * @see #synonyms + */ + public void setSynonyms(List<String> synonyms) { + this.synonyms = synonyms; + } + + /** + * @return database identifier. + */ + public String getMeSHId() { + return meSHId; + } + + /** + * @param meSHId + * database identifier + */ + public void setMeSHId(String meSHId) { + this.meSHId = meSHId; + } + + /** + * @return description of the object. + */ + public String getDescription() { + return description; + } + + /** + * @param description + * long description. + */ + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + StringBuffer result = new StringBuffer(); + result.append("\nid: " + meSHId); + result.append("\nname: " + name); + result.append("\ndescription:" + description); + result.append("\nsynonyms:" + getSynonymsString()); + return result.toString(); + } + + /** + * @return list of synonyms as string. + */ + public String getSynonymsString() { + return StringUtils.join(synonyms, ","); + } + + /** + * Adds synonym to the synonym list. + * + * @param synonym + * synonym to add + */ + public void addSynonym(String synonym) { + synonyms.add(synonym); + } + + /** + * Adds synonyms to the synonym list. + * + * @param synonymsToAdd + * synonyms to add + */ + public void addSynonyms(Set<String> synonymsToAdd) { + for (String synonym : synonymsToAdd) { + this.synonyms.add(synonym); + } + + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/MiRNA.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/MiRNA.java index 2602a1751a..aeef8f7704 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/MiRNA.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/MiRNA.java @@ -1,10 +1,7 @@ package lcsb.mapviewer.annotation.data; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; +import java.util.*; import javax.xml.bind.annotation.XmlRootElement; @@ -65,21 +62,6 @@ public class MiRNA implements Serializable, TargettingStructure { return result.toString(); } - /** - * @return list of genes plus publications. - */ - public List<Target> getTargets() { - return targets; - } - - /** - * @param targets - * list of genes plus publications. - */ - public void setTargets(List<Target> targets) { - this.targets = targets; - } - /** * @return id form Mirtarbase id. */ @@ -97,7 +79,7 @@ public class MiRNA implements Serializable, TargettingStructure { /** * Adds target to mirna. - * + * * @param target * target to add. */ @@ -111,6 +93,21 @@ public class MiRNA implements Serializable, TargettingStructure { return new ArrayList<>(); } + /** + * @return list of genes plus publications. + */ + public List<Target> getTargets() { + return targets; + } + + /** + * @param targets + * list of genes plus publications. + */ + public void setTargets(List<Target> targets) { + this.targets = targets; + } + /** * Comparator of the objects by their name. * diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Target.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Target.java index 20c0eaa0ad..1b2b36520c 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/Target.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/Target.java @@ -1,13 +1,12 @@ package lcsb.mapviewer.annotation.data; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; import javax.xml.bind.annotation.XmlElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargetType.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargetType.java index 6b695531bb..ce2cc04d75 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargetType.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargetType.java @@ -8,46 +8,46 @@ package lcsb.mapviewer.annotation.data; */ public enum TargetType { - /** - * Target is a single protein. - */ - SINGLE_PROTEIN("Single protein"), - - /** - * Target is a complex. - */ - COMPLEX_PROTEIN("Complex protein"), - - /** - * Target is a protein family. - */ - PROTEIN_FAMILY("Protein family"), - - /** - * Target is of other type. - */ - OTHER("Other"); - - /** - * Human readable name. - */ - private String commonName; - - /** - * Default constructor that creates enum position. - * - * @param commonName - * {@link #commonName} - */ - TargetType(String commonName) { - this.commonName = commonName; - } - - /** - * - * @return {@link #commonName} - */ - public String getCommonName() { - return commonName; - } + /** + * Target is a single protein. + */ + SINGLE_PROTEIN("Single protein"), + + /** + * Target is a complex. + */ + COMPLEX_PROTEIN("Complex protein"), + + /** + * Target is a protein family. + */ + PROTEIN_FAMILY("Protein family"), + + /** + * Target is of other type. + */ + OTHER("Other"); + + /** + * Human readable name. + */ + private String commonName; + + /** + * Default constructor that creates enum position. + * + * @param commonName + * {@link #commonName} + */ + TargetType(String commonName) { + this.commonName = commonName; + } + + /** + * + * @return {@link #commonName} + */ + public String getCommonName() { + return commonName; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargettingStructure.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargettingStructure.java index c35645c3da..6f1dbae2d3 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargettingStructure.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/TargettingStructure.java @@ -12,17 +12,17 @@ import lcsb.mapviewer.model.map.MiriamData; */ public interface TargettingStructure { - /** - * - * @return list of {@link MiriamData annotations} that describe source of this - * object - */ - Collection<MiriamData> getSources(); + /** + * + * @return list of {@link MiriamData annotations} that describe source of this + * object + */ + Collection<MiriamData> getSources(); - /** - * - * @return list of {@link Target targets} with which object is interacting - */ - Collection<Target> getTargets(); + /** + * + * @return list of {@link Target targets} with which object is interacting + */ + Collection<Target> getTargets(); } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/data/package-info.java b/annotation/src/main/java/lcsb/mapviewer/annotation/data/package-info.java index 1473f561a5..edfa64fa1f 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/data/package-info.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/data/package-info.java @@ -2,4 +2,3 @@ * Data structures used by annotation module. */ package lcsb.mapviewer.annotation.data; - diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChEMBLParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChEMBLParser.java index 4791f2adb2..37a429c6f0 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChEMBLParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChEMBLParser.java @@ -2,30 +2,18 @@ package lcsb.mapviewer.annotation.services; import java.io.IOException; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.data.Drug; -import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.data.TargetType; -import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; -import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; -import lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator; -import lcsb.mapviewer.annotation.services.annotators.UniprotSearchException; +import org.w3c.dom.*; + +import lcsb.mapviewer.annotation.cache.*; +import lcsb.mapviewer.annotation.data.*; +import lcsb.mapviewer.annotation.services.annotators.*; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.model.map.MiriamData; @@ -43,54 +31,45 @@ import lcsb.mapviewer.model.map.MiriamType; @Service public class ChEMBLParser extends DrugAnnotation implements IExternalService { + /** + * Prefix used in key for storing data by name. + */ + static final String NAME_PREFIX = "drug:"; /** * Url that access data of drug identified by drug chembl identifier. */ private static final String DRUG_BY_DRUG_ID_API_URL = "https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_chembl_id="; - /** * Url that access data about targetting mechanisms for a give drug chembl * identifier. */ private static final String TARGET_MECHANISM_BY_DRUG_ID_API_URL = "https://www.ebi.ac.uk/chembl/api/data/mechanism?molecule_chembl_id="; - /** * Url that access data about drugs identified by drug target identifier. */ private static final String DRUG_BY_TARGET_ID_API_URL = "https://www.ebi.ac.uk/chembl/api/data/mechanism?target_chembl_id="; - /** * Url that access data of drug identified by name. */ private static final String DRUG_NAME_API_URL = "https://www.ebi.ac.uk/chembl/api/data/molecule?pref_name__exact="; - /** * Url that access target by identifier. */ private static final String TARGET_API_URL = "https://www.ebi.ac.uk/chembl/api/data/target/"; - /** * Url that list of all child nodes for chembl ontology term. */ private static final String PARENT_CHILD_API_URL = "https://www.ebi.ac.uk/chembl/api/data/molecule_form/"; - /** * Suffix that should be added to {@link #PARENT_CHILD_API_URL}. */ private static final String PARENT_CHILD_API_URL_SUFFIX = ".xml"; - /** * Url used for finding targets containing uniprot identifiers. Important - for * now the limit of targets is 1000 so if more targets will be found this link * will not provide them. */ private static final String URL_TARGET_FROM_UNIPROT = "https://www.ebi.ac.uk/chembl/api/data/target?limit=1000&target_components__accession="; - - /** - * Prefix used in key for storing data by name. - */ - static final String NAME_PREFIX = "drug:"; - /** * Length of the prefix used in key for storing data by name. */ @@ -122,30 +101,9 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { this.hgncAnnotator = hgncAnnotator; } - @Override - public String refreshCacheQuery(Object query) throws SourceNotAvailable { - String result = null; - try { - if (query instanceof String) { - String name = (String) query; - if (name.startsWith(NAME_PREFIX)) { - name = name.substring(NAME_PREFIX_LENGTH); - result = getDrugSerializer().objectToString(findDrug(name)); - } else { - result = super.refreshCacheQuery(query); - } - } else { - result = super.refreshCacheQuery(query); - } - } catch (DrugSearchException e) { - throw new SourceNotAvailable(e); - } - return result; - } - /** * Returns target for given chembl identifier. - * + * * @param md * {@link MiriamType#CHEMBL_TARGET chembl identifier} of the target * @return target @@ -244,7 +202,7 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { /** * Parse node of target component to get information about * {@link MiriamType#HGNC_SYMBOL} identifier. - * + * * @param targetComponent * xml node to parse * @return {@link MiriamData} with {@link MiriamType#HGNC_SYMBOL} identifier @@ -272,7 +230,7 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { /** * Returns list of targets for given drug. - * + * * @param drugId * identifier of a drug for which targets are looked * @throws DrugSearchException @@ -321,7 +279,7 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { /** * Parse xml node with references. - * + * * @param referenceNode * node with references * @return list of references obtained from xml node @@ -396,10 +354,94 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { } } + @Override + public List<Drug> getDrugListByTarget(MiriamData target, Collection<MiriamData> organisms) + throws DrugSearchException { + List<Drug> result = new ArrayList<>(); + List<MiriamData> uniprotData = new ArrayList<>(); + if (MiriamType.HGNC_SYMBOL.equals(target.getDataType())) { + try { + uniprotData = hgncAnnotator.hgncToUniprot(target); + } catch (AnnotatorException e) { + throw new DrugSearchException("Cannot transform target into uniprot identifier", e); + } + } else if (MiriamType.UNIPROT.equals(target.getDataType())) { + uniprotData.add(target); + } else { + throw new DrugSearchException("Don't know how to process target of " + target.getDataType() + " type."); + } + if (uniprotData.size() == 0) { + return result; + } else if (uniprotData.size() > 1) { + logger.warn("Too many uniprot ids. Only first will be taken"); + } + try { + String url = URL_TARGET_FROM_UNIPROT + uniprotData.get(0).getResource(); + + String page = getWebPageContent(url); + Set<String> drugNames = new HashSet<>(); + + Document document = XmlParser.getXmlDocumentFromString(page); + + Node response = XmlParser.getNode("response", document); + Node targets = XmlParser.getNode("targets", response); + NodeList nodeList = targets.getChildNodes(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equalsIgnoreCase("target")) { + String organismName = XmlParser.getNode("organism", node).getTextContent(); + if (organismMatch(organismName, organisms)) { + Node chemblTargetIdNode = XmlParser.getNode("target_chembl_id", node); + MiriamData targetMiriam = new MiriamData(MiriamType.CHEMBL_TARGET, chemblTargetIdNode.getTextContent()); + List<Drug> drugs = getDrugsByChemblTarget(targetMiriam); + for (Drug drug : drugs) { + // don't add duplicates + if (!drugNames.contains(drug.getName())) { + drugNames.add(drug.getName()); + result.add(drug); + } + } + } + } + } + } + + } catch (IOException e) { + throw new DrugSearchException("Problem with accessing Chembl database", e); + } catch (InvalidXmlSchemaException e) { + throw new DrugSearchException("Problem with parsing Chembl response", e); + } + + return result; + + } + + @Override + public String refreshCacheQuery(Object query) throws SourceNotAvailable { + String result = null; + try { + if (query instanceof String) { + String name = (String) query; + if (name.startsWith(NAME_PREFIX)) { + name = name.substring(NAME_PREFIX_LENGTH); + result = getDrugSerializer().objectToString(findDrug(name)); + } else { + result = super.refreshCacheQuery(query); + } + } else { + result = super.refreshCacheQuery(query); + } + } catch (DrugSearchException e) { + throw new SourceNotAvailable(e); + } + return result; + } + /** * Parse xml node repesenting drug and returns drug with information obtained * from there and other places in chembl API. - * + * * @param node * xml node representing drug, sample can be found <a href= * "https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_chembl_id=CHEMBL2068724"> @@ -432,7 +474,7 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { /** * Get targets for chembl children nodes. - * + * * @param drugId * id of the parent drug * @return list of drug targets for children molecules in chembl ontology @@ -474,7 +516,7 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { /** * Parse xml node with synonyms. - * + * * @param synonymsNode * xml node with synonyms * @return list of synonyms obtained from the input xml @@ -498,7 +540,7 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { /** * Returns information about drug by chembl drug identifier. - * + * * @param drugId * {@link MiriamType#CHEMBL_COMPOUND chembl drug identifier} * @return drug by chembl drug identifier @@ -556,69 +598,6 @@ public class ChEMBLParser extends DrugAnnotation implements IExternalService { return status; } - @Override - public List<Drug> getDrugListByTarget(MiriamData target, Collection<MiriamData> organisms) - throws DrugSearchException { - List<Drug> result = new ArrayList<>(); - List<MiriamData> uniprotData = new ArrayList<>(); - if (MiriamType.HGNC_SYMBOL.equals(target.getDataType())) { - try { - uniprotData = hgncAnnotator.hgncToUniprot(target); - } catch (AnnotatorException e) { - throw new DrugSearchException("Cannot transform target into uniprot identifier", e); - } - } else if (MiriamType.UNIPROT.equals(target.getDataType())) { - uniprotData.add(target); - } else { - throw new DrugSearchException("Don't know how to process target of " + target.getDataType() + " type."); - } - if (uniprotData.size() == 0) { - return result; - } else if (uniprotData.size() > 1) { - logger.warn("Too many uniprot ids. Only first will be taken"); - } - try { - String url = URL_TARGET_FROM_UNIPROT + uniprotData.get(0).getResource(); - - String page = getWebPageContent(url); - Set<String> drugNames = new HashSet<>(); - - Document document = XmlParser.getXmlDocumentFromString(page); - - Node response = XmlParser.getNode("response", document); - Node targets = XmlParser.getNode("targets", response); - NodeList nodeList = targets.getChildNodes(); - for (int i = 0; i < nodeList.getLength(); i++) { - Node node = nodeList.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equalsIgnoreCase("target")) { - String organismName = XmlParser.getNode("organism", node).getTextContent(); - if (organismMatch(organismName, organisms)) { - Node chemblTargetIdNode = XmlParser.getNode("target_chembl_id", node); - MiriamData targetMiriam = new MiriamData(MiriamType.CHEMBL_TARGET, chemblTargetIdNode.getTextContent()); - List<Drug> drugs = getDrugsByChemblTarget(targetMiriam); - for (Drug drug : drugs) { - // don't add duplicates - if (!drugNames.contains(drug.getName())) { - drugNames.add(drug.getName()); - result.add(drug); - } - } - } - } - } - } - - } catch (IOException e) { - throw new DrugSearchException("Problem with accessing Chembl database", e); - } catch (InvalidXmlSchemaException e) { - throw new DrugSearchException("Problem with parsing Chembl response", e); - } - - return result; - - } - /** * Returns list of drugs found by target identified in the paramter. * diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java index 3519a430ba..381c637811 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java @@ -1,33 +1,20 @@ package lcsb.mapviewer.annotation.services; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.SerializationException; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Node; -import lcsb.mapviewer.annotation.cache.CachableInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; -import lcsb.mapviewer.annotation.data.Chemical; -import lcsb.mapviewer.annotation.data.ChemicalDirectEvidence; -import lcsb.mapviewer.annotation.data.MeSH; -import lcsb.mapviewer.annotation.data.Target; +import lcsb.mapviewer.annotation.cache.*; +import lcsb.mapviewer.annotation.data.*; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -47,108 +34,89 @@ import lcsb.mapviewer.persist.dao.ProjectDao; @Service public class ChemicalParser extends CachableInterface implements IExternalService { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(ChemicalParser.class); - - /** - * Prefix used for caching elements with chemical identifier as a key. - */ - static final String CHEMICAL_PREFIX = "chemical:"; - - /** - * Prefix used for caching all chemical names in a disease. - */ - protected static final String DISEASE_CHEMICALS_PREFIX = "DISEASE_CHEMICALS:"; - - /** - * Prefix used for caching list of suggested queries for project. - */ - protected static final String PROJECT_SUGGESTED_QUERY_PREFIX = "PROJECT_CHEMICAL_QUERIES:"; - - /** - * Home page of ctd database. - */ - static final String URL = "https://ctdbase.org/"; - - /** - * URL to get a list of chemicals by disease id. - */ - public static final String DISEASE_URL = URL + "detail.go?6578706f7274=1&d-1332398-e=5&view=chem&" - + "type=disease&acc=MESH%3A"; - - /** - * URL to get a list of chemicals by gene id. - */ - public static final String DISEASE_GENE_URL = URL + "detail.go?slimTerm=all&6578706f7274=1&qid=3464576&" - + "d-1332398-e=5&view=disease&type=gene&assnType=curated&acc="; - - /** - * Column in results obtained from {@link ChemicalParser#DISEASE_GENE_URL} - * describing drugs that are related to the gene (gene identifier is provided in - * the url). - */ - private static final int DRUG_NAME_COL_IN_GENE_DRUG_LIST = 3; - /** * The location of name column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_NAME_COL = 0; - /** * The location of id column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_ID_COL = 1; - /** * The location of CAS column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_CAS_COL = 2; - /** * The location of disease name column in the parsed tab separated chemicals * file. */ public static final Integer CHEMICALS_DISEASE_NAME_COL = 3; - /** * The location of disease id column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_DISEASE_ID_COL = 4; - /** * The location of direct column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_DIRECT_COL = 5; - /** * The location of network of genes column in the parsed tab separated chemicals * file. */ public static final Integer CHEMICALS_NETWORK_COL = 6; - /** * The location of score column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_SCORE_COL = 7; - /** * The location of count column in the parsed tab separated chemicals file. */ public static final Integer CHEMICALS_COUNT_COL = 8; - /** * The location of pubmed id column in the publications. */ public static final Integer PUBLICATIONS_ID_COL = 0; - /** * The location of list of genes column that is associated with this publication * for particular chemical. */ public static final Integer PUBLICATIONS_ASSOCIATION_COL = 5; - + /** + * Prefix used for caching all chemical names in a disease. + */ + protected static final String DISEASE_CHEMICALS_PREFIX = "DISEASE_CHEMICALS:"; + /** + * Prefix used for caching list of suggested queries for project. + */ + protected static final String PROJECT_SUGGESTED_QUERY_PREFIX = "PROJECT_CHEMICAL_QUERIES:"; + /** + * Prefix used for caching elements with chemical identifier as a key. + */ + static final String CHEMICAL_PREFIX = "chemical:"; + /** + * Home page of ctd database. + */ + static final String URL = "https://ctdbase.org/"; + /** + * URL to get a list of chemicals by disease id. + */ + public static final String DISEASE_URL = URL + "detail.go?6578706f7274=1&d-1332398-e=5&view=chem&" + + "type=disease&acc=MESH%3A"; + /** + * URL to get a list of chemicals by gene id. + */ + public static final String DISEASE_GENE_URL = URL + "detail.go?slimTerm=all&6578706f7274=1&qid=3464576&" + + "d-1332398-e=5&view=disease&type=gene&assnType=curated&acc="; + /** + * Column in results obtained from {@link ChemicalParser#DISEASE_GENE_URL} + * describing drugs that are related to the gene (gene identifier is provided in + * the url). + */ + private static final int DRUG_NAME_COL_IN_GENE_DRUG_LIST = 3; + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(ChemicalParser.class); /** * Object that allows to serialize {@link Chemical} elements into xml string and * deserialize xml into {@link Chemical} objects. @@ -367,6 +335,16 @@ public class ChemicalParser extends CachableInterface implements IExternalServic } } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + /** * @param diseaseID * the Mesh id of the disease. @@ -669,16 +647,6 @@ public class ChemicalParser extends CachableInterface implements IExternalServic this.hgncAnnotator = hgncAnnotator; } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - public List<String> getSuggestedQueryList(Project project, MiriamData diseaseMiriam) throws ChemicalSearchException { if (diseaseMiriam == null) { return new ArrayList<>(); @@ -687,7 +655,7 @@ public class ChemicalParser extends CachableInterface implements IExternalServic String cachedData = getCacheValue(cacheQuery); List<String> result; if (cachedData == null) { -// result = getSuggestedQueryListWithoutCache(project, diseaseMiriam); + // result = getSuggestedQueryListWithoutCache(project, diseaseMiriam); result = new ArrayList<>(); cachedData = StringUtils.join(result, "\n"); setCacheValue(cacheQuery, cachedData); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalSearchException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalSearchException.java index 6c06b5320f..e1f6b6d39a 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalSearchException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalSearchException.java @@ -8,41 +8,41 @@ package lcsb.mapviewer.annotation.services; */ public class ChemicalSearchException extends Exception { - /** - * Default constructor. - * - * @param string - * exception message - */ - public ChemicalSearchException(String string) { - super(string); - } + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param e - * parent exception - */ - public ChemicalSearchException(Exception e) { - super(e); - } + /** + * Default constructor. + * + * @param string + * exception message + */ + public ChemicalSearchException(String string) { + super(string); + } - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * source exception - */ - public ChemicalSearchException(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param e + * parent exception + */ + public ChemicalSearchException(Exception e) { + super(e); + } - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * source exception + */ + public ChemicalSearchException(String message, Exception e) { + super(message, e); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugAnnotation.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugAnnotation.java index 5cc8c49bbd..e05925aedc 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugAnnotation.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugAnnotation.java @@ -1,20 +1,14 @@ package lcsb.mapviewer.annotation.services; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; -import lcsb.mapviewer.annotation.cache.CachableInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Drug; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugSearchException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugSearchException.java index f52c229c3e..b5332ce490 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugSearchException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugSearchException.java @@ -8,41 +8,41 @@ package lcsb.mapviewer.annotation.services; */ public class DrugSearchException extends Exception { - /** - * Default constructor. - * - * @param string - * exception message - */ - public DrugSearchException(String string) { - super(string); - } + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param e - * parent exception - */ - public DrugSearchException(Exception e) { - super(e); - } + /** + * Default constructor. + * + * @param string + * exception message + */ + public DrugSearchException(String string) { + super(string); + } - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * source exception - */ - public DrugSearchException(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param e + * parent exception + */ + public DrugSearchException(Exception e) { + super(e); + } - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * source exception + */ + public DrugSearchException(String message, Exception e) { + super(message, e); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParser.java index b377b95434..51cab1bc64 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParser.java @@ -3,11 +3,7 @@ package lcsb.mapviewer.annotation.services; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -18,18 +14,12 @@ import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.data.Drug; -import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.data.TargetType; +import lcsb.mapviewer.annotation.cache.*; +import lcsb.mapviewer.annotation.data.*; import lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator; import lcsb.mapviewer.annotation.services.annotators.UniprotSearchException; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; /** * Class used for parsing and accessing data from html interfaces of drugbank @@ -42,63 +32,52 @@ import lcsb.mapviewer.model.map.MiriamType; @Service public class DrugbankHTMLParser extends DrugAnnotation implements IExternalService { - /** - * Maximum available length of the pubmed identifiers. - */ - private static final int MAX_PUBMED_IDENTIFIER_LENGTH = 9; - /** * Prefix used for storing data about drug with name key value. */ static final String DRUG_NAME_PREFIX = "drug:"; - - /** - * Service used for annotation of proteins using {@link MiriamType#UNIPROT - * uniprot}. - */ - private UniprotAnnotator uniprotAnnotator; - - /** - * Pattern that extract information about drug name when accessing page about - * target. - */ - private final Pattern drugNamePattern = Pattern.compile("(?<=<td><strong>)([\\s\\S]*?)(?=</strong></td>)"); - - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(DrugbankHTMLParser.class); - /** * Url used for finding drug by drug name. */ static final String URLB = "https://www.drugbank.ca/search?searcher=drugs&utf8=%E2%9C%93&button=&filter=false&query="; - /** * Url used for retrieving general information about drug. */ static final String URLDRUG = "https://www.drugbank.ca/drugs/"; - /** * Homepage of drugbank. */ static final String URL = "https://www.drugbank.ca/"; - /** * Url used for accessing information about target synonyms. */ static final String URLPEP = "https://www.drugbank.ca/polypeptides/"; - /** * Url that allows to search for drugs using target hgnc name. */ static final String URL_TARGETS = "https://www.drugbank.ca/search?utf8=%E2%9C%93&searcher=bio_entities&query="; - /** * Url that helps finding drug name for given target identifier. */ static final String URL_TARGET_DETAIL = "https://www.drugbank.ca/bio_entities/"; - + /** + * Maximum available length of the pubmed identifiers. + */ + private static final int MAX_PUBMED_IDENTIFIER_LENGTH = 9; + /** + * Pattern that extract information about drug name when accessing page about + * target. + */ + private final Pattern drugNamePattern = Pattern.compile("(?<=<td><strong>)([\\s\\S]*?)(?=</strong></td>)"); + /** + * Service used for annotation of proteins using {@link MiriamType#UNIPROT + * uniprot}. + */ + private UniprotAnnotator uniprotAnnotator; + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(DrugbankHTMLParser.class); /** * Pattern used to get information about {@link Drug#bloodBrainBarrier blood * brain barrier}. @@ -120,30 +99,9 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi this.uniprotAnnotator = uniprotAnnotator; } - @Override - public String refreshCacheQuery(Object query) throws SourceNotAvailable { - String result = null; - try { - if (query instanceof String) { - String name = (String) query; - if (name.startsWith(DRUG_NAME_PREFIX)) { - name = name.substring(DRUG_NAME_PREFIX.length()); - result = getDrugSerializer().objectToString(findDrug(name)); - } else { - result = super.refreshCacheQuery(query); - } - } else { - result = super.refreshCacheQuery(query); - } - } catch (DrugSearchException e) { - throw new SourceNotAvailable(e); - } - return result; - } - /** * Finds the drug identifier in the web page with information about drug. - * + * * @param webpageContent * content of the web page with information about drug * @return drugbank identifier @@ -161,7 +119,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Finds the drug name in the webpage with information about drug. - * + * * @param webpageContent * content of the webpage with information about drug * @return name of the drug @@ -178,7 +136,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Finds the description of the drug on the content of the web page with * information about drug. - * + * * @param webpageContent * content of the web page with information about drug * @return description of the drug @@ -204,7 +162,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Returns list of the drug brand names from the web page content. - * + * * @param page * content of the web page with information about drug * @return list of the drug brand names @@ -235,7 +193,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Returns list of drug synonyms from drugbank database. - * + * * @param page * web page content with drug information * @return list of drug synonyms @@ -264,7 +222,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Returns references from reference string (obtained from drugbank homepage) . - * + * * @param descriptionString * string containing references obtained from drugbank webpage * @return list of references obtained from drugbank {@link String} @@ -298,7 +256,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Returns targets parsed from page content. - * + * * @param page * webpage content from which data are extracted * @throws DrugSearchException @@ -358,7 +316,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Parse html info about target into {@link Target} structure. - * + * * @param htmlPage * string with html content * @return {@link Target} for given html content @@ -422,7 +380,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Finds information about drug in drugbank database. - * + * * @param name * name of the dug that we are looking for * @throws DrugSearchException @@ -482,7 +440,7 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Check if drug data mateches with the search name. - * + * * @param drug * drug to be checked * @param name @@ -511,10 +469,10 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Finds blood brain barrier info about drug in the webpage content. - * + * * @param page * webpage content used for parsing - * + * * @return status of blood brain barrier */ String getBloodBrainBarrier(String page) { @@ -543,10 +501,10 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi /** * Finds if drug is approved. - * + * * @param page * webpage content used for parsing - * + * * @return <code>true</code> if drug is approved */ private Boolean getApproved(String page) { @@ -599,27 +557,6 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi return drug; } - @Override - public ExternalServiceStatus getServiceStatus() { - ExternalServiceStatus status = new ExternalServiceStatus("DrugBank", URL); - - GeneralCacheInterface cacheCopy = getCache(); - this.setCache(null); - - try { - Drug drug = findDrug("Amantadine"); - status.setStatus(ExternalServiceStatusType.OK); - if (drug == null) { - status.setStatus(ExternalServiceStatusType.CHANGED); - } - } catch (Exception e) { - logger.error("DrugBank is down", e); - status.setStatus(ExternalServiceStatusType.DOWN); - } - this.setCache(cacheCopy); - return status; - } - @Override public List<Drug> getDrugListByTarget(MiriamData target, Collection<MiriamData> organisms) throws DrugSearchException { @@ -664,6 +601,48 @@ public class DrugbankHTMLParser extends DrugAnnotation implements IExternalServi } } + @Override + public String refreshCacheQuery(Object query) throws SourceNotAvailable { + String result = null; + try { + if (query instanceof String) { + String name = (String) query; + if (name.startsWith(DRUG_NAME_PREFIX)) { + name = name.substring(DRUG_NAME_PREFIX.length()); + result = getDrugSerializer().objectToString(findDrug(name)); + } else { + result = super.refreshCacheQuery(query); + } + } else { + result = super.refreshCacheQuery(query); + } + } catch (DrugSearchException e) { + throw new SourceNotAvailable(e); + } + return result; + } + + @Override + public ExternalServiceStatus getServiceStatus() { + ExternalServiceStatus status = new ExternalServiceStatus("DrugBank", URL); + + GeneralCacheInterface cacheCopy = getCache(); + this.setCache(null); + + try { + Drug drug = findDrug("Amantadine"); + status.setStatus(ExternalServiceStatusType.OK); + if (drug == null) { + status.setStatus(ExternalServiceStatusType.CHANGED); + } + } catch (Exception e) { + logger.error("DrugBank is down", e); + status.setStatus(ExternalServiceStatusType.DOWN); + } + this.setCache(cacheCopy); + return status; + } + boolean isDrugContainTarget(MiriamData targetMiriamData, Drug drug) { boolean targets = false; for (Target target : drug.getTargets()) { diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatus.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatus.java index dd45fbfd58..f7bd01cacd 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatus.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatus.java @@ -9,83 +9,83 @@ package lcsb.mapviewer.annotation.services; */ public class ExternalServiceStatus { - /** - * Name of the service. - */ - private String name; + /** + * Name of the service. + */ + private String name; - /** - * Status of the external resource. - */ - private ExternalServiceStatusType status; + /** + * Status of the external resource. + */ + private ExternalServiceStatusType status; - /** - * Webpage associated with external resource. - */ - private String page; + /** + * Webpage associated with external resource. + */ + private String page; - /** - * Default constructor. - * - * @param name - * name of the service - * @param page - * webpage associated with the external resource - */ - public ExternalServiceStatus(String name, String page) { - this.setName(name); - this.setPage(page); - } + /** + * Default constructor. + * + * @param name + * name of the service + * @param page + * webpage associated with the external resource + */ + public ExternalServiceStatus(String name, String page) { + this.setName(name); + this.setPage(page); + } - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } - /** - * @return the status - * @see #status - */ - public ExternalServiceStatusType getStatus() { - return status; - } + /** + * @return the status + * @see #status + */ + public ExternalServiceStatusType getStatus() { + return status; + } - /** - * @param status - * the status to set - * @see #status - */ - public void setStatus(ExternalServiceStatusType status) { - this.status = status; - } + /** + * @param status + * the status to set + * @see #status + */ + public void setStatus(ExternalServiceStatusType status) { + this.status = status; + } - /** - * @return the page - * @see #page - */ - public String getPage() { - return page; - } + /** + * @return the page + * @see #page + */ + public String getPage() { + return page; + } - /** - * @param page - * the page to set - * @see #page - */ - public void setPage(String page) { - this.page = page; - } + /** + * @param page + * the page to set + * @see #page + */ + public void setPage(String page) { + this.page = page; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusType.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusType.java index 2e3092188b..c3666cd684 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusType.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusType.java @@ -7,59 +7,59 @@ package lcsb.mapviewer.annotation.services; * */ public enum ExternalServiceStatusType { - - /** - * Service is ok and access method is ok. - */ - OK("Ok", 0), - - /** - * Service is down (we don't know anything about access method). - */ - DOWN("Not available", 1), - - /** - * Service is up, but access method changed. - */ - CHANGED("Specification changed", 2); - /** - * Common name of the status. - */ - private String commonName; - - /** - * Severity level of the status (the higher the worse). - */ - private int level; + /** + * Service is ok and access method is ok. + */ + OK("Ok", 0), - /** - * Default constructor. - * - * @param commonName - * name of the status - * @param level - * severity level of the status - */ - ExternalServiceStatusType(String commonName, int level) { - this.commonName = commonName; - this.level = level; - } + /** + * Service is down (we don't know anything about access method). + */ + DOWN("Not available", 1), - /** - * @return the commonName - * @see #commonName - */ - public String getCommonName() { - return commonName; - } + /** + * Service is up, but access method changed. + */ + CHANGED("Specification changed", 2); - /** - * @return the level - * @see #level - */ - public int getLevel() { - return level; - } + /** + * Common name of the status. + */ + private String commonName; + + /** + * Severity level of the status (the higher the worse). + */ + private int level; + + /** + * Default constructor. + * + * @param commonName + * name of the status + * @param level + * severity level of the status + */ + ExternalServiceStatusType(String commonName, int level) { + this.commonName = commonName; + this.level = level; + } + + /** + * @return the commonName + * @see #commonName + */ + public String getCommonName() { + return commonName; + } + + /** + * @return the level + * @see #level + */ + public int getLevel() { + return level; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/IExternalService.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/IExternalService.java index a6d859ef72..764897e279 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/IExternalService.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/IExternalService.java @@ -1,6 +1,5 @@ package lcsb.mapviewer.annotation.services; - /** * Interface that should be implemented by all classes that access external * resources. @@ -9,22 +8,21 @@ package lcsb.mapviewer.annotation.services; * */ public interface IExternalService { - /** - * Returns status of the external resource. - * - * @return status of the external resource. Three different values are - * possible: - * <ul> - * <li> - * {@link lcsb.mapviewer.annotation.services.ExternalServiceStatus.Status#OK - * OK}</li> - * <li> - * {@link lcsb.mapviewer.annotation.services.ExternalServiceStatus.Status#DOWN - * DOWN}</li> - * <li> - * {@link lcsb.mapviewer.annotation.services.ExternalServiceStatus.Status#CHANGED - * CHANGED}</li> - * </ul> - */ - ExternalServiceStatus getServiceStatus(); + /** + * Returns status of the external resource. + * + * @return status of the external resource. Three different values are possible: + * <ul> + * <li> + * {@link lcsb.mapviewer.annotation.services.ExternalServiceStatus.Status#OK + * OK}</li> + * <li> + * {@link lcsb.mapviewer.annotation.services.ExternalServiceStatus.Status#DOWN + * DOWN}</li> + * <li> + * {@link lcsb.mapviewer.annotation.services.ExternalServiceStatus.Status#CHANGED + * CHANGED}</li> + * </ul> + */ + ExternalServiceStatus getServiceStatus(); } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java index 4337be731d..65b8f1b17a 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ImproperAnnotations.java @@ -18,60 +18,60 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class ImproperAnnotations implements ProblematicAnnotation { - /** - * {@link BioEntity} improperly annotated. - */ - private BioEntity bioEntity; + /** + * {@link BioEntity} improperly annotated. + */ + private BioEntity bioEntity; - /** - * Wrong miriam data. - */ - private List<MiriamData> wrongAnnotations = new ArrayList<>(); + /** + * Wrong miriam data. + */ + private List<MiriamData> wrongAnnotations = new ArrayList<>(); - /** - * Constructor that initializes the data with {@link #bioEntity bioEntity} and - * list of improper {@link MiriamData}. - * - * @param list - * list of improper {@link MiriamData} - * @param bioEntity - * bioentity - */ - public ImproperAnnotations(BioEntity bioEntity, List<MiriamData> list) { - if (list.size() == 0) { - throw new InvalidArgumentException("List of improper annotations cannot be null"); - } - this.bioEntity = bioEntity; - wrongAnnotations.addAll(list); - } + /** + * Constructor that initializes the data with {@link #bioEntity bioEntity} and + * list of improper {@link MiriamData}. + * + * @param list + * list of improper {@link MiriamData} + * @param bioEntity + * bioentity + */ + public ImproperAnnotations(BioEntity bioEntity, List<MiriamData> list) { + if (list.size() == 0) { + throw new InvalidArgumentException("List of improper annotations cannot be null"); + } + this.bioEntity = bioEntity; + wrongAnnotations.addAll(list); + } - /** - * Constructor that initializes the data with {@link #bioEntity bio entity} - * and improper {@link MiriamData}. - * - * @param miriamData - * invalid {@link MiriamData} - * @param bioEntity - * annotated object - */ - public ImproperAnnotations(BioEntity bioEntity, MiriamData miriamData) { - this.bioEntity = bioEntity; - wrongAnnotations.add(miriamData); - } + /** + * Constructor that initializes the data with {@link #bioEntity bio entity} and + * improper {@link MiriamData}. + * + * @param miriamData + * invalid {@link MiriamData} + * @param bioEntity + * annotated object + */ + public ImproperAnnotations(BioEntity bioEntity, MiriamData miriamData) { + this.bioEntity = bioEntity; + wrongAnnotations.add(miriamData); + } - @Override - public String getMessage() { - StringBuilder result = new StringBuilder(new ElementUtils().getElementTag(bioEntity)); - result.append("contains invalid annotations: "); - for (MiriamData miriamData : wrongAnnotations) { - result.append(miriamData.getDataType().getCommonName() + "(" + miriamData.getResource() + "), "); - } - return result.toString(); - } + @Override + public String getMessage() { + StringBuilder result = new StringBuilder(new ElementUtils().getElementTag(bioEntity)); + result.append("contains invalid annotations: "); + for (MiriamData miriamData : wrongAnnotations) { + result.append(miriamData.getDataType().getCommonName() + "(" + miriamData.getResource() + "), "); + } + return result.toString(); + } - @Override - public String toString() { - return getMessage(); - } + @Override + public String toString() { + return getMessage(); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MeSHParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MeSHParser.java index f178fc9cef..e94b209278 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MeSHParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MeSHParser.java @@ -1,26 +1,18 @@ package lcsb.mapviewer.annotation.services; import java.io.IOException; -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.*; import org.apache.commons.lang3.SerializationException; import org.apache.http.HttpStatus; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.w3c.dom.Node; import com.google.gson.Gson; -import lcsb.mapviewer.annotation.cache.CachableInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.MeSH; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -36,21 +28,18 @@ import lcsb.mapviewer.model.map.MiriamType; @Service public class MeSHParser extends CachableInterface implements IExternalService { + /** + * Prefix used in the DB to identify the cache entry. + */ + static final String MESH_PREFIX = "mesh:"; /** * Url used for searching drugs by name. */ private static final String URL_MESH_DATABASE = "https://meshb.nlm.nih.gov/api/record/ui/"; - /** * Url used for searching mesh terms by synonym. */ private static final String URL_SEARCH_BY_SYNONYM = "https://meshb.nlm.nih.gov/api/search/record?searchInField=termDescriptor&sort=&size=20&searchType=exactMatch&searchMethod=FullWord&q="; - - /** - * Prefix used in the DB to identify the cache entry. - */ - static final String MESH_PREFIX = "mesh:"; - /** * Default class logger. */ @@ -99,6 +88,16 @@ public class MeSHParser extends CachableInterface implements IExternalService { return result; } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + /** * @param meshID * miriam type id. @@ -189,7 +188,7 @@ public class MeSHParser extends CachableInterface implements IExternalService { /** * Extracts name from gson object. - * + * * @param gsonObject * gson to process * @return name of {@link MeSH} entry @@ -204,7 +203,7 @@ public class MeSHParser extends CachableInterface implements IExternalService { /** * Extracts Mesh id name from gson object. - * + * * @param gsonObject * gson to process * @return id of {@link MeSH} entry @@ -219,7 +218,7 @@ public class MeSHParser extends CachableInterface implements IExternalService { /** * Extracts Mesh term description from gson object. - * + * * @param gsonObject * gson to process * @return description of {@link MeSH} entry @@ -231,7 +230,7 @@ public class MeSHParser extends CachableInterface implements IExternalService { /** * Extracts list of synonyms from gson object. - * + * * @param gsonObject * gson to process * @return synonyms of {@link MeSH} entry @@ -276,7 +275,7 @@ public class MeSHParser extends CachableInterface implements IExternalService { /** * Checks if the mesh identifier is valid. - * + * * @param meshId * mesh id * @return <code>true</code> if it's valid @@ -290,16 +289,6 @@ public class MeSHParser extends CachableInterface implements IExternalService { return getMeSH(meshId) != null; } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - public List<MeSH> getMeshBySynonym(String synonym) throws AnnotatorException { try { List<MeSH> result = new ArrayList<>(); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNAParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNAParser.java index 166a177023..bb6dec3baa 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNAParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNAParser.java @@ -1,47 +1,22 @@ package lcsb.mapviewer.annotation.services; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.poi.poifs.filesystem.NotOLE2FileException; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Node; -import lcsb.mapviewer.annotation.cache.BigFileCache; -import lcsb.mapviewer.annotation.cache.CachableInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.XmlSerializer; -import lcsb.mapviewer.annotation.data.MiRNA; -import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.data.TargetType; +import lcsb.mapviewer.annotation.cache.*; +import lcsb.mapviewer.annotation.data.*; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; import lcsb.mapviewer.common.IProgressUpdater; @@ -62,65 +37,53 @@ import lcsb.mapviewer.persist.dao.ProjectDao; @Service public class MiRNAParser extends CachableInterface implements IExternalService { - /** - * Url used for searching mirna by name. - */ - private static final String URL_SOURCE_DATABASE = "http://mirtarbase.mbc.nctu.edu.tw/cache/download/6.1/miRTarBase_SE_WR.xls"; - - /** - * Cached file with static database about miriam (right now we parse it from - * excel file). - */ - private ByteArrayOutputStream sourceInputStream; - - /** - * Prefix used in the DB to identify the cache entry. - */ - protected static final String MI_RNA_PREFIX = "mirBase:"; - - protected static final String PROJECT_SUGGESTED_QUERY_PREFIX = "PROJECT_MI_RNA_QUERIES:"; - - /** - * Prefix used in the DB to identify the cache entry that will have information - * about mirna that targets specific target. - */ - static final String MI_RNA_TARGET_PREFIX = "MIRNA_TARGET:"; - /** * The location of Mirtarbase id column of Mirtarbase database. */ public static final Integer MIR_TAR_BASE_ID_COL = 0; - /** * The location of Mirbase name column of Mirbase database. */ public static final Integer MIR_BASE_NAME_COL = 1; - /** * The location of species column. */ public static final Integer SPECIES_COL = 5; - /** * The location of target gene HGNC ID column. */ public static final Integer GENE_HGNC_ID_COL = 3; - /** * The location of target gene ENTREZ ID column. */ public static final Integer GENE_ENTREZ_ID_COL = 4; - /** * The location of publication PEDMED ID column. */ public static final Integer INTERACTION_PEDMED_ID_COL = 8; - + /** + * Prefix used in the DB to identify the cache entry. + */ + protected static final String MI_RNA_PREFIX = "mirBase:"; + protected static final String PROJECT_SUGGESTED_QUERY_PREFIX = "PROJECT_MI_RNA_QUERIES:"; + /** + * Prefix used in the DB to identify the cache entry that will have information + * about mirna that targets specific target. + */ + static final String MI_RNA_TARGET_PREFIX = "MIRNA_TARGET:"; + /** + * Url used for searching mirna by name. + */ + private static final String URL_SOURCE_DATABASE = "http://mirtarbase.mbc.nctu.edu.tw/cache/download/6.1/miRTarBase_SE_WR.xls"; /** * Size of the buffer when copying files. */ private static final int BUFFER_SIZE = 1024; - + /** + * Cached file with static database about miriam (right now we parse it from + * excel file). + */ + private ByteArrayOutputStream sourceInputStream; /** * Default class logger. */ @@ -157,9 +120,9 @@ public class MiRNAParser extends CachableInterface implements IExternalService { */ @Autowired public MiRNAParser(TaxonomyBackend taxonomyBackend, - HgncAnnotator hgncAnnotator, - BigFileCache bigFileCache, - ProjectDao projectDao) { + HgncAnnotator hgncAnnotator, + BigFileCache bigFileCache, + ProjectDao projectDao) { super(MiRNAParser.class); miRnaSerializer = new XmlSerializer<>(MiRNA.class); this.taxonomyBackend = taxonomyBackend; @@ -268,7 +231,7 @@ public class MiRNAParser extends CachableInterface implements IExternalService { String filename = bigFileCache.getAbsolutePathForFile(URL_SOURCE_DATABASE); this.sourceInputStream = downloadedFileToInputStream(filename); - //if downloaded file is corrupted download it again + // if downloaded file is corrupted download it again try { POIFSFileSystem element = new POIFSFileSystem(new ByteArrayInputStream(sourceInputStream.toByteArray())); element.close(); diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNASearchException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNASearchException.java index e63f663df4..5090f6bff0 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNASearchException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiRNASearchException.java @@ -8,40 +8,40 @@ package lcsb.mapviewer.annotation.services; */ public class MiRNASearchException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param string - * exception message - */ - public MiRNASearchException(String string) { - super(string); - } + /** + * Default constructor. + * + * @param string + * exception message + */ + public MiRNASearchException(String string) { + super(string); + } - /** - * Default constructor. - * - * @param e - * parent exception - */ - public MiRNASearchException(Exception e) { - super(e); - } + /** + * Default constructor. + * + * @param e + * parent exception + */ + public MiRNASearchException(Exception e) { + super(e); + } - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * source exception - */ - public MiRNASearchException(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * source exception + */ + public MiRNASearchException(String message, Exception e) { + super(message, e); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java index c4b3c8e7d4..86bcd1aa80 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MiriamConnector.java @@ -23,21 +23,19 @@ import lcsb.mapviewer.model.map.*; */ @Service public final class MiriamConnector extends CachableInterface implements IExternalService { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(MiriamConnector.class); - /** * String used to distinguish cached data for links. */ static final String LINK_DB_PREFIX = "Link: "; - /** * String describing invalid miriam entries that will be put into db (instead of * null). */ private static final String INVALID_LINK = "INVALID"; + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(MiriamConnector.class); /** * Default class constructor. Prevent initialization. @@ -69,9 +67,19 @@ public final class MiriamConnector extends CachableInterface implements IExterna return result; } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + /** * Returns url to the web page represented by {@link MiriamData} parameter. - * + * * @param miriamData * miriam data * @return url to resource pointed by miriam data @@ -160,7 +168,7 @@ public final class MiriamConnector extends CachableInterface implements IExterna /** * Check if identifier can be transformed into {@link MiriamData}. - * + * * @param string * identifier in the format NAME:IDENTIFIER. Where NAME is the name * from {@link MiriamType#getCommonName()} and IDENTIFIER is resource @@ -179,7 +187,7 @@ public final class MiriamConnector extends CachableInterface implements IExterna /** * Checks if {@link MiriamType} is valid. - * + * * @param type * type to be checked * @return <code>true</code> if {@link MiriamType} is valid, <code>false</code> @@ -194,7 +202,7 @@ public final class MiriamConnector extends CachableInterface implements IExterna /** * Returns uri to miriam resource. - * + * * @param md * {@link MiriamData} object for which uri should be returned * @return uri to miriam resource @@ -202,14 +210,4 @@ public final class MiriamConnector extends CachableInterface implements IExterna public String miriamDataToUri(MiriamData md) { return md.getDataType().getUris().get(0) + ":" + md.getResource(); } - - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java index 1dd95d2302..6f62351bd4 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingAnnotation.java @@ -12,29 +12,29 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class MissingAnnotation implements ProblematicAnnotation { - /** - * BioEntity improperly annotated. - */ - private BioEntity bioEntity; + /** + * BioEntity improperly annotated. + */ + private BioEntity bioEntity; - /** - * Constructor that initializes the data with {@link #bioEntity bioEntity} . - * - * @param bioEntity - * bioEntity that misses annotation - */ - public MissingAnnotation(BioEntity bioEntity) { - this.bioEntity = bioEntity; - } + /** + * Constructor that initializes the data with {@link #bioEntity bioEntity} . + * + * @param bioEntity + * bioEntity that misses annotation + */ + public MissingAnnotation(BioEntity bioEntity) { + this.bioEntity = bioEntity; + } - @Override - public String getMessage() { - return new ElementUtils().getElementTag(bioEntity) + "misses annotations."; - } + @Override + public String getMessage() { + return new ElementUtils().getElementTag(bioEntity) + "misses annotations."; + } - @Override - public String toString() { - return getMessage(); - } + @Override + public String toString() { + return getMessage(); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java index bc57929783..291b370178 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotations.java @@ -1,13 +1,9 @@ package lcsb.mapviewer.annotation.services; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.modelutils.map.ElementUtils; /** @@ -19,46 +15,46 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class MissingRequiredAnnotations implements ProblematicAnnotation { - /** - * BioEntity improperly annotated. - */ - private BioEntity bioEntity; - - /** - * Required miriam type. - */ - private List<MiriamType> requiredMiriamType = new ArrayList<>(); - - /** - * Constructor that initializes the data with {@link #bioEntity bioEntity} and - * list of improper {@link MiriamData}. - * - * @param list - * list of missing but required {@link MiriamType} - * @param bioEntity - * {@link BioEntity} - */ - public MissingRequiredAnnotations(BioEntity bioEntity, Collection<MiriamType> list) { - if (list.size() == 0) { - throw new InvalidArgumentException("List of improper annotations cannot be null"); - } - this.bioEntity = bioEntity; - requiredMiriamType.addAll(list); - } - - @Override - public String getMessage() { - StringBuilder result = new StringBuilder(new ElementUtils().getElementTag(bioEntity)); - result.append("misses one of the following annotations: "); - for (MiriamType type : requiredMiriamType) { - result.append(type.getCommonName() + ", "); - } - return result.toString(); - } - - @Override - public String toString() { - return getMessage(); - } + /** + * BioEntity improperly annotated. + */ + private BioEntity bioEntity; + + /** + * Required miriam type. + */ + private List<MiriamType> requiredMiriamType = new ArrayList<>(); + + /** + * Constructor that initializes the data with {@link #bioEntity bioEntity} and + * list of improper {@link MiriamData}. + * + * @param list + * list of missing but required {@link MiriamType} + * @param bioEntity + * {@link BioEntity} + */ + public MissingRequiredAnnotations(BioEntity bioEntity, Collection<MiriamType> list) { + if (list.size() == 0) { + throw new InvalidArgumentException("List of improper annotations cannot be null"); + } + this.bioEntity = bioEntity; + requiredMiriamType.addAll(list); + } + + @Override + public String getMessage() { + StringBuilder result = new StringBuilder(new ElementUtils().getElementTag(bioEntity)); + result.append("misses one of the following annotations: "); + for (MiriamType type : requiredMiriamType) { + result.append(type.getCommonName() + ", "); + } + return result.toString(); + } + + @Override + public String toString() { + return getMessage(); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java index f2c8889279..28e51f6e7e 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java @@ -1,17 +1,10 @@ package lcsb.mapviewer.annotation.services; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; +import java.util.*; import org.apache.commons.collections4.ListUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -19,9 +12,7 @@ import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.ElementAnnotator; import lcsb.mapviewer.common.IProgressUpdater; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; @@ -52,17 +43,14 @@ public class ModelAnnotator { * {@link #performAnnotations(Model, IProgressUpdater)} method. */ private static final double COPYING_RATIO = 0.2; - - /** - * Connector used for accessing data from miriam registry. - */ - private MiriamConnector miriamConnector; - /** * Default class logger. */ private static Logger logger = LogManager.getLogger(ModelAnnotator.class); - + /** + * Connector used for accessing data from miriam registry. + */ + private MiriamConnector miriamConnector; /** * List of all avaliable {@link ElementAnnotator} objects. */ diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ProblematicAnnotation.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ProblematicAnnotation.java index 90e41d1cfe..b2404c82d6 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ProblematicAnnotation.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ProblematicAnnotation.java @@ -8,10 +8,10 @@ package lcsb.mapviewer.annotation.services; */ public interface ProblematicAnnotation { - /** - * Returns error message. - * - * @return problem error message - */ - String getMessage(); + /** + * Returns error message. + * + * @return problem error message + */ + String getMessage(); } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedParser.java index e26017f9f9..60f0c7fc60 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedParser.java @@ -1,29 +1,21 @@ package lcsb.mapviewer.annotation.services; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; +import javax.xml.xpath.*; -import lcsb.mapviewer.common.XmlParser; import org.apache.commons.lang3.SerializationException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.NodeList; -import lcsb.mapviewer.annotation.cache.CachableInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Article; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; @@ -48,19 +40,15 @@ public class PubmedParser extends CachableInterface implements IExternalService * Prefix used for caching elements with pubmed identifier as a key. */ static final String PUBMED_PREFIX = "pubmed: "; - - /** - * Length of {@link #PUBMED_PREFIX} string. - */ - private static final int PUBMED_PREFIX_LENGTH = PUBMED_PREFIX.length(); - /** * Version of the remote API that is supported by this connecting class. */ static final String SUPPORTED_VERSION = "6.1"; - static final String API_URL = "https://www.ebi.ac.uk/europepmc/webservices/rest/"; - + /** + * Length of {@link #PUBMED_PREFIX} string. + */ + private static final int PUBMED_PREFIX_LENGTH = PUBMED_PREFIX.length(); /** * Connector used for accessing data from miriam registry. */ @@ -77,6 +65,17 @@ public class PubmedParser extends CachableInterface implements IExternalService */ private XmlSerializer<Article> articleSerializer; + /** + * Constructor. Initializes structures used for transforming {@link Article} + * from/to xml. + */ + @Autowired + public PubmedParser(MiriamConnector miriamConnector) { + super(PubmedParser.class); + articleSerializer = new XmlSerializer<>(Article.class); + this.miriamConnector = miriamConnector; + } + @Override public Object refreshCacheQuery(Object query) throws SourceNotAvailable { Object result = null; @@ -99,20 +98,19 @@ public class PubmedParser extends CachableInterface implements IExternalService return result; } - /** - * Constructor. Initializes structures used for transforming {@link Article} - * from/to xml. - */ - @Autowired - public PubmedParser(MiriamConnector miriamConnector) { - super(PubmedParser.class); - articleSerializer = new XmlSerializer<>(Article.class); - this.miriamConnector = miriamConnector; + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); } /** * Returns article data for given pubmed identifier. - * + * * @param id * pubmed identifier * @return article data @@ -218,7 +216,7 @@ public class PubmedParser extends CachableInterface implements IExternalService /** * This method return html \< a\ > tag with link for pubmed id (with some * additional information). - * + * * @param id * pubmed identifier * @param withTextPrefix @@ -245,7 +243,7 @@ public class PubmedParser extends CachableInterface implements IExternalService /** * This method return html \< a\ > tag with link for pubmed id (with some * additional information). - * + * * @param id * pubmed identifier * @return link to webpage with pubmed article @@ -259,7 +257,7 @@ public class PubmedParser extends CachableInterface implements IExternalService /** * Get the summary of the article. - * + * * @param id * pubmed identifier * @return summary of the article. @@ -304,7 +302,7 @@ public class PubmedParser extends CachableInterface implements IExternalService /** * Returns current version of the pmc API. - * + * * @return version of the API to which this class is connected * @throws PubmedSearchException * thrown when there is a problem with accessing external database @@ -334,7 +332,7 @@ public class PubmedParser extends CachableInterface implements IExternalService /** * Get the summary of the article. - * + * * @param id * pubmed identifier * @return summary of the article. @@ -380,14 +378,4 @@ public class PubmedParser extends CachableInterface implements IExternalService this.articleSerializer = articleSerializer; } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedSearchException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedSearchException.java index ae2d8cf115..64acc6532c 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedSearchException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/PubmedSearchException.java @@ -8,31 +8,31 @@ package lcsb.mapviewer.annotation.services; */ public class PubmedSearchException extends Exception { - /** - * Default constructor. - * - * @param e - * parent exception - */ - public PubmedSearchException(Exception e) { - super(e); - } + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * source exception - */ - public PubmedSearchException(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param e + * parent exception + */ + public PubmedSearchException(Exception e) { + super(e); + } - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * source exception + */ + public PubmedSearchException(String message, Exception e) { + super(message, e); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java index dffc032f82..e694c4c101 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomyBackend.java @@ -5,16 +5,14 @@ import java.net.URLEncoder; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Service; -import lcsb.mapviewer.annotation.cache.CachableInterface; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import org.springframework.stereotype.Service; /** * This class is a backend to Taxonomy. @@ -41,6 +39,17 @@ public class TaxonomyBackend extends CachableInterface implements IExternalServi * by taxonomy id. */ static final String TAXONOMY_NAME_CACHE_PREFIX = "TAXONOMY_NAME_BY_ID: "; + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(TaxonomyBackend.class); + + /** + * Default constructor. + */ + public TaxonomyBackend() { + super(TaxonomyBackend.class); + } @Override public String refreshCacheQuery(Object query) throws SourceNotAvailable { @@ -71,6 +80,16 @@ public class TaxonomyBackend extends CachableInterface implements IExternalServi return result; } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + /** * Returns {@link MiriamData} representing taxonomy identified by name. * @@ -85,8 +104,8 @@ public class TaxonomyBackend extends CachableInterface implements IExternalServi return null; } if (term.equalsIgnoreCase("Humans")) { - term="Human"; - } + term = "Human"; + } String res = getCacheValue(TAXONOMY_CACHE_PREFIX + term); if (res != null) { if (res.equals("null")) { @@ -134,18 +153,6 @@ public class TaxonomyBackend extends CachableInterface implements IExternalServi } - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(TaxonomyBackend.class); - - /** - * Default constructor. - */ - public TaxonomyBackend() { - super(TaxonomyBackend.class); - } - @Override public ExternalServiceStatus getServiceStatus() { ExternalServiceStatus status = new ExternalServiceStatus(MiriamType.TAXONOMY.getCommonName(), @@ -207,14 +214,4 @@ public class TaxonomyBackend extends CachableInterface implements IExternalServi } } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomySearchException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomySearchException.java index ce90c04e61..02ec2c2031 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomySearchException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/TaxonomySearchException.java @@ -9,22 +9,22 @@ package lcsb.mapviewer.annotation.services; */ public class TaxonomySearchException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructs a new exception with the specified detail message and cause. - * - * @param message - * the detail message - * @param cause - * the cause (A <tt>null</tt> value is permitted, and indicates that - * the cause is nonexistent or unknown.) - */ - public TaxonomySearchException(String message, Throwable cause) { - super(message, cause); - } + /** + * Constructs a new exception with the specified detail message and cause. + * + * @param message + * the detail message + * @param cause + * the cause (A <tt>null</tt> value is permitted, and indicates that + * the cause is nonexistent or unknown.) + */ + public TaxonomySearchException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/WrongResponseCodeIOException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/WrongResponseCodeIOException.java index 501f7a4807..eee6f59029 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/WrongResponseCodeIOException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/WrongResponseCodeIOException.java @@ -11,33 +11,33 @@ import java.io.IOException; * */ public class WrongResponseCodeIOException extends IOException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * Response code returned by the super {@link IOException}. - */ - private int responseCode; + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * Response code returned by the super {@link IOException}. + */ + private int responseCode; - /** - * Default constructor. - * - * @param exception - * super exception - * @param code - * {@link #responseCode} - */ - public WrongResponseCodeIOException(IOException exception, int code) { - super(exception); - this.responseCode = code; - } + /** + * Default constructor. + * + * @param exception + * super exception + * @param code + * {@link #responseCode} + */ + public WrongResponseCodeIOException(IOException exception, int code) { + super(exception); + this.responseCode = code; + } - /** - * @return the responseCode - * @see #responseCode - */ - public int getResponseCode() { - return responseCode; - } + /** + * @return the responseCode + * @see #responseCode + */ + public int getResponseCode() { + return responseCode; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java index 5c123b67d7..864f922507 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java @@ -1,28 +1,20 @@ package lcsb.mapviewer.annotation.services.annotators; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -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.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements a backend to Brenda enzyme database. @@ -121,16 +113,6 @@ public class BrendaAnnotator extends ElementAnnotator implements IExternalServic return MiriamType.BRENDA.getDbHomepage(); } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - @Override public List<AnnotatorInputParameter> getAvailableInputParameters() { return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS), @@ -147,4 +129,14 @@ public class BrendaAnnotator extends ElementAnnotator implements IExternalServic return new MiriamData(MiriamType.UNIPROT, "P12345"); } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotator.java index c4ace692b7..7974a2a06b 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotator.java @@ -1,34 +1,24 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -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.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements a backend to CAZy. @@ -105,9 +95,35 @@ public class CazyAnnotator extends ElementAnnotator implements IExternalService return cazyIds.size() > 0; } + @Override + public String getCommonName() { + return MiriamType.CAZY.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.CAZY.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS), + new AnnotatorInputParameter(MiriamType.UNIPROT)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList(new AnnotatorOutputParameter(MiriamType.CAZY)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.UNIPROT, "Q9SG95"); + } + /** * Returns URL to TAIR page about TAIR entry. - * + * * @param uniProtId * UniProt identifier * @return URL to CAZY UniProt accession search result page @@ -119,7 +135,7 @@ public class CazyAnnotator extends ElementAnnotator implements IExternalService /** * Parse CAZy webpage to find information about {@link MiriamType#CAZY} and * returns them. - * + * * @param pageContent * CAZy info page * @return CAZy family identifier found on the page @@ -135,7 +151,7 @@ public class CazyAnnotator extends ElementAnnotator implements IExternalService /** * Transform UniProt identifier to CAZy identifier. - * + * * @param UniProt * {@link MiriamData} with UniProt identifier * @return {@link MiriamData} with CAZy identifier @@ -169,16 +185,6 @@ public class CazyAnnotator extends ElementAnnotator implements IExternalService } } - @Override - public String getCommonName() { - return MiriamType.CAZY.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.CAZY.getDbHomepage(); - } - @Override protected WebPageDownloader getWebPageDownloader() { return super.getWebPageDownloader(); @@ -189,20 +195,4 @@ public class CazyAnnotator extends ElementAnnotator implements IExternalService super.setWebPageDownloader(webPageDownloader); } - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS), - new AnnotatorInputParameter(MiriamType.UNIPROT)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList(new AnnotatorOutputParameter(MiriamType.CAZY)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.UNIPROT, "Q9SG95"); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java index 355a9828d7..359333328a 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java @@ -1,42 +1,22 @@ package lcsb.mapviewer.annotation.services.annotators; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; -import java.util.Set; +import java.util.*; import javax.xml.ws.WebServiceException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Chebi; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.species.Chemical; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.annotator.*; import uk.ac.ebi.chebi.webapps.chebiWS.client.ChebiWebServiceClient; -import uk.ac.ebi.chebi.webapps.chebiWS.model.DataItem; -import uk.ac.ebi.chebi.webapps.chebiWS.model.Entity; -import uk.ac.ebi.chebi.webapps.chebiWS.model.LiteEntity; -import uk.ac.ebi.chebi.webapps.chebiWS.model.LiteEntityList; -import uk.ac.ebi.chebi.webapps.chebiWS.model.OntologyDataItem; -import uk.ac.ebi.chebi.webapps.chebiWS.model.SearchCategory; -import uk.ac.ebi.chebi.webapps.chebiWS.model.StarsCategory; +import uk.ac.ebi.chebi.webapps.chebiWS.model.*; /** * This is a class that implements a backend to publicly available chebi API. @@ -47,17 +27,15 @@ import uk.ac.ebi.chebi.webapps.chebiWS.model.StarsCategory; @Service public class ChebiAnnotator extends ElementAnnotator implements IExternalService { + /** + * Prefix used for entries identified by chebi id. + */ + public static final String ID_PREFIX = "id: "; /** * What is the maximum number of results that should be retrieved from chebi * API. */ static final int MAX_SEARCH_RESULTS_FROM_CHEBI_API = 50; - - /** - * Prefix used for entries identified by chebi id. - */ - public static final String ID_PREFIX = "id: "; - /** * Prefix used for ontology list for single chebi id. */ @@ -77,6 +55,28 @@ public class ChebiAnnotator extends ElementAnnotator implements IExternalService * Length of the prefix used for entries identified by name. */ private static final int NAME_PREFIX_LENGTH = NAME_PREFIX.length(); + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(ChebiAnnotator.class); + /** + * Client to chebi API. + */ + private ChebiWebServiceClient client = null; + /** + * Object that allows to serialize {@link Chebi} elements into xml string and + * deserialize xml into {@link Chebi} objects. + */ + private XmlSerializer<Chebi> chebiSerializer; + + /** + * Default constructor. Initializes structures used for transforming + * {@link Chebi} from/to xml. + */ + public ChebiAnnotator() { + super(ChebiAnnotator.class, new Class[] { Chemical.class }, true); + chebiSerializer = new XmlSerializer<>(Chebi.class); + } @Override public String refreshCacheQuery(Object query) throws SourceNotAvailable { @@ -109,31 +109,6 @@ public class ChebiAnnotator extends ElementAnnotator implements IExternalService return result; } - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(ChebiAnnotator.class); - - /** - * Client to chebi API. - */ - private ChebiWebServiceClient client = null; - - /** - * Object that allows to serialize {@link Chebi} elements into xml string and - * deserialize xml into {@link Chebi} objects. - */ - private XmlSerializer<Chebi> chebiSerializer; - - /** - * Default constructor. Initializes structures used for transforming - * {@link Chebi} from/to xml. - */ - public ChebiAnnotator() { - super(ChebiAnnotator.class, new Class[] { Chemical.class }, true); - chebiSerializer = new XmlSerializer<>(Chebi.class); - } - /** * Returns {@link MiriamData} for given chebi name. * @@ -435,21 +410,13 @@ public class ChebiAnnotator extends ElementAnnotator implements IExternalService return client; } - @Override - public boolean annotateElement(BioEntityProxy element, String name, AnnotatorData parameters) - throws AnnotatorException { - try { - MiriamData chebi = getChebiForChebiName(name); - if (chebi != null) { - element.addMiriamData(chebi); - return annotateElement(element, chebi, parameters); - } else { - logger.warn(element.getElementTag() + "Chemical name cannot be found in chebi: " + name); - return false; - } - } catch (Exception e) { - throw new AnnotatorException("Problem with getting information about chebi", e); - } + /** + * @param client + * the client to set + * @see #client + */ + void setClient(ChebiWebServiceClient client) { + this.client = client; } @Override @@ -473,6 +440,23 @@ public class ChebiAnnotator extends ElementAnnotator implements IExternalService } } + @Override + public boolean annotateElement(BioEntityProxy element, String name, AnnotatorData parameters) + throws AnnotatorException { + try { + MiriamData chebi = getChebiForChebiName(name); + if (chebi != null) { + element.addMiriamData(chebi); + return annotateElement(element, chebi, parameters); + } else { + logger.warn(element.getElementTag() + "Chemical name cannot be found in chebi: " + name); + return false; + } + } catch (Exception e) { + throw new AnnotatorException("Problem with getting information about chebi", e); + } + } + @Override public String getCommonName() { return MiriamType.CHEBI.getCommonName(); @@ -483,15 +467,6 @@ public class ChebiAnnotator extends ElementAnnotator implements IExternalService return MiriamType.CHEBI.getDbHomepage(); } - /** - * @param client - * the client to set - * @see #client - */ - void setClient(ChebiWebServiceClient client) { - this.client = client; - } - @Override public List<AnnotatorInputParameter> getAvailableInputParameters() { return Arrays.asList(new AnnotatorInputParameter(MiriamType.CHEBI), diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java index 68874cf702..a41c28d60f 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotator.java @@ -1,33 +1,21 @@ package lcsb.mapviewer.annotation.services.annotators; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.annotation.cache.CachableInterface; import lcsb.mapviewer.common.comparator.StringSetComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerChemical; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Chemical; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.UniprotRecord; import lcsb.mapviewer.model.user.AnnotatorParamDefinition; -import lcsb.mapviewer.model.user.annotator.AnnotatorConfigParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.annotator.*; import lcsb.mapviewer.modelutils.map.ElementUtils; /** @@ -50,128 +38,400 @@ public abstract class ElementAnnotator extends CachableInterface { * annotator}. */ private final List<Class<? extends BioEntity>> validClasses = new ArrayList<>(); - + /** + * Parameters which this annotator can be provided. Should be set in + * constructor. + */ + protected List<AnnotatorParamDefinition> paramsDefs = new ArrayList<>(); /** * Should be this annotator used as a default annotator. */ private boolean isDefault = false; /** - * Parameters which this annotator can be provided. Should be set in - * constructor. + * Default constructor. + * + * @param validClasses + * list of classes for which this annotator is valid + * @param isDefault + * {@link #isDefault} + * @param clazz + * type that defines this interface */ - protected List<AnnotatorParamDefinition> paramsDefs = new ArrayList<>(); - - class BioEntityProxy { - private BioEntity originalBioEntity; - private AnnotatorData parameters; - - public BioEntityProxy(BioEntity bioEntity, AnnotatorData parameters) { - originalBioEntity = bioEntity; - this.parameters = parameters; - - } - - public void addMiriamData(Collection<MiriamData> annotations) { - for (MiriamData miriamData : annotations) { - addMiriamData(miriamData); + @SuppressWarnings("unchecked") + public ElementAnnotator(Class<? extends CachableInterface> clazz, Class<?>[] validClasses, boolean isDefault) { + super(clazz); + for (Class<?> validClass : validClasses) { + if (BioEntity.class.isAssignableFrom(validClass)) { + addValidClass((Class<? extends BioEntity>) validClass); + } else { + throw new InvalidArgumentException("Cannot pass class of type: " + validClass + ". Only classes extending " + + BioEntity.class + " are accepted."); } } + this.isDefault = isDefault; + } - public void addMiriamData(MiriamData miriamData) { - if (!contains(miriamData)) { - miriamData.setAnnotator(ElementAnnotator.this.getClass()); - originalBioEntity.addMiriamData(miriamData); + /** + * Annotate element. + * + * @param element + * object to be annotated + * @throws AnnotatorException + * thrown when there is a problem with annotating not related to data + */ + public void annotateElement(BioEntity element) throws AnnotatorException { + annotateElement(element, createAnnotatorData()); + } + + /** + * Annotate element using parameters. + * + * @param bioEntity + * object to be annotated + * @param parameters + * list of parameters passed to the annotator which is expected to be + * in the same order as its {@link this#parameterDefs} + * @throws AnnotatorException + * thrown when there is a problem with annotating not related to data + */ + public final void annotateElement(BioEntity bioEntity, AnnotatorData parameters) throws AnnotatorException { + if (isAnnotatable(bioEntity)) { + BioEntityProxy proxy = new BioEntityProxy(bioEntity, parameters); + List<AnnotatorInputParameter> inputParameters = parameters.getInputParameters(); + if (inputParameters.size() == 0) { + inputParameters = getAvailableInputParameters(); + } + if (parameters.getOutputParameters().size() == 0) { + parameters.addAnnotatorParameters(this.getAvailableOuputProperties()); + } + List<Set<Object>> inputs = getInputsParameters(bioEntity, inputParameters); + for (Set<Object> inputSet : inputs) { + boolean annotated = false; + for (Object object : inputSet) { + if (object instanceof MiriamData) { + if (annotateElement(proxy, (MiriamData) object, parameters)) { + annotated = true; + } + } else if (object instanceof String) { + if (annotateElement(proxy, (String) object, parameters)) { + annotated = true; + } + } else { + throw new NotImplementedException(); + } + } + if (annotated) { + break; + } } } + } - public boolean contains(MiriamData identifier) { - MiriamData copy = new MiriamData(identifier); - copy.setAnnotator(null); - MiriamData copy2 = new MiriamData(identifier); - copy.setAnnotator(ElementAnnotator.this.getClass()); - return originalBioEntity.getMiriamData().contains(copy) || originalBioEntity.getMiriamData().contains(copy2); - } + public abstract boolean annotateElement(BioEntityProxy element, MiriamData identifier, + AnnotatorData parameters) + throws AnnotatorException; - public String getElementTag() { - return new ElementUtils().getElementTag(originalBioEntity, ElementAnnotator.this); - } +public boolean annotateElement(BioEntityProxy element, String name, AnnotatorData parameters) + throws AnnotatorException { + throw new NotImplementedException(); + } - public boolean isElement() { - return originalBioEntity instanceof Element; - } + /** + * Returns a list of all classes that can be annotated using this annotator. + * + * @return a list of all classes that can be annotated using this annotator + */ + public List<Class<? extends BioEntity>> getValidClasses() { + return validClasses; + }; - public void addUniprot(UniprotRecord ur) { - if (originalBioEntity instanceof Species) { - Species species = ((Species) originalBioEntity); - species.getUniprots().add(ur); - ur.setSpecies(species); - } else { - logger.warn("Cannot add uniprot object to: " + originalBioEntity.getClass().getSimpleName()); + /** + * Returns <code>true</code> if this annotator can annotate the object given in + * the parameter. + * + * @param object + * object to be tested if can be annotated + * @return <code>true</code> if object can be annotated by this annotator, + * <code>false</code> otherwise + */ + public boolean isAnnotatable(BioEntity object) { + Class<?> clazz = object.getClass(); + for (Class<?> validClazz : getValidClasses()) { + if (validClazz.isAssignableFrom(clazz)) { + return true; } } + return false; + } - public boolean isReaction() { - return originalBioEntity instanceof Reaction; - } + /** + * Adds a class to list of classes that can be annotated by the annotator. + * + * @param clazz + * class to add + */ + private void addValidClass(Class<? extends BioEntity> clazz) { + validClasses.add(clazz); + } - /** - * Sets synonyms to the element. - * - * @param synonyms - * new synonyms list - */ - public void setSynonyms(Collection<String> synonyms) { - if (canAssignStringSet(synonyms, originalBioEntity.getSynonyms(), BioEntityField.SYNONYMS)) { - List<String> sortedSynonyms = new ArrayList<>(synonyms); - Collections.sort(sortedSynonyms); + /** + * Returns the common name that should be presented to user. + * + * @return the common name + */ + public abstract String getCommonName(); - originalBioEntity.setSynonyms(sortedSynonyms); - } - } + /** + * Returns url to the external resource used for annotation. + * + * @return url + */ + public abstract String getUrl(); - private boolean canAssignStringSet(Collection<String> newCollection, Collection<String> oldCollection, - BioEntityField field) { - if (!parameters.hasOutputField(field)) { - return false; - } - if (oldCollection == null || oldCollection.size() == 0) { - return true; - } else if (newCollection == null || newCollection.size() == 0) { - return false; - } else { - StringSetComparator stringSetComparator = new StringSetComparator(); - Set<String> set1 = new HashSet<>(); - Set<String> set2 = new HashSet<>(); + /** + * Provides description of the extraction process for {@link ElementAnnotator} + * to be used in the front end. + * + * @return the description + */ + public String getDescription() { + return ""; + } - set1.addAll(newCollection); - set2.addAll(oldCollection); + /** + * Returns list with definitions of the parameters available for this annotator. + * + * @return the parameters {@link AnnotatorParamDefinition} list + */ + public Collection<AnnotatorParamDefinition> getParametersDefinitions() { + return paramsDefs; + } - if (stringSetComparator.compare(set1, set2) != 0) { - logger.warn(getElementTag() + field.getCommonName() + " don't match: \"" + set1 + "\", \"" + set2 + "\""); - return false; - } + /** + * Sets definitions of parameters for given annotator. + * + * @param paramDefs + * definitions to be set + */ + public void setParametersDefinitions(List<AnnotatorParamDefinition> paramDefs) { + this.paramsDefs = paramDefs; + } + + /** + * Returns <code>true</code> if this annotator can annotate the object of given + * class type. + * + * @param clazz + * class to be tested if can be annotated + * @return <code>true</code> if class can be annotated by this annotator, + * <code>false</code> otherwise + */ + public boolean isAnnotatable(Class<?> clazz) { + for (Class<?> clazz2 : validClasses) { + if (clazz2.isAssignableFrom(clazz)) { return true; } } + return false; + } - /** - * Sets symbol value to the element. - * - * @param symbol - * new symbol - */ - public void setSymbol(String symbol) { - if (canAssign(symbol, originalBioEntity.getSymbol(), BioEntityField.SYMBOL)) { - originalBioEntity.setSymbol(symbol); - } - } + /** + * + * @return {@link #isDefault} + */ + public boolean isDefault() { + return isDefault; + } - public void setName(String nam) { - if (canAssign(nam, originalBioEntity.getName(), BioEntityField.NAME)) { - originalBioEntity.setName(nam); - } - } + /** + * Adds parameter definition to the definitions of parameters for given + * annotator + * + * @param paramDef + * parameter definition to be added + */ + public void addParameterDefinition(AnnotatorParamDefinition paramDef) { + this.paramsDefs.add(paramDef); + } + + /** + * Returns list of available {@link AnnotatorInputParameter}. Order indicates + * the default order that should be considered when extracting identifier. + * + * @return list of available {@link AnnotatorInputParameter} for class + */ + public abstract List<AnnotatorInputParameter> getAvailableInputParameters(); + + /** + * Returns list of available {@link AnnotatorOutputParameter}. Order indicates + * the default order that should be considered when extracting identifier. + * + * @return list of available {@link AnnotatorOutputParameter} for class + */ + public abstract List<AnnotatorOutputParameter> getAvailableOuputProperties(); + + public List<Set<Object>> getInputsParameters(BioEntity bioEntity, List<AnnotatorInputParameter> inputParameters) { + List<Set<Object>> result = new ArrayList<>(); + for (AnnotatorInputParameter parameter : inputParameters) { + Set<Object> inputs = new HashSet<>(); + if (parameter.getField() != null && parameter.getIdentifierType() == null) { + inputs.add(BioEntityField.getFieldValueForBioEntity(bioEntity, parameter.getField())); + } else if (parameter.getField() != null && parameter.getIdentifierType() != null) { + String value = BioEntityField.getFieldValueForBioEntity(bioEntity, parameter.getField()); + if (value != null && !value.isEmpty()) { + inputs.add(new MiriamData(parameter.getIdentifierType(), + BioEntityField.getFieldValueForBioEntity(bioEntity, parameter.getField()))); + } + } else if (parameter.getField() == null && parameter.getIdentifierType() != null) { + for (MiriamData md : bioEntity.getMiriamData()) { + if (md.getDataType().equals(parameter.getIdentifierType())) { + inputs.add(md); + } + } + } else { + throw new InvalidArgumentException("Input parameter must have either field or identifierType defined"); + } + result.add(inputs); + } + + return result; + } + + public abstract MiriamData getExampleValidAnnotation(); + + public List<AnnotatorConfigParameter> getExampleValidParameters() { + return new ArrayList<>(); + } + + /** + * Creates default {@link AnnotatorData} for this {@link ElementAnnotator}. + * + * @return + */ + public AnnotatorData createAnnotatorData() { + AnnotatorData result = new AnnotatorData(this.getClass()); + // by default use everything as input + result.addAnnotatorParameters(getAvailableInputParameters()); + // and provide all available output + result.addAnnotatorParameters(getAvailableOuputProperties()); + // and provide all available output + for (AnnotatorParamDefinition type : getParametersDefinitions()) { + result.addAnnotatorParameter(type, ""); + } + return result; + } + + class BioEntityProxy { + private BioEntity originalBioEntity; + private AnnotatorData parameters; + + public BioEntityProxy(BioEntity bioEntity, AnnotatorData parameters) { + originalBioEntity = bioEntity; + this.parameters = parameters; + + } + + public void addMiriamData(Collection<MiriamData> annotations) { + for (MiriamData miriamData : annotations) { + addMiriamData(miriamData); + } + } + + public void addMiriamData(MiriamData miriamData) { + if (!contains(miriamData)) { + miriamData.setAnnotator(ElementAnnotator.this.getClass()); + originalBioEntity.addMiriamData(miriamData); + } + } + + public boolean contains(MiriamData identifier) { + MiriamData copy = new MiriamData(identifier); + copy.setAnnotator(null); + MiriamData copy2 = new MiriamData(identifier); + copy.setAnnotator(ElementAnnotator.this.getClass()); + return originalBioEntity.getMiriamData().contains(copy) || originalBioEntity.getMiriamData().contains(copy2); + } + + public String getElementTag() { + return new ElementUtils().getElementTag(originalBioEntity, ElementAnnotator.this); + } + + public boolean isElement() { + return originalBioEntity instanceof Element; + } + + public void addUniprot(UniprotRecord ur) { + if (originalBioEntity instanceof Species) { + Species species = ((Species) originalBioEntity); + species.getUniprots().add(ur); + ur.setSpecies(species); + } else { + logger.warn("Cannot add uniprot object to: " + originalBioEntity.getClass().getSimpleName()); + } + } + + public boolean isReaction() { + return originalBioEntity instanceof Reaction; + } + + /** + * Sets synonyms to the element. + * + * @param synonyms + * new synonyms list + */ + public void setSynonyms(Collection<String> synonyms) { + if (canAssignStringSet(synonyms, originalBioEntity.getSynonyms(), BioEntityField.SYNONYMS)) { + List<String> sortedSynonyms = new ArrayList<>(synonyms); + Collections.sort(sortedSynonyms); + + originalBioEntity.setSynonyms(sortedSynonyms); + } + } + + private boolean canAssignStringSet(Collection<String> newCollection, Collection<String> oldCollection, + BioEntityField field) { + if (!parameters.hasOutputField(field)) { + return false; + } + if (oldCollection == null || oldCollection.size() == 0) { + return true; + } else if (newCollection == null || newCollection.size() == 0) { + return false; + } else { + StringSetComparator stringSetComparator = new StringSetComparator(); + Set<String> set1 = new HashSet<>(); + Set<String> set2 = new HashSet<>(); + + set1.addAll(newCollection); + set2.addAll(oldCollection); + + if (stringSetComparator.compare(set1, set2) != 0) { + logger.warn(getElementTag() + field.getCommonName() + " don't match: \"" + set1 + "\", \"" + set2 + "\""); + return false; + } + return true; + } + } + + /** + * Sets symbol value to the element. + * + * @param symbol + * new symbol + */ + public void setSymbol(String symbol) { + if (canAssign(symbol, originalBioEntity.getSymbol(), BioEntityField.SYMBOL)) { + originalBioEntity.setSymbol(symbol); + } + } + + public void setName(String nam) { + if (canAssign(nam, originalBioEntity.getName(), BioEntityField.NAME)) { + originalBioEntity.setName(nam); + } + } private boolean canAssign(String newValue, String oldValue, BioEntityField field) { if (!parameters.hasOutputField(field)) { @@ -220,7 +480,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets name to the element. - * + * * @param name * new name */ @@ -238,7 +498,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Adds description to {@link BioEntity#getNotes()}. - * + * * @param description * value to set */ @@ -269,7 +529,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link CellDesignerChemical#inChI}. - * + * * @param inchi * value to set */ @@ -286,7 +546,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link CellDesignerChemical#inChIKey}. - * + * * @param inchiKey * value to set */ @@ -304,7 +564,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link CellDesignerChemical#smiles}. - * + * * @param smile * value to set */ @@ -326,7 +586,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link Species#charge}. - * + * * @param charge * value to set */ @@ -344,7 +604,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link Reaction#subsystem}. - * + * * @param subsystem * value to set */ @@ -362,7 +622,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link BioEntity#getFormula()}. - * + * * @param formula * value to set */ @@ -374,7 +634,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link BioEntity#getAbbreviation()}. - * + * * @param value * value to set */ @@ -386,7 +646,7 @@ public abstract class ElementAnnotator extends CachableInterface { /** * Sets {@link Reaction#getMechanicalConfidenceScore()}. - * + * * @param value * value to set */ @@ -481,278 +741,4 @@ public abstract class ElementAnnotator extends CachableInterface { } - /** - * Default constructor. - * - * @param validClasses - * list of classes for which this annotator is valid - * @param isDefault - * {@link #isDefault} - * @param clazz - * type that defines this interface - */ - @SuppressWarnings("unchecked") - public ElementAnnotator(Class<? extends CachableInterface> clazz, Class<?>[] validClasses, boolean isDefault) { - super(clazz); - for (Class<?> validClass : validClasses) { - if (BioEntity.class.isAssignableFrom(validClass)) { - addValidClass((Class<? extends BioEntity>) validClass); - } else { - throw new InvalidArgumentException("Cannot pass class of type: " + validClass + ". Only classes extending " - + BioEntity.class + " are accepted."); - } - } - this.isDefault = isDefault; - } - - /** - * Annotate element. - * - * @param element - * object to be annotated - * @throws AnnotatorException - * thrown when there is a problem with annotating not related to data - */ - public void annotateElement(BioEntity element) throws AnnotatorException { - annotateElement(element, createAnnotatorData()); - } - - /** - * Annotate element using parameters. - * - * @param bioEntity - * object to be annotated - * @param parameters - * list of parameters passed to the annotator which is expected to be - * in the same order as its {@link this#parameterDefs} - * @throws AnnotatorException - * thrown when there is a problem with annotating not related to data - */ - public final void annotateElement(BioEntity bioEntity, AnnotatorData parameters) throws AnnotatorException { - if (isAnnotatable(bioEntity)) { - BioEntityProxy proxy = new BioEntityProxy(bioEntity, parameters); - List<AnnotatorInputParameter> inputParameters = parameters.getInputParameters(); - if (inputParameters.size() == 0) { - inputParameters = getAvailableInputParameters(); - } - if (parameters.getOutputParameters().size() == 0) { - parameters.addAnnotatorParameters(this.getAvailableOuputProperties()); - } - List<Set<Object>> inputs = getInputsParameters(bioEntity, inputParameters); - for (Set<Object> inputSet : inputs) { - boolean annotated = false; - for (Object object : inputSet) { - if (object instanceof MiriamData) { - if (annotateElement(proxy, (MiriamData) object, parameters)) { - annotated = true; - } - } else if (object instanceof String) { - if (annotateElement(proxy, (String) object, parameters)) { - annotated = true; - } - } else { - throw new NotImplementedException(); - } - } - if (annotated) { - break; - } - } - } - } - - public abstract boolean annotateElement(BioEntityProxy element, MiriamData identifier, - AnnotatorData parameters) - throws AnnotatorException; - - public boolean annotateElement(BioEntityProxy element, String name, AnnotatorData parameters) - throws AnnotatorException { - throw new NotImplementedException(); - }; - - /** - * Returns a list of all classes that can be annotated using this annotator. - * - * @return a list of all classes that can be annotated using this annotator - */ - public List<Class<? extends BioEntity>> getValidClasses() { - return validClasses; - } - - /** - * Returns <code>true</code> if this annotator can annotate the object given in - * the parameter. - * - * @param object - * object to be tested if can be annotated - * @return <code>true</code> if object can be annotated by this annotator, - * <code>false</code> otherwise - */ - public boolean isAnnotatable(BioEntity object) { - Class<?> clazz = object.getClass(); - for (Class<?> validClazz : getValidClasses()) { - if (validClazz.isAssignableFrom(clazz)) { - return true; - } - } - return false; - } - - /** - * Adds a class to list of classes that can be annotated by the annotator. - * - * @param clazz - * class to add - */ - private void addValidClass(Class<? extends BioEntity> clazz) { - validClasses.add(clazz); - } - - /** - * Returns the common name that should be presented to user. - * - * @return the common name - */ - public abstract String getCommonName(); - - /** - * Returns url to the external resource used for annotation. - * - * @return url - */ - public abstract String getUrl(); - - /** - * Provides description of the extraction process for {@link ElementAnnotator} - * to be used in the front end. - * - * @return the description - */ - public String getDescription() { - return ""; - } - - /** - * Returns list with definitions of the parameters available for this annotator. - * - * @return the parameters {@link AnnotatorParamDefinition} list - */ - public Collection<AnnotatorParamDefinition> getParametersDefinitions() { - return paramsDefs; - } - - /** - * Returns <code>true</code> if this annotator can annotate the object of given - * class type. - * - * @param clazz - * class to be tested if can be annotated - * @return <code>true</code> if class can be annotated by this annotator, - * <code>false</code> otherwise - */ - public boolean isAnnotatable(Class<?> clazz) { - for (Class<?> clazz2 : validClasses) { - if (clazz2.isAssignableFrom(clazz)) { - return true; - } - } - return false; - } - - /** - * - * @return {@link #isDefault} - */ - public boolean isDefault() { - return isDefault; - } - - /** - * Sets definitions of parameters for given annotator. - * - * @param paramDefs - * definitions to be set - */ - public void setParametersDefinitions(List<AnnotatorParamDefinition> paramDefs) { - this.paramsDefs = paramDefs; - } - - /** - * Adds parameter definition to the definitions of parameters for given - * annotator - * - * @param paramDef - * parameter definition to be added - */ - public void addParameterDefinition(AnnotatorParamDefinition paramDef) { - this.paramsDefs.add(paramDef); - } - - /** - * Returns list of available {@link AnnotatorInputParameter}. Order indicates - * the default order that should be considered when extracting identifier. - * - * @return list of available {@link AnnotatorInputParameter} for class - */ - public abstract List<AnnotatorInputParameter> getAvailableInputParameters(); - - /** - * Returns list of available {@link AnnotatorOutputParameter}. Order indicates - * the default order that should be considered when extracting identifier. - * - * @return list of available {@link AnnotatorOutputParameter} for class - */ - public abstract List<AnnotatorOutputParameter> getAvailableOuputProperties(); - - public List<Set<Object>> getInputsParameters(BioEntity bioEntity, List<AnnotatorInputParameter> inputParameters) { - List<Set<Object>> result = new ArrayList<>(); - for (AnnotatorInputParameter parameter : inputParameters) { - Set<Object> inputs = new HashSet<>(); - if (parameter.getField() != null && parameter.getIdentifierType() == null) { - inputs.add(BioEntityField.getFieldValueForBioEntity(bioEntity, parameter.getField())); - } else if (parameter.getField() != null && parameter.getIdentifierType() != null) { - String value = BioEntityField.getFieldValueForBioEntity(bioEntity, parameter.getField()); - if (value != null && !value.isEmpty()) { - inputs.add(new MiriamData(parameter.getIdentifierType(), - BioEntityField.getFieldValueForBioEntity(bioEntity, parameter.getField()))); - } - } else if (parameter.getField() == null && parameter.getIdentifierType() != null) { - for (MiriamData md : bioEntity.getMiriamData()) { - if (md.getDataType().equals(parameter.getIdentifierType())) { - inputs.add(md); - } - } - } else { - throw new InvalidArgumentException("Input parameter must have either field or identifierType defined"); - } - result.add(inputs); - } - - return result; - } - - public abstract MiriamData getExampleValidAnnotation(); - - public List<AnnotatorConfigParameter> getExampleValidParameters() { - return new ArrayList<>(); - } - - /** - * Creates default {@link AnnotatorData} for this {@link ElementAnnotator}. - * - * @return - */ - public AnnotatorData createAnnotatorData() { - AnnotatorData result = new AnnotatorData(this.getClass()); - // by default use everything as input - result.addAnnotatorParameters(getAvailableInputParameters()); - // and provide all available output - result.addAnnotatorParameters(getAvailableOuputProperties()); - // and provide all available output - for (AnnotatorParamDefinition type : getParametersDefinitions()) { - result.addAnnotatorParameter(type, ""); - } - return result; - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java index d38d2e2807..6f01d674e5 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotator.java @@ -1,35 +1,24 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This class is responsible for connecting to @@ -43,10 +32,10 @@ import lcsb.mapviewer.model.user.annotator.BioEntityField; @Service public class EnsemblAnnotator extends ElementAnnotator implements IExternalService { - /** - * Version of the rest API that is supported by this annotator. - */ - static final String SUPPORTED_VERSION = "11.0"; + /** + * Version of the rest API that is supported by this annotator. + */ + static final String SUPPORTED_VERSION = "11.0"; /** * Url address of ensembl restful service. @@ -63,6 +52,10 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi * Url used for retrieving version of the restful API. */ private static final String REST_SERVICE_VERSION_URL = "https://rest.ensembl.org/info/rest?content-type=text/xml"; + /** + * Standard class logger. + */ + private final Logger logger = LogManager.getLogger(EnsemblAnnotator.class); /** * Default constructor. @@ -71,21 +64,6 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi super(EnsemblAnnotator.class, new Class[] { Protein.class, Rna.class, Gene.class }, false); } - /** - * Standard class logger. - */ - private final Logger logger = LogManager.getLogger(EnsemblAnnotator.class); - - @Override - public String getCommonName() { - return MiriamType.ENSEMBL.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.ENSEMBL.getDbHomepage(); - } - @Override public ExternalServiceStatus getServiceStatus() { ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); @@ -222,13 +200,13 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi } @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); + public String getCommonName() { + return MiriamType.ENSEMBL.getCommonName(); } @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); + public String getUrl() { + return MiriamType.ENSEMBL.getDbHomepage(); } @Override @@ -251,4 +229,14 @@ public class EnsemblAnnotator extends ElementAnnotator implements IExternalServi return new MiriamData(MiriamType.ENSEMBL, "ENSG00000157764"); } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java index 6ae860d282..9fceeda97a 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotator.java @@ -2,42 +2,24 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.commons.text.StringEscapeUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.EntrezData; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.XmlParser; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This class is responsible for connecting to @@ -51,17 +33,19 @@ import lcsb.mapviewer.model.user.annotator.BioEntityField; @Service public class EntrezAnnotator extends ElementAnnotator implements IExternalService { + /** + * Prefix used in cache key to indicate that cached value contains + * {@link EntrezData} object for a given entrez id. + */ + static final String ENTREZ_DATA_PREFIX = "ENTREZ_DATA:"; /** * Address of Entrez API that should be used for retrieving data. */ private static final String REST_API_URL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=gene&rettype=xml&id="; - /** - * Prefix used in cache key to indicate that cached value contains - * {@link EntrezData} object for a given entrez id. + * Standard class logger. */ - static final String ENTREZ_DATA_PREFIX = "ENTREZ_DATA:"; - + private final Logger logger = LogManager.getLogger(EntrezAnnotator.class); /** * Object that allows to serialize {@link EntrezData} elements into xml string * and deserialize xml into {@link EntrezData} objects. @@ -102,19 +86,14 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic return result; } - /** - * Standard class logger. - */ - private final Logger logger = LogManager.getLogger(EntrezAnnotator.class); - @Override - public String getCommonName() { - return MiriamType.ENTREZ.getCommonName(); + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); } @Override - public String getUrl() { - return MiriamType.ENTREZ.getDbHomepage(); + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); } @Override @@ -164,6 +143,36 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic } } + @Override + public String getCommonName() { + return MiriamType.ENTREZ.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.ENTREZ.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.ENTREZ)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList(new AnnotatorOutputParameter(MiriamType.ENSEMBL), + new AnnotatorOutputParameter(MiriamType.HGNC), + new AnnotatorOutputParameter(BioEntityField.FULL_NAME), + new AnnotatorOutputParameter(BioEntityField.DESCRIPTION), + new AnnotatorOutputParameter(BioEntityField.SYMBOL), + new AnnotatorOutputParameter(BioEntityField.SYNONYMS)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.ENTREZ, "6621"); + } + /** * Returns preprocessed data for entrez identifier. * @@ -264,7 +273,7 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic Node node = list.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("Gene-ref_syn_E")) { - synonyms.add(StringEscapeUtils.unescapeHtml4(node.getTextContent())); + synonyms.add(StringEscapeUtils.unescapeHtml4(node.getTextContent())); } } } @@ -298,16 +307,6 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic return result; } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - /** * @return the entrezSerializer * @see #entrezSerializer @@ -325,24 +324,4 @@ public class EntrezAnnotator extends ElementAnnotator implements IExternalServic this.entrezSerializer = entrezSerializer; } - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.ENTREZ)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList(new AnnotatorOutputParameter(MiriamType.ENSEMBL), - new AnnotatorOutputParameter(MiriamType.HGNC), - new AnnotatorOutputParameter(BioEntityField.FULL_NAME), - new AnnotatorOutputParameter(BioEntityField.DESCRIPTION), - new AnnotatorOutputParameter(BioEntityField.SYMBOL), - new AnnotatorOutputParameter(BioEntityField.SYNONYMS)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.ENTREZ, "6621"); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java index 53669eecb7..78077388e8 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotator.java @@ -1,38 +1,25 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.gson.Gson; -import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; -import lcsb.mapviewer.annotation.cache.SourceNotAvailable; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.cache.XmlSerializer; +import lcsb.mapviewer.annotation.cache.*; import lcsb.mapviewer.annotation.data.Go; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.MiriamConnector; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.annotator.*; /** * This class is a backend to Gene Ontology API. @@ -99,6 +86,16 @@ public class GoAnnotator extends ElementAnnotator implements IExternalService { return result; } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + @Override public boolean annotateElement(BioEntityProxy object, MiriamData identifier, AnnotatorData parameters) throws AnnotatorException { @@ -120,6 +117,33 @@ public class GoAnnotator extends ElementAnnotator implements IExternalService { } + @Override + public String getCommonName() { + return MiriamType.GO.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.GO.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.GO)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList( + new AnnotatorOutputParameter(BioEntityField.FULL_NAME), + new AnnotatorOutputParameter(BioEntityField.DESCRIPTION)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.GO, "GO:0046902"); + } + /** * Returns go entry from the Gene Ontology database for the goTerm (identifier). * @@ -210,41 +234,4 @@ public class GoAnnotator extends ElementAnnotator implements IExternalService { this.mc = mc; } - @Override - public String getCommonName() { - return MiriamType.GO.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.GO.getDbHomepage(); - } - - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.GO)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList( - new AnnotatorOutputParameter(BioEntityField.FULL_NAME), - new AnnotatorOutputParameter(BioEntityField.DESCRIPTION)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.GO, "GO:0046902"); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java index 36aa9fb4a2..e7af4a9ce6 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotator.java @@ -1,36 +1,23 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.MiriamConnector; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.annotation.services.*; +import lcsb.mapviewer.common.XmlParser; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This class is responsible for connecting to @@ -48,7 +35,10 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService * Address of HGNC API that should be used for retrieving data. */ private static final String REST_API_URL = "https://rest.genenames.org/fetch/"; - + /** + * Standard class logger. + */ + private final Logger logger = LogManager.getLogger(HgncAnnotator.class); private MiriamConnector miriamConnector; /** @@ -59,21 +49,6 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService this.miriamConnector = miriamConnector; } - /** - * Standard class logger. - */ - private final Logger logger = LogManager.getLogger(HgncAnnotator.class); - - @Override - public String getCommonName() { - return MiriamType.HGNC.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.HGNC.getDbHomepage(); - } - @Override public ExternalServiceStatus getServiceStatus() { ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); @@ -205,6 +180,43 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService } } + @Override + public String getCommonName() { + return MiriamType.HGNC.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.HGNC.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.HGNC_SYMBOL), + new AnnotatorInputParameter(MiriamType.HGNC), + new AnnotatorInputParameter(BioEntityField.NAME, MiriamType.HGNC_SYMBOL)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList( + new AnnotatorOutputParameter(MiriamType.ENSEMBL), + new AnnotatorOutputParameter(MiriamType.ENTREZ), + new AnnotatorOutputParameter(MiriamType.HGNC), + new AnnotatorOutputParameter(MiriamType.HGNC_SYMBOL), + new AnnotatorOutputParameter(MiriamType.REFSEQ), + new AnnotatorOutputParameter(MiriamType.UNIPROT), + new AnnotatorOutputParameter(BioEntityField.SYMBOL), + new AnnotatorOutputParameter(BioEntityField.SYNONYMS), + new AnnotatorOutputParameter(BioEntityField.NAME), + new AnnotatorOutputParameter(BioEntityField.FULL_NAME)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); + } + /** * Creates query url for given {@link MiriamType#HGNC} identifier. * @@ -425,31 +437,4 @@ public class HgncAnnotator extends ElementAnnotator implements IExternalService super.setWebPageDownloader(webPageDownloader); } - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.HGNC_SYMBOL), - new AnnotatorInputParameter(MiriamType.HGNC), - new AnnotatorInputParameter(BioEntityField.NAME, MiriamType.HGNC_SYMBOL)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList( - new AnnotatorOutputParameter(MiriamType.ENSEMBL), - new AnnotatorOutputParameter(MiriamType.ENTREZ), - new AnnotatorOutputParameter(MiriamType.HGNC), - new AnnotatorOutputParameter(MiriamType.HGNC_SYMBOL), - new AnnotatorOutputParameter(MiriamType.REFSEQ), - new AnnotatorOutputParameter(MiriamType.UNIPROT), - new AnnotatorOutputParameter(BioEntityField.SYMBOL), - new AnnotatorOutputParameter(BioEntityField.SYNONYMS), - new AnnotatorOutputParameter(BioEntityField.NAME), - new AnnotatorOutputParameter(BioEntityField.FULL_NAME)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA"); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotator.java index 3d53b59497..813d56f3a0 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotator.java @@ -1,36 +1,23 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.user.AnnotatorParamDefinition; -import lcsb.mapviewer.model.user.annotator.AnnotatorConfigParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements KEGG annotator which extract from KEGG PUBMED @@ -153,17 +140,56 @@ public class KeggAnnotator extends ElementAnnotator implements IExternalService } catch (IOException exception) { throw new AnnotatorException(exception); } catch (UniprotSearchException e) { - logger.warn(e, e); - return false; + logger.warn(e, e); + return false; } } object.addMiriamData(annotations); return annotations.size() > 0; } + @Override + public String getCommonName() { + return "KEGG"; + } + + @Override + public String getUrl() { + return "http://www.genome.jp/kegg/"; + } + + @Override + public String getDescription() { + return "Annotations extracted from KEGG ENZYME Database based on species EC numbers. " + + "Annotation include relevant publications and homologous genes for given EC numbers."; + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS), + new AnnotatorInputParameter(MiriamType.UNIPROT), + new AnnotatorInputParameter(MiriamType.EC)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList(new AnnotatorOutputParameter(MiriamType.PUBMED), + new AnnotatorOutputParameter(MiriamType.TAIR_LOCUS)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.EC, "3.1.2.14"); + } + + @Override + public List<AnnotatorConfigParameter> getExampleValidParameters() { + return Arrays.asList(new AnnotatorConfigParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "ATH")); + } + /** * Returns url to KEGG restful API about enzyme classification. - * + * * @param ecId * enzyme classification * @return url to KEGG restful API about given EC @@ -175,7 +201,7 @@ public class KeggAnnotator extends ElementAnnotator implements IExternalService /** * Parse KEGG webpage to find information about {@link MiriamType#PUBMED}s and * returns them. - * + * * @param pageContent * Kegg page * @param params @@ -184,7 +210,7 @@ public class KeggAnnotator extends ElementAnnotator implements IExternalService * organisms names. If the value has not been set by the user, null * will be passed. * @return {@link MiriamType#PUBMED}s found on the page - * @throws UniprotSearchException + * @throws UniprotSearchException */ private Collection<MiriamData> parseKegg(String pageContent, AnnotatorData params) throws UniprotSearchException { @@ -207,11 +233,11 @@ public class KeggAnnotator extends ElementAnnotator implements IExternalService if (m.find()) { String[] tairLocusNames = m.group(1).trim().split(" "); for (String tairLocusName : tairLocusNames) { - tairLocusName = tairLocusName.split("\\(")[0]; // some codes are in the form AT1G08510(FATB) - MiriamData md = uniprotAnnotator.uniprotTairLocusNameToId(tairLocusName); - if (!md.equals(new MiriamData())){ - result.add(md); - } + tairLocusName = tairLocusName.split("\\(")[0]; // some codes are in the form AT1G08510(FATB) + MiriamData md = uniprotAnnotator.uniprotTairLocusNameToId(tairLocusName); + if (!md.equals(new MiriamData())) { + result.add(md); + } } } } @@ -221,22 +247,6 @@ public class KeggAnnotator extends ElementAnnotator implements IExternalService return result; } - @Override - public String getCommonName() { - return "KEGG"; - } - - @Override - public String getUrl() { - return "http://www.genome.jp/kegg/"; - } - - @Override - public String getDescription() { - return "Annotations extracted from KEGG ENZYME Database based on species EC numbers. " - + "Annotation include relevant publications and homologous genes for given EC numbers."; - } - @Override protected WebPageDownloader getWebPageDownloader() { return super.getWebPageDownloader(); @@ -246,27 +256,4 @@ public class KeggAnnotator extends ElementAnnotator implements IExternalService protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { super.setWebPageDownloader(webPageDownloader); } - - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS), - new AnnotatorInputParameter(MiriamType.UNIPROT), - new AnnotatorInputParameter(MiriamType.EC)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList(new AnnotatorOutputParameter(MiriamType.PUBMED), - new AnnotatorOutputParameter(MiriamType.TAIR_LOCUS)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.EC, "3.1.2.14"); - } - - @Override - public List<AnnotatorConfigParameter> getExampleValidParameters() { - return Arrays.asList(new AnnotatorConfigParameter(AnnotatorParamDefinition.KEGG_ORGANISM_IDENTIFIER, "ATH")); - } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotator.java index 65b1a8a5ba..96d96d4d32 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotator.java @@ -1,15 +1,10 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -18,23 +13,14 @@ import com.google.gson.reflect.TypeToken; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -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.*; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.Structure; import lcsb.mapviewer.model.map.species.field.UniprotRecord; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements a backend to the EBI's PDB SIFTS REST API @@ -59,6 +45,24 @@ public class PdbAnnotator extends ElementAnnotator implements IExternalService { super(PdbAnnotator.class, new Class[] { Protein.class, Rna.class, Gene.class }, false); } + /** + * Tests if given input string is a valid JSON document. + * + * @param json + * Input document as a string. + * @return True or false dependent on whether the input string is a valid JSON + * document + */ + public static boolean isJson(String json) { + Gson gson = new Gson(); + try { + gson.fromJson(json, Object.class); + return true; + } catch (com.google.gson.JsonSyntaxException ex) { + return false; + } + } + @Override public ExternalServiceStatus getServiceStatus() { ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); @@ -139,9 +143,34 @@ public class PdbAnnotator extends ElementAnnotator implements IExternalService { } } + @Override + public String getCommonName() { + return MiriamType.PDB.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.PDB.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.UNIPROT)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList(new AnnotatorOutputParameter(MiriamType.PDB)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.UNIPROT, "P29373"); + } + /** * Returns url to JSON with best mapping PDB entries given the UniProt entry. - * + * * @param uniprotId * uniprot identifier * @return url with best mapping PDB entries to the UniProt entry @@ -153,7 +182,7 @@ public class PdbAnnotator extends ElementAnnotator implements IExternalService { /** * Parse UniProt-to-PDB mapping JSON file. {@link MiriamType#PDB} and returns * them. - * + * * @param pageContentJson * JSON file with the UniProt to PDB mapping * @return set of PDB identifiers found on the webpage @@ -178,27 +207,9 @@ public class PdbAnnotator extends ElementAnnotator implements IExternalService { return result; } - /** - * Tests if given input string is a valid JSON document. - * - * @param json - * Input document as a string. - * @return True or false dependent on whether the input string is a valid JSON - * document - */ - public static boolean isJson(String json) { - Gson gson = new Gson(); - try { - gson.fromJson(json, Object.class); - return true; - } catch (com.google.gson.JsonSyntaxException ex) { - return false; - } - } - /** * Transform UniProt identifier into PDB IDs. - * + * * @param uniprot * {@link MiriamData} with UniProt identifier * @return JSON String with mapping. thrown when there is a problem with @@ -219,16 +230,6 @@ public class PdbAnnotator extends ElementAnnotator implements IExternalService { return isJson(json) ? processMappingData(json) : new ArrayList<>(); } - @Override - public String getCommonName() { - return MiriamType.PDB.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.PDB.getDbHomepage(); - } - @Override protected WebPageDownloader getWebPageDownloader() { return super.getWebPageDownloader(); @@ -239,19 +240,4 @@ public class PdbAnnotator extends ElementAnnotator implements IExternalService { super.setWebPageDownloader(webPageDownloader); } - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.UNIPROT)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList(new AnnotatorOutputParameter(MiriamType.PDB)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.UNIPROT, "P29373"); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java index 4bd99f0f05..e2335ab292 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotator.java @@ -1,25 +1,18 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; import java.util.Map.Entry; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; +import com.google.gson.*; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; - +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.MinervaLoggerAppender; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; @@ -27,10 +20,7 @@ import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Chemical; import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements a backend to RECON database. @@ -317,45 +307,6 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService } } - public MiriamData createKeggMiriam(BioEntityProxy element, String value) { - MiriamData md = null; - if (value.startsWith("C")) { - md = new MiriamData(MiriamType.KEGG_COMPOUND, value); - } else if (value.startsWith("R")) { - md = new MiriamData(MiriamType.KEGG_REACTION, value); - } else if (value.startsWith("K")) { - md = new MiriamData(MiriamType.KEGG_ORTHOLOGY, value); - } else { - logger.warn(element.getElementTag() - + "Unknown Kegg identifier type (only Kegg compounds and reactions are supported): \"" + value + "\""); - } - return md; - } - - private JsonObject getBestMatchForAbbreviation(String id, JsonArray asJsonArray) { - String match = null; - JsonObject result = null; - for (JsonElement element : asJsonArray) { - if (((JsonObject) element).get("abbreviation") != null) { - String objAbreviation = ((JsonObject) element).get("abbreviation").getAsString(); - if (match == null) { - match = objAbreviation; - result = (JsonObject) element; - } else if (match.length() > objAbreviation.length()) { - match = objAbreviation; - result = (JsonObject) element; - } else if (id.equalsIgnoreCase(objAbreviation)) { - match = objAbreviation; - result = (JsonObject) element; - } - } else if (match == null) { - logger.warn("No abbreviation found for element: " + element); - result = (JsonObject) element; - } - } - return result; - } - @Override public String getCommonName() { return "Recon annotator"; @@ -366,16 +317,6 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService return "https://www.vmh.life/"; } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - @Override public List<AnnotatorInputParameter> getAvailableInputParameters() { return Arrays.asList(new AnnotatorInputParameter(BioEntityField.ABBREVIATION, MiriamType.VMH_METABOLITE), @@ -420,4 +361,53 @@ public class ReconAnnotator extends ElementAnnotator implements IExternalService return null; } + public MiriamData createKeggMiriam(BioEntityProxy element, String value) { + MiriamData md = null; + if (value.startsWith("C")) { + md = new MiriamData(MiriamType.KEGG_COMPOUND, value); + } else if (value.startsWith("R")) { + md = new MiriamData(MiriamType.KEGG_REACTION, value); + } else if (value.startsWith("K")) { + md = new MiriamData(MiriamType.KEGG_ORTHOLOGY, value); + } else { + logger.warn(element.getElementTag() + + "Unknown Kegg identifier type (only Kegg compounds and reactions are supported): \"" + value + "\""); + } + return md; + } + + private JsonObject getBestMatchForAbbreviation(String id, JsonArray asJsonArray) { + String match = null; + JsonObject result = null; + for (JsonElement element : asJsonArray) { + if (((JsonObject) element).get("abbreviation") != null) { + String objAbreviation = ((JsonObject) element).get("abbreviation").getAsString(); + if (match == null) { + match = objAbreviation; + result = (JsonObject) element; + } else if (match.length() > objAbreviation.length()) { + match = objAbreviation; + result = (JsonObject) element; + } else if (id.equalsIgnoreCase(objAbreviation)) { + match = objAbreviation; + result = (JsonObject) element; + } + } else if (match == null) { + logger.warn("No abbreviation found for element: " + element); + result = (JsonObject) element; + } + } + return result; + } + + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotator.java index 553b202ce2..b2239ef737 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.annotation.services.annotators; import java.util.Arrays; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.WebPageDownloader; @@ -14,9 +15,7 @@ import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements STITCH annotation which is derived from @@ -100,16 +99,6 @@ public class StitchAnnotator extends ElementAnnotator implements IExternalServic return MiriamType.STITCH.getDbHomepage(); } - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - @Override public List<AnnotatorInputParameter> getAvailableInputParameters() { return Arrays.asList(new AnnotatorInputParameter(MiriamType.CHEBI)); @@ -125,4 +114,14 @@ public class StitchAnnotator extends ElementAnnotator implements IExternalServic return new MiriamData(MiriamType.CHEBI, "CHEBI:35697"); } + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } + } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotator.java index f32e7904ef..32511bc1db 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotator.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.annotation.services.annotators; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -13,12 +11,8 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -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.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements a mapping to STRING database. @@ -31,13 +25,11 @@ public class StringAnnotator extends ElementAnnotator implements IExternalServic /** * Service used for annotation of entities using {@link MiriamType#TAIR_LOCUS - * TAIR}. - * Note that STRING annotation process will annotate only - * records which have a TAIR ID assigned by a human annotator. - * Otherwise, it would generate UniProt miriam records also for - * TAIR IDs generated from, e.g., KEGG annotator, i.e. for homologues - * and these UniProt IDs would be indistinguishable from the - * UniProt IDs describing the molecule. + * TAIR}. Note that STRING annotation process will annotate only records which + * have a TAIR ID assigned by a human annotator. Otherwise, it would generate + * UniProt miriam records also for TAIR IDs generated from, e.g., KEGG + * annotator, i.e. for homologues and these UniProt IDs would be + * indistinguishable from the UniProt IDs describing the molecule. */ private TairAnnotator tairAnnotator; @@ -60,9 +52,9 @@ public class StringAnnotator extends ElementAnnotator implements IExternalServic throws AnnotatorException { List<MiriamData> mdUniprots = new ArrayList<>(); if (identifier.getDataType().equals(MiriamType.TAIR_LOCUS)) { - if (identifier.getAnnotator() == null) { - mdUniprots.addAll(tairAnnotator.tairToUniprot(identifier)); - } + if (identifier.getAnnotator() == null) { + mdUniprots.addAll(tairAnnotator.tairToUniprot(identifier)); + } } else if (identifier.getDataType().equals(MiriamType.UNIPROT)) { mdUniprots.add(identifier); } else { @@ -80,27 +72,6 @@ public class StringAnnotator extends ElementAnnotator implements IExternalServic return stringIds.size() > 0; } - /** - * Transform UniProt {@link MiriamData} data to STRING {@link MiriamData}. - * - * @param UniProt - * {@link MiriamData} with UniProt identifier - * @return {@link MiriamData} with STRING identifier - * @throws AnnotatorException - * thrown when there is a problem with accessing external database - */ - public MiriamData uniprotToString(MiriamData uniprot) throws AnnotatorException { - if (uniprot == null) { - return null; - } - - if (!MiriamType.UNIPROT.equals(uniprot.getDataType())) { - throw new InvalidArgumentException(MiriamType.UNIPROT + " expected."); - } - - return new MiriamData(MiriamType.STRING, uniprot.getResource()); - } - @Override public String getCommonName() { return MiriamType.STRING.getCommonName(); @@ -126,4 +97,25 @@ public class StringAnnotator extends ElementAnnotator implements IExternalServic public MiriamData getExampleValidAnnotation() { return new MiriamData(MiriamType.UNIPROT, "P53350"); } + + /** + * Transform UniProt {@link MiriamData} data to STRING {@link MiriamData}. + * + * @param UniProt + * {@link MiriamData} with UniProt identifier + * @return {@link MiriamData} with STRING identifier + * @throws AnnotatorException + * thrown when there is a problem with accessing external database + */ + public MiriamData uniprotToString(MiriamData uniprot) throws AnnotatorException { + if (uniprot == null) { + return null; + } + + if (!MiriamType.UNIPROT.equals(uniprot.getDataType())) { + throw new InvalidArgumentException(MiriamType.UNIPROT + " expected."); + } + + return new MiriamData(MiriamType.STRING, uniprot.getResource()); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotator.java index cf28f3f734..13c12430f8 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotator.java @@ -1,41 +1,31 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -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.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** - * This is a class that implements a backend to TAIR. - * Note that TAIR annotation process will annotate only - * records which have a TAIR ID assigned by a human annotator. - * Otherwise, it would generate UniProt miriam records also for - * TAIR IDs generated from, e.g., KEGG annotator, i.e. for homologues - * and these UniProt IDs would be indistinguishable from the - * UniProt IDs describing the molecule. + * This is a class that implements a backend to TAIR. Note that TAIR annotation + * process will annotate only records which have a TAIR ID assigned by a human + * annotator. Otherwise, it would generate UniProt miriam records also for TAIR + * IDs generated from, e.g., KEGG annotator, i.e. for homologues and these + * UniProt IDs would be indistinguishable from the UniProt IDs describing the + * molecule. * * * @author David Hoksza @@ -50,18 +40,17 @@ public class TairAnnotator extends ElementAnnotator implements IExternalService private static Logger logger = LogManager.getLogger(TairAnnotator.class); /** - * Pattern used for getting Tair Locus ID symbol from UniProt result page. + * Default constructor. */ - private Pattern getUniprotIdParsePattern(String tairId) { - return Pattern.compile("(\\w*)\\tlocus:" + tairId); + public TairAnnotator() { + super(TairAnnotator.class, new Class[] { Protein.class, Gene.class, Rna.class }, false); } - /** - * Default constructor. + * Pattern used for getting Tair Locus ID symbol from UniProt result page. */ - public TairAnnotator() { - super(TairAnnotator.class, new Class[] { Protein.class, Gene.class, Rna.class }, false); + private Pattern getUniprotIdParsePattern(String tairId) { + return Pattern.compile("(\\w*)\\tlocus:" + tairId); } @Override @@ -92,12 +81,13 @@ public class TairAnnotator extends ElementAnnotator implements IExternalService public boolean annotateElement(BioEntityProxy object, MiriamData identifier, AnnotatorData parameters) throws AnnotatorException { - if (identifier.getAnnotator() != null) { - return false; - } + if (identifier.getAnnotator() != null) { + return false; + } if (identifier.getDataType().equals(MiriamType.TAIR_LOCUS)) { - //UniProt are only obained from TAIR's which were provided by the annotator (otherwise we would get - //also UniProt IDs for, e.g., homologous genes' TAIR IDs obtained from KEGG + // UniProt are only obained from TAIR's which were provided by the annotator + // (otherwise we would get + // also UniProt IDs for, e.g., homologous genes' TAIR IDs obtained from KEGG Collection<MiriamData> collection = tairToUniprot(identifier); if (collection.size() > 0) { object.addMiriamData(collection); @@ -111,24 +101,51 @@ public class TairAnnotator extends ElementAnnotator implements IExternalService } } + @Override + public String getCommonName() { + return "TAIR"; + } + + @Override + public String getUrl() { + return MiriamType.TAIR_LOCUS.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList(new AnnotatorOutputParameter(MiriamType.UNIPROT)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.TAIR_LOCUS, "2200950"); + } + /** * Returns URL to UniProt result containing mapped UniProtIds for submitted TAIR * entry. - * + * * @param tairId * TAIR identifier * @return URL to UniProt result page with the TAIR mapping */ private String getUniProtUrl(String tairId) { - return "https://www.uniprot.org/uniprot/?query=database%3A%28type%3Atair%29+" + tairId + "&format=tab&columns=id,database(tair)"; -// return "https://www.uniprot.org/uniprot/?query=database%3A%28type%3Atair+"+tairId+"%29&format=list&columns=id"; + return "https://www.uniprot.org/uniprot/?query=database%3A%28type%3Atair%29+" + tairId + + "&format=tab&columns=id,database(tair)"; + // return + // "https://www.uniprot.org/uniprot/?query=database%3A%28type%3Atair+"+tairId+"%29&format=list&columns=id"; } /** * Parse UniProt result page which contains list of Uniprot ids mapped to * submitted TAIR id. The procedure obtains first {@link MiriamType#UNIPROT} and * returns it. - * + * * @param pageContent * uniprot REST API result page * @return uniprot identifier found on the page @@ -136,22 +153,22 @@ public class TairAnnotator extends ElementAnnotator implements IExternalService private Collection<MiriamData> parseUniprotUniprot(String pageContent, String tairId) { Collection<MiriamData> result = new HashSet<MiriamData>(); if (!pageContent.isEmpty()) { - //the query returns a list of possible matches which needs to be pruned - Matcher m = getUniprotIdParsePattern(tairId).matcher(pageContent); - if (m.find()) { - result.add(new MiriamData(MiriamType.UNIPROT, m.group(1))); - } + // the query returns a list of possible matches which needs to be pruned + Matcher m = getUniprotIdParsePattern(tairId).matcher(pageContent); + if (m.find()) { + result.add(new MiriamData(MiriamType.UNIPROT, m.group(1))); + } } return result; } /** * Transform TAIR identifier into uniprot identifier. - * + * * Used to use the TAIR record page, but that tends to change and moreover TAIR * limits number of accesses from an address. So now the transformation queries * directly UniProt from which the mapping can be obtained as well. - * + * * @param tair * {@link MiriamData} with TAIR identifier * @return {@link MiriamData} with UniProt identifier @@ -179,16 +196,6 @@ public class TairAnnotator extends ElementAnnotator implements IExternalService } } - @Override - public String getCommonName() { - return "TAIR"; - } - - @Override - public String getUrl() { - return MiriamType.TAIR_LOCUS.getDbHomepage(); - } - @Override protected WebPageDownloader getWebPageDownloader() { return super.getWebPageDownloader(); @@ -199,19 +206,4 @@ public class TairAnnotator extends ElementAnnotator implements IExternalService super.setWebPageDownloader(webPageDownloader); } - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.TAIR_LOCUS)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList(new AnnotatorOutputParameter(MiriamType.UNIPROT)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.TAIR_LOCUS, "2200950"); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotator.java index 58aa9b9366..ff87b55ac5 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotator.java @@ -1,34 +1,23 @@ package lcsb.mapviewer.annotation.services.annotators; import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.GeneralCacheInterface; import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; -import lcsb.mapviewer.annotation.services.WrongResponseCodeIOException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -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.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.user.annotator.*; /** * This is a class that implements a backend to uniprot restfull API. @@ -59,7 +48,7 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi */ private Pattern uniprotToEC = Pattern .compile("EC=((\\d+\\.-\\.-\\.-)|(\\d+\\.\\d+\\.-\\.-)|(\\d+\\.\\d+\\.\\d+\\.-)|(\\d+\\.\\d+\\.\\d+\\.\\d+))"); - + /** * Pattern used for getting Tair Locus ID symbol from UniProt result page. */ @@ -132,9 +121,38 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi } } + @Override + public String getCommonName() { + return MiriamType.UNIPROT.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.UNIPROT.getDbHomepage(); + } + + @Override + public List<AnnotatorInputParameter> getAvailableInputParameters() { + return Arrays.asList(new AnnotatorInputParameter(MiriamType.UNIPROT), + new AnnotatorInputParameter(BioEntityField.NAME, MiriamType.UNIPROT)); + } + + @Override + public List<AnnotatorOutputParameter> getAvailableOuputProperties() { + return Arrays.asList(new AnnotatorOutputParameter(MiriamType.HGNC_SYMBOL), + new AnnotatorOutputParameter(MiriamType.UNIPROT), + new AnnotatorOutputParameter(MiriamType.EC), + new AnnotatorOutputParameter(MiriamType.ENTREZ)); + } + + @Override + public MiriamData getExampleValidAnnotation() { + return new MiriamData(MiriamType.UNIPROT, "Q5S007"); + } + /** * Returns url to uniprot restfull API about uniprot entry. - * + * * @param uniprotId * uniprot identifier * @return url to uniprot restfull API about uniprot entry @@ -142,23 +160,24 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi private String getUniprotUrl(String uniprotId) { return "https://www.uniprot.org/uniprot/" + uniprotId + ".txt"; } - + /** * Returns URL to UniProt result containing mapped UniProtIds for submitted TAIR * entry. - * + * * @param tairId * TAIR identifier * @return URL to UniProt result page with the TAIR mapping */ private String getUniProtTairLocus2IdUrl(String tairLocusName) { - return "https://www.uniprot.org/uniprot/?query=database%3A%28type%3Atair+" + tairLocusName + "%29&format=tab&columns=id,database(tair)"; + return "https://www.uniprot.org/uniprot/?query=database%3A%28type%3Atair+" + tairLocusName + + "%29&format=tab&columns=id,database(tair)"; } /** * Parse uniprot webpage to find information about {@link MiriamType#ENTREZ} and * returns them. - * + * * @param pageContent * uniprot info page * @return set of entrez identifiers found on the webpage @@ -175,7 +194,7 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi /** * Parse uniprot webpage to find information about * {@link MiriamType#HGNC_SYMBOL} and returns them. - * + * * @param pageContent * uniprot info page * @return set of entrez identifiers found on the webpage @@ -192,7 +211,7 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi /** * Parse UniProt webpage to find information about {@link MiriamType#EC}s and * returns them. - * + * * @param pageContent * UniProt info page * @return EC found on the page @@ -208,7 +227,7 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi /** * Transform uniprot identifier into hgnc name. - * + * * @param uniprot * {@link MiriamData} with uniprot identifier * @return {@link MiriamData} with hgnc name @@ -241,7 +260,7 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi /** * Transform uniprot identifier into EC identifiers. - * + * * @param uniprot * {@link MiriamData} with uniprot identifier * @return ArrayList of {@link MiriamData} with EC codes @@ -268,12 +287,12 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi } } - + /** - * Transform TAIR Locus name into TAIR Locus identifier. - * UniProt is used for this task because TAIR i) does not have - * an API and ii) restricts the number of accesses. - * + * Transform TAIR Locus name into TAIR Locus identifier. UniProt is used for + * this task because TAIR i) does not have an API and ii) restricts the number + * of accesses. + * * @param tairLocus * String with the TAIR Locus name. * @return {@link MiriamData} with TAIR Locus ID @@ -281,29 +300,19 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi * thrown when there is a problem with accessing external database */ public MiriamData uniprotTairLocusNameToId(String tairLocus) throws UniprotSearchException { - String accessUrl = getUniProtTairLocus2IdUrl(tairLocus); - try { - String pageContent = getWebPageContent(accessUrl); - Matcher m = uniprotTairLocusToId.matcher(pageContent); - if (m.find()) { - return new MiriamData(MiriamType.TAIR_LOCUS, m.group(1)); - } else { - logger.warn("No TAIR ID found for locus: " + tairLocus); - return new MiriamData(); - } - } catch (IOException e) { - throw new UniprotSearchException("Problem with accessing uniprot webpage", e); - } - } - - @Override - public String getCommonName() { - return MiriamType.UNIPROT.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.UNIPROT.getDbHomepage(); + String accessUrl = getUniProtTairLocus2IdUrl(tairLocus); + try { + String pageContent = getWebPageContent(accessUrl); + Matcher m = uniprotTairLocusToId.matcher(pageContent); + if (m.find()) { + return new MiriamData(MiriamType.TAIR_LOCUS, m.group(1)); + } else { + logger.warn("No TAIR ID found for locus: " + tairLocus); + return new MiriamData(); + } + } catch (IOException e) { + throw new UniprotSearchException("Problem with accessing uniprot webpage", e); + } } @Override @@ -315,23 +324,4 @@ public class UniprotAnnotator extends ElementAnnotator implements IExternalServi protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { super.setWebPageDownloader(webPageDownloader); } - - @Override - public List<AnnotatorInputParameter> getAvailableInputParameters() { - return Arrays.asList(new AnnotatorInputParameter(MiriamType.UNIPROT), - new AnnotatorInputParameter(BioEntityField.NAME, MiriamType.UNIPROT)); - } - - @Override - public List<AnnotatorOutputParameter> getAvailableOuputProperties() { - return Arrays.asList(new AnnotatorOutputParameter(MiriamType.HGNC_SYMBOL), - new AnnotatorOutputParameter(MiriamType.UNIPROT), - new AnnotatorOutputParameter(MiriamType.EC), - new AnnotatorOutputParameter(MiriamType.ENTREZ)); - } - - @Override - public MiriamData getExampleValidAnnotation() { - return new MiriamData(MiriamType.UNIPROT, "Q5S007"); - } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/package-info.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/package-info.java index 25b66c7be1..1d74ee6fff 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/package-info.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/package-info.java @@ -6,4 +6,3 @@ * */ package lcsb.mapviewer.annotation.services.annotators; - diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/AbstractReferenceGenomeConnector.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/AbstractReferenceGenomeConnector.java index f46251b46d..281a9d4bb5 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/AbstractReferenceGenomeConnector.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/AbstractReferenceGenomeConnector.java @@ -2,15 +2,10 @@ package lcsb.mapviewer.annotation.services.genome; import java.io.IOException; import java.net.URISyntaxException; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; - -import org.apache.logging.log4j.*; +import java.util.concurrent.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.cache.BigFileCache; @@ -32,365 +27,369 @@ import lcsb.mapviewer.persist.dao.map.layout.ReferenceGenomeGeneMappingDao; */ public abstract class AbstractReferenceGenomeConnector extends CachableInterface implements ReferenceGenomeConnector { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(AbstractReferenceGenomeConnector.class); - - /** - * Utils that help to manage the sessions in custom multithreaded - * implementation. - */ - @Autowired - private DbUtils dbUtils; - - /** - * Data access object for reference genomes that we have in a database. - */ - @Autowired - private ReferenceGenomeDao referenceGenomeDao; - - /** - * Data access object for reference genome mappings that we have in a - * database. - */ - @Autowired - private ReferenceGenomeGeneMappingDao referenceGenomeGeneMappingDao; - - /** - * Interface for storing/accessing big files on teh server (we have local copy - * if big files on the server). - */ - @Autowired - private BigFileCache bigFileCache; - - /** - * Service used for executing tasks in separate thread. - */ - private ExecutorService asyncExecutorService; - - /** - * Service used for executing tasks immediately. - */ - private ExecutorService syncExecutorService; - - /** - * Default constructor. - * - * @param clazz - * class that extends this abstract interface - */ - public AbstractReferenceGenomeConnector(Class<? extends CachableInterface> clazz) { - super(clazz); - // the executor is a daemon thread so that it will get killed automatically - // when the main program exits - asyncExecutorService = Executors.newScheduledThreadPool(10, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }); - syncExecutorService = Executors.newScheduledThreadPool(1, new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r); - t.setDaemon(true); - return t; - } - }); - - // put in the queue empty task to make sure that everything was initialized - // (additional managing thread was createed) - asyncExecutorService.submit(new Callable<Object>() { - @Override - public Object call() throws Exception { - return null; - } - }); - syncExecutorService.submit(new Callable<Object>() { - @Override - public Object call() throws Exception { - return null; - } - }); - } - - /** - * Task that will be able to fetch mapping genome file with given version from - * externalserver. - * - * @author Piotr Gawron - * - */ - private final class DownloadGeneMappingGenomeVersionTask implements Callable<Void> { - - /** - * Url to the file that we want to download. - * - */ - private String url; - - /** - * Callback listener that will receive information about download progress. - * - */ - private IProgressUpdater updater; - - /** - * Name of the gen genome mapping. - */ - private String name; - - /** - * Genome where mapping should be added. - */ - private ReferenceGenome referenceGenome; - - /** - * Default constructor. - * - * @param url - * {@link #url} - * @param updater - * {@link #updater} - * @param referenceGenome - * {@link #referenceGenome} - * @param name - * {@link #name} - * @throws ReferenceGenomeConnectorException - */ - private DownloadGeneMappingGenomeVersionTask(ReferenceGenome referenceGenome, String name, String url, IProgressUpdater updater) throws ReferenceGenomeConnectorException { - this.url = url; - this.referenceGenome = referenceGenome; - this.name = name; - if (updater != null) { - this.updater = updater; - } else { - this.updater = new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }; - } - - } - - @Override - public Void call() throws Exception { - getDbUtils().createSessionForCurrentThread(); - try { - ReferenceGenome referenceGenome = getReferenceGenomeDao().getById(this.referenceGenome.getId()); - for (ReferenceGenomeGeneMapping mapping : referenceGenome.getGeneMapping()) { - if (mapping.getName().equals(name)) { - throw new ReferenceGenomeConnectorException("Gene mapping with name: \"" + name + "\" already exists."); - } - } - if (!url.toLowerCase().endsWith("bb")) { - throw new ReferenceGenomeConnectorException("Only big bed format files are supported but found: \"" + url + "\"."); - } - ReferenceGenomeGeneMapping mapping = new ReferenceGenomeGeneMapping(); - mapping.setName(name); - mapping.setSourceUrl(url); - referenceGenome.addReferenceGenomeGeneMapping(mapping); - getReferenceGenomeDao().update(referenceGenome); - getReferenceGenomeDao().commit(); - getReferenceGenomeDao().flush(); - getBigFileCache().downloadFile(url, false, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - if (updater != null) { - updater.setProgress(progress); - } - // we have to get the object because it's in separate thread - ReferenceGenomeGeneMapping temp = getReferenceGenomeGeneMappingDao().getById(mapping.getId()); - temp.setDownloadProgress(progress); - getReferenceGenomeGeneMappingDao().update(temp); - getReferenceGenomeGeneMappingDao().commit(); - } - }); - ReferenceGenomeGeneMapping temp = getReferenceGenomeGeneMappingDao().getById(mapping.getId()); - temp.setDownloadProgress(100.0); - getReferenceGenomeGeneMappingDao().update(temp); - return null; - } catch (Exception e) { - logger.error(e, e); - throw e; - } finally { - getDbUtils().closeSessionForCurrentThread(); - } - } - - } - - @Override - public void downloadGeneMappingGenomeVersion(ReferenceGenome referenceGenome, String name, IProgressUpdater updater, boolean async, String url) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException { - Callable<Void> computations = new DownloadGeneMappingGenomeVersionTask(referenceGenome, name, url, updater); - if (async) { - getAsyncExecutorService().submit(computations); - } else { - Future<Void> task = getSyncExecutorService().submit(computations); - executeTask(task); - } - } - - /** - * @return the dbUtils - * @see #dbUtils - */ - public DbUtils getDbUtils() { - return dbUtils; - } - - /** - * @param dbUtils - * the dbUtils to set - * @see #dbUtils - */ - public void setDbUtils(DbUtils dbUtils) { - this.dbUtils = dbUtils; - } - - /** - * @return the referenceGenomeDao - * @see #referenceGenomeDao - */ - public ReferenceGenomeDao getReferenceGenomeDao() { - return referenceGenomeDao; - } - - /** - * @param referenceGenomeDao - * the referenceGenomeDao to set - * @see #referenceGenomeDao - */ - public void setReferenceGenomeDao(ReferenceGenomeDao referenceGenomeDao) { - this.referenceGenomeDao = referenceGenomeDao; - } - - /** - * @return the referenceGenomeGeneMappingDao - * @see #referenceGenomeGeneMappingDao - */ - public ReferenceGenomeGeneMappingDao getReferenceGenomeGeneMappingDao() { - return referenceGenomeGeneMappingDao; - } - - /** - * @param referenceGenomeGeneMappingDao - * the referenceGenomeGeneMappingDao to set - * @see #referenceGenomeGeneMappingDao - */ - public void setReferenceGenomeGeneMappingDao(ReferenceGenomeGeneMappingDao referenceGenomeGeneMappingDao) { - this.referenceGenomeGeneMappingDao = referenceGenomeGeneMappingDao; - } - - /** - * @return the bigFileCache - * @see #bigFileCache - */ - public BigFileCache getBigFileCache() { - return bigFileCache; - } - - /** - * @param bigFileCache - * the bigFileCache to set - * @see #bigFileCache - */ - public void setBigFileCache(BigFileCache bigFileCache) { - this.bigFileCache = bigFileCache; - } - - @Override - public void removeGeneMapping(ReferenceGenomeGeneMapping mapping2) throws IOException { - ReferenceGenomeGeneMapping dbMapping = getReferenceGenomeGeneMappingDao().getById(mapping2.getId()); - if (dbMapping == null) { - logger.warn("Mapping doesn't exist in the DB"); - } else { - if (getBigFileCache().isCached(dbMapping.getSourceUrl())) { - getBigFileCache().removeFile(dbMapping.getSourceUrl()); - } - ReferenceGenome genome = dbMapping.getReferenceGenome(); - genome.getGeneMapping().remove(dbMapping); - getReferenceGenomeGeneMappingDao().delete(dbMapping); - } - } - - /** - * @return the asyncExecutorService - * @see #asyncExecutorService - */ - protected ExecutorService getAsyncExecutorService() { - return asyncExecutorService; - } - - /** - * @param asyncExecutorService - * the asyncExecutorService to set - * @see #asyncExecutorService - */ - protected void setAsyncExecutorService(ExecutorService asyncExecutorService) { - this.asyncExecutorService = asyncExecutorService; - } - - /** - * @return the syncExecutorService - * @see #syncExecutorService - */ - protected ExecutorService getSyncExecutorService() { - return syncExecutorService; - } - - /** - * @param syncExecutorService - * the syncExecutorService to set - * @see #syncExecutorService - */ - protected void setSyncExecutorService(ExecutorService syncExecutorService) { - this.syncExecutorService = syncExecutorService; - } - - /** - * Return number of tasks that are executed or are waiting for execution. - * - * @return number of tasks that are executed or are waiting for execution - */ - public int getDownloadThreadCount() { - return ((ScheduledThreadPoolExecutor) asyncExecutorService).getQueue().size() + ((ScheduledThreadPoolExecutor) asyncExecutorService).getActiveCount() - + ((ScheduledThreadPoolExecutor) syncExecutorService).getQueue().size() + ((ScheduledThreadPoolExecutor) syncExecutorService).getActiveCount(); - } - - /** - * Executes download/update task. - * - * @param task - * task to be executed - * @throws URISyntaxException - * thrown when task finsihed with {@link URISyntaxException} - * @throws IOException - * thrown when task finsihed with {@link IOException} - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with genome connector - */ - void executeTask(Future<?> task) throws URISyntaxException, IOException, ReferenceGenomeConnectorException { - try { - task.get(); - } catch (InterruptedException e) { - logger.error(e, e); - } catch (ExecutionException e) { - if (e.getCause() instanceof URISyntaxException) { - throw (URISyntaxException) e.getCause(); - } else if (e.getCause() instanceof IOException) { - throw new IOException((IOException) e.getCause()); - } else if (e.getCause() instanceof ReferenceGenomeConnectorException) { - throw new ReferenceGenomeConnectorException((ReferenceGenomeConnectorException) e.getCause()); - } else { - throw new InvalidStateException(e); - } - } - } + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(AbstractReferenceGenomeConnector.class); + + /** + * Utils that help to manage the sessions in custom multithreaded + * implementation. + */ + @Autowired + private DbUtils dbUtils; + + /** + * Data access object for reference genomes that we have in a database. + */ + @Autowired + private ReferenceGenomeDao referenceGenomeDao; + + /** + * Data access object for reference genome mappings that we have in a database. + */ + @Autowired + private ReferenceGenomeGeneMappingDao referenceGenomeGeneMappingDao; + + /** + * Interface for storing/accessing big files on teh server (we have local copy + * if big files on the server). + */ + @Autowired + private BigFileCache bigFileCache; + + /** + * Service used for executing tasks in separate thread. + */ + private ExecutorService asyncExecutorService; + + /** + * Service used for executing tasks immediately. + */ + private ExecutorService syncExecutorService; + + /** + * Default constructor. + * + * @param clazz + * class that extends this abstract interface + */ + public AbstractReferenceGenomeConnector(Class<? extends CachableInterface> clazz) { + super(clazz); + // the executor is a daemon thread so that it will get killed automatically + // when the main program exits + asyncExecutorService = Executors.newScheduledThreadPool(10, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }); + syncExecutorService = Executors.newScheduledThreadPool(1, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(r); + t.setDaemon(true); + return t; + } + }); + + // put in the queue empty task to make sure that everything was initialized + // (additional managing thread was createed) + asyncExecutorService.submit(new Callable<Object>() { + @Override + public Object call() throws Exception { + return null; + } + }); + syncExecutorService.submit(new Callable<Object>() { + @Override + public Object call() throws Exception { + return null; + } + }); + } + + @Override + public void downloadGeneMappingGenomeVersion(ReferenceGenome referenceGenome, String name, IProgressUpdater updater, + boolean async, String url) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException { + Callable<Void> computations = new DownloadGeneMappingGenomeVersionTask(referenceGenome, name, url, updater); + if (async) { + getAsyncExecutorService().submit(computations); + } else { + Future<Void> task = getSyncExecutorService().submit(computations); + executeTask(task); + } + } + + @Override + public void removeGeneMapping(ReferenceGenomeGeneMapping mapping2) throws IOException { + ReferenceGenomeGeneMapping dbMapping = getReferenceGenomeGeneMappingDao().getById(mapping2.getId()); + if (dbMapping == null) { + logger.warn("Mapping doesn't exist in the DB"); + } else { + if (getBigFileCache().isCached(dbMapping.getSourceUrl())) { + getBigFileCache().removeFile(dbMapping.getSourceUrl()); + } + ReferenceGenome genome = dbMapping.getReferenceGenome(); + genome.getGeneMapping().remove(dbMapping); + getReferenceGenomeGeneMappingDao().delete(dbMapping); + } + } + + /** + * @return the dbUtils + * @see #dbUtils + */ + public DbUtils getDbUtils() { + return dbUtils; + } + + /** + * @param dbUtils + * the dbUtils to set + * @see #dbUtils + */ + public void setDbUtils(DbUtils dbUtils) { + this.dbUtils = dbUtils; + } + + /** + * @return the referenceGenomeDao + * @see #referenceGenomeDao + */ + public ReferenceGenomeDao getReferenceGenomeDao() { + return referenceGenomeDao; + } + + /** + * @param referenceGenomeDao + * the referenceGenomeDao to set + * @see #referenceGenomeDao + */ + public void setReferenceGenomeDao(ReferenceGenomeDao referenceGenomeDao) { + this.referenceGenomeDao = referenceGenomeDao; + } + + /** + * @return the referenceGenomeGeneMappingDao + * @see #referenceGenomeGeneMappingDao + */ + public ReferenceGenomeGeneMappingDao getReferenceGenomeGeneMappingDao() { + return referenceGenomeGeneMappingDao; + } + + /** + * @param referenceGenomeGeneMappingDao + * the referenceGenomeGeneMappingDao to set + * @see #referenceGenomeGeneMappingDao + */ + public void setReferenceGenomeGeneMappingDao(ReferenceGenomeGeneMappingDao referenceGenomeGeneMappingDao) { + this.referenceGenomeGeneMappingDao = referenceGenomeGeneMappingDao; + } + + /** + * @return the bigFileCache + * @see #bigFileCache + */ + public BigFileCache getBigFileCache() { + return bigFileCache; + } + + /** + * @param bigFileCache + * the bigFileCache to set + * @see #bigFileCache + */ + public void setBigFileCache(BigFileCache bigFileCache) { + this.bigFileCache = bigFileCache; + } + + /** + * @return the asyncExecutorService + * @see #asyncExecutorService + */ + protected ExecutorService getAsyncExecutorService() { + return asyncExecutorService; + } + + /** + * @param asyncExecutorService + * the asyncExecutorService to set + * @see #asyncExecutorService + */ + protected void setAsyncExecutorService(ExecutorService asyncExecutorService) { + this.asyncExecutorService = asyncExecutorService; + } + + /** + * @return the syncExecutorService + * @see #syncExecutorService + */ + protected ExecutorService getSyncExecutorService() { + return syncExecutorService; + } + + /** + * @param syncExecutorService + * the syncExecutorService to set + * @see #syncExecutorService + */ + protected void setSyncExecutorService(ExecutorService syncExecutorService) { + this.syncExecutorService = syncExecutorService; + } + + /** + * Return number of tasks that are executed or are waiting for execution. + * + * @return number of tasks that are executed or are waiting for execution + */ + public int getDownloadThreadCount() { + return ((ScheduledThreadPoolExecutor) asyncExecutorService).getQueue().size() + + ((ScheduledThreadPoolExecutor) asyncExecutorService).getActiveCount() + + ((ScheduledThreadPoolExecutor) syncExecutorService).getQueue().size() + + ((ScheduledThreadPoolExecutor) syncExecutorService).getActiveCount(); + } + + /** + * Executes download/update task. + * + * @param task + * task to be executed + * @throws URISyntaxException + * thrown when task finsihed with {@link URISyntaxException} + * @throws IOException + * thrown when task finsihed with {@link IOException} + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with genome connector + */ + void executeTask(Future<?> task) throws URISyntaxException, IOException, ReferenceGenomeConnectorException { + try { + task.get(); + } catch (InterruptedException e) { + logger.error(e, e); + } catch (ExecutionException e) { + if (e.getCause() instanceof URISyntaxException) { + throw (URISyntaxException) e.getCause(); + } else if (e.getCause() instanceof IOException) { + throw new IOException((IOException) e.getCause()); + } else if (e.getCause() instanceof ReferenceGenomeConnectorException) { + throw new ReferenceGenomeConnectorException((ReferenceGenomeConnectorException) e.getCause()); + } else { + throw new InvalidStateException(e); + } + } + } + + /** + * Task that will be able to fetch mapping genome file with given version from + * externalserver. + * + * @author Piotr Gawron + * + */ + private final class DownloadGeneMappingGenomeVersionTask implements Callable<Void> { + + /** + * Url to the file that we want to download. + * + */ + private String url; + + /** + * Callback listener that will receive information about download progress. + * + */ + private IProgressUpdater updater; + + /** + * Name of the gen genome mapping. + */ + private String name; + + /** + * Genome where mapping should be added. + */ + private ReferenceGenome referenceGenome; + + /** + * Default constructor. + * + * @param url + * {@link #url} + * @param updater + * {@link #updater} + * @param referenceGenome + * {@link #referenceGenome} + * @param name + * {@link #name} + * @throws ReferenceGenomeConnectorException + */ + private DownloadGeneMappingGenomeVersionTask(ReferenceGenome referenceGenome, String name, String url, + IProgressUpdater updater) throws ReferenceGenomeConnectorException { + this.url = url; + this.referenceGenome = referenceGenome; + this.name = name; + if (updater != null) { + this.updater = updater; + } else { + this.updater = new IProgressUpdater() { + @Override + public void setProgress(double progress) { + } + }; + } + + } + + @Override + public Void call() throws Exception { + getDbUtils().createSessionForCurrentThread(); + try { + ReferenceGenome referenceGenome = getReferenceGenomeDao().getById(this.referenceGenome.getId()); + for (ReferenceGenomeGeneMapping mapping : referenceGenome.getGeneMapping()) { + if (mapping.getName().equals(name)) { + throw new ReferenceGenomeConnectorException("Gene mapping with name: \"" + name + "\" already exists."); + } + } + if (!url.toLowerCase().endsWith("bb")) { + throw new ReferenceGenomeConnectorException( + "Only big bed format files are supported but found: \"" + url + "\"."); + } + ReferenceGenomeGeneMapping mapping = new ReferenceGenomeGeneMapping(); + mapping.setName(name); + mapping.setSourceUrl(url); + referenceGenome.addReferenceGenomeGeneMapping(mapping); + getReferenceGenomeDao().update(referenceGenome); + getReferenceGenomeDao().commit(); + getReferenceGenomeDao().flush(); + getBigFileCache().downloadFile(url, false, new IProgressUpdater() { + @Override + public void setProgress(double progress) { + if (updater != null) { + updater.setProgress(progress); + } + // we have to get the object because it's in separate thread + ReferenceGenomeGeneMapping temp = getReferenceGenomeGeneMappingDao().getById(mapping.getId()); + temp.setDownloadProgress(progress); + getReferenceGenomeGeneMappingDao().update(temp); + getReferenceGenomeGeneMappingDao().commit(); + } + }); + ReferenceGenomeGeneMapping temp = getReferenceGenomeGeneMappingDao().getById(mapping.getId()); + temp.setDownloadProgress(100.0); + getReferenceGenomeGeneMappingDao().update(temp); + return null; + } catch (Exception e) { + logger.error(e, e); + throw e; + } finally { + getDbUtils().closeSessionForCurrentThread(); + } + } + + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/FileNotAvailableException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/FileNotAvailableException.java index 0a11c19a4b..9a358e7326 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/FileNotAvailableException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/FileNotAvailableException.java @@ -9,40 +9,40 @@ package lcsb.mapviewer.annotation.services.genome; */ public class FileNotAvailableException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * error message - */ - public FileNotAvailableException(String message) { - super(message); - } + /** + * Default constructor. + * + * @param message + * error message + */ + public FileNotAvailableException(String message) { + super(message); + } - /** - * Default constructor. - * - * @param cause - * error cause - */ - public FileNotAvailableException(Throwable cause) { - super(cause); - } + /** + * Default constructor. + * + * @param cause + * error cause + */ + public FileNotAvailableException(Throwable cause) { + super(cause); + } - /** - * Default constructor. - * - * @param message - * error message - * @param cause - * error cause - */ - public FileNotAvailableException(String message, Throwable cause) { - super(message, cause); - } + /** + * Default constructor. + * + * @param message + * error message + * @param cause + * error cause + */ + public FileNotAvailableException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnector.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnector.java index 0eeb5101a6..5bf0554bb1 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnector.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnector.java @@ -17,142 +17,142 @@ import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; */ public interface ReferenceGenomeConnector { - /** - * Returns list of downloaded reference genomes. This list should contain list - * of differente versions of reference genome from this database for given - * organism. - * - * @param organism - * organism for which list should be obtained - * @return list of downloaded reference genomes - */ - List<String> getDownloadedGenomeVersions(MiriamData organism); + /** + * Returns list of downloaded reference genomes. This list should contain list + * of differente versions of reference genome from this database for given + * organism. + * + * @param organism + * organism for which list should be obtained + * @return list of downloaded reference genomes + */ + List<String> getDownloadedGenomeVersions(MiriamData organism); - /** - * Returns list of available reference genomes for given organism. - * - * @param organism - * organism for which list should be obtained - * @return list of available reference genomes - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with accessing external database - */ - List<String> getAvailableGenomeVersion(MiriamData organism) throws ReferenceGenomeConnectorException; + /** + * Returns list of available reference genomes for given organism. + * + * @param organism + * organism for which list should be obtained + * @return list of available reference genomes + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with accessing external database + */ + List<String> getAvailableGenomeVersion(MiriamData organism) throws ReferenceGenomeConnectorException; - /** - * Returns list of reference genome organism available in this database. - * - * @return list of reference genome organisms - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with accessing external database - */ - List<MiriamData> getAvailableOrganisms() throws ReferenceGenomeConnectorException; + /** + * Returns list of reference genome organism available in this database. + * + * @return list of reference genome organisms + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with accessing external database + */ + List<MiriamData> getAvailableOrganisms() throws ReferenceGenomeConnectorException; - /** - * Downloads reference genome with specified version. - * - * @param organism - * organism for which reference genome should be downloaded - * @param version - * version of reference genome - * @param updater - * callback funtion that will be called to update information about - * progress - * @param async - * should the download be performed asynchronously - * @throws FileNotAvailableException - * thrown when file for given input reference genome is not - * available - * @throws IOException - * thrown when there is a problem with downloading file - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with genome connector - */ - void downloadGenomeVersion(MiriamData organism, String version, IProgressUpdater updater, boolean async) - throws FileNotAvailableException, IOException, ReferenceGenomeConnectorException; + /** + * Downloads reference genome with specified version. + * + * @param organism + * organism for which reference genome should be downloaded + * @param version + * version of reference genome + * @param updater + * callback funtion that will be called to update information about + * progress + * @param async + * should the download be performed asynchronously + * @throws FileNotAvailableException + * thrown when file for given input reference genome is not available + * @throws IOException + * thrown when there is a problem with downloading file + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with genome connector + */ + void downloadGenomeVersion(MiriamData organism, String version, IProgressUpdater updater, boolean async) + throws FileNotAvailableException, IOException, ReferenceGenomeConnectorException; - /** - * Downloads reference genome with specified version. - * - * @param organism - * organism for which reference genome should be downloaded - * @param version - * version of reference genome - * @param updater - * callback funtion that will be called to update information about - * progress - * @param async - * should the download be performed asynchronously - * @param url - * url that points to the reference genome - * @throws IOException - * thrown when there is a problem with downloading file - * @throws URISyntaxException - * thrown when url is invalid - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with genome connector - */ - void downloadGenomeVersion(MiriamData organism, String version, IProgressUpdater updater, boolean async, String url) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException; + /** + * Downloads reference genome with specified version. + * + * @param organism + * organism for which reference genome should be downloaded + * @param version + * version of reference genome + * @param updater + * callback funtion that will be called to update information about + * progress + * @param async + * should the download be performed asynchronously + * @param url + * url that points to the reference genome + * @throws IOException + * thrown when there is a problem with downloading file + * @throws URISyntaxException + * thrown when url is invalid + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with genome connector + */ + void downloadGenomeVersion(MiriamData organism, String version, IProgressUpdater updater, boolean async, String url) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException; - /** - * Downloads gene mapping for reference genome. - * - * @param referenceGenome - * reference genome for which gene mapping is downloaded - * @param updater - * callback funtion that will be called to update information about - * progress - * @param async - * should the download be performed asynchronously - * @param name - * name of the mapping - * @param url - * url that points to the reference genome - * @throws IOException - * thrown when there is a problem with downloading file - * @throws URISyntaxException - * thrown when url is invalid - * @throws ReferenceGenomeConnectorException - * thrown when there is problem with accessing external database - */ - void downloadGeneMappingGenomeVersion(ReferenceGenome referenceGenome, String name, IProgressUpdater updater, boolean async, String url) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException; + /** + * Downloads gene mapping for reference genome. + * + * @param referenceGenome + * reference genome for which gene mapping is downloaded + * @param updater + * callback funtion that will be called to update information about + * progress + * @param async + * should the download be performed asynchronously + * @param name + * name of the mapping + * @param url + * url that points to the reference genome + * @throws IOException + * thrown when there is a problem with downloading file + * @throws URISyntaxException + * thrown when url is invalid + * @throws ReferenceGenomeConnectorException + * thrown when there is problem with accessing external database + */ + void downloadGeneMappingGenomeVersion(ReferenceGenome referenceGenome, String name, IProgressUpdater updater, + boolean async, String url) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException; - /** - * Removes reference genome. - * - * @param organism - * organism that defines reference genome - * @param version - * version of the reference genome - * @throws IOException - * thrown when there is a problem with removing file - */ - void removeGenomeVersion(MiriamData organism, String version) throws IOException; + /** + * Removes reference genome. + * + * @param organism + * organism that defines reference genome + * @param version + * version of the reference genome + * @throws IOException + * thrown when there is a problem with removing file + */ + void removeGenomeVersion(MiriamData organism, String version) throws IOException; - /** - * Returns url to the file that describes reference genome. - * - * @param organism - * organism of reference genome - * @param version - * version of the reference genome - * @return url to the file that describes reference genome - * @throws FileNotAvailableException - * thrown when file describing reference genome cannot be found - */ - String getGenomeVersionFile(MiriamData organism, String version) throws FileNotAvailableException; + /** + * Returns url to the file that describes reference genome. + * + * @param organism + * organism of reference genome + * @param version + * version of the reference genome + * @return url to the file that describes reference genome + * @throws FileNotAvailableException + * thrown when file describing reference genome cannot be found + */ + String getGenomeVersionFile(MiriamData organism, String version) throws FileNotAvailableException; - /** - * Removes gene mapping from reference genome. - * - * @param mapping - * mapping to be removed - * @throws IOException - * thrown when removing of a file encountered some problems - */ + /** + * Removes gene mapping from reference genome. + * + * @param mapping + * mapping to be removed + * @throws IOException + * thrown when removing of a file encountered some problems + */ - void removeGeneMapping(ReferenceGenomeGeneMapping mapping) throws IOException; + void removeGeneMapping(ReferenceGenomeGeneMapping mapping) throws IOException; } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnectorException.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnectorException.java index 58253f8b61..84cc441980 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnectorException.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/ReferenceGenomeConnectorException.java @@ -10,41 +10,41 @@ package lcsb.mapviewer.annotation.services.genome; */ public class ReferenceGenomeConnectorException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * message associated with exception - * @param exception - * original exception - */ - public ReferenceGenomeConnectorException(String message, Exception exception) { - super(message, exception); - } + /** + * Default constructor. + * + * @param message + * message associated with exception + * @param exception + * original exception + */ + public ReferenceGenomeConnectorException(String message, Exception exception) { + super(message, exception); + } - /** - * Default constructor. - * - * @param message - * message associated with exception - */ - public ReferenceGenomeConnectorException(String message) { - super(message); - } + /** + * Default constructor. + * + * @param message + * message associated with exception + */ + public ReferenceGenomeConnectorException(String message) { + super(message); + } - /** - * Default constructor. - * - * @param cause - * original exception - */ - public ReferenceGenomeConnectorException(Exception cause) { - super(cause); - } + /** + * Default constructor. + * + * @param cause + * original exception + */ + public ReferenceGenomeConnectorException(Exception cause) { + super(cause); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnector.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnector.java index e58e376800..a8f94a0215 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnector.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnector.java @@ -2,23 +2,17 @@ package lcsb.mapviewer.annotation.services.genome; import java.io.IOException; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.Future; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPClient; -import org.apache.commons.net.ftp.FTPFile; -import org.apache.commons.net.ftp.FTPReply; -import org.apache.logging.log4j.*; +import org.apache.commons.net.ftp.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import lcsb.mapviewer.annotation.cache.SourceNotAvailable; import lcsb.mapviewer.annotation.cache.WebPageDownloader; @@ -29,10 +23,7 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; -import org.springframework.stereotype.Service; +import lcsb.mapviewer.model.map.layout.*; /** * Implementeation of reference genome connector accessing @@ -44,17 +35,15 @@ import org.springframework.stereotype.Service; @Service public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnector implements ReferenceGenomeConnector { - /** - * Server domain name. - */ - private static final String SERVER = "hgdownload.cse.ucsc.edu"; - /** * Prefix string used for marking queries in cache database that identifies list * of reference genome versions by organism id. */ static final String FILENAME_BY_ORGANISM_VERSION_PREFIX = "ORGANISM_VERSION_FILE:"; - + /** + * Server domain name. + */ + private static final String SERVER = "hgdownload.cse.ucsc.edu"; /** * Default class logger. */ @@ -186,6 +175,92 @@ public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnect } } + @Override + public void downloadGenomeVersion(MiriamData organism, String version, IProgressUpdater updater, boolean async, + String customUrl) throws IOException, URISyntaxException, ReferenceGenomeConnectorException { + Callable<Void> computations = new DownloadGenomeVersionTask(organism, version, customUrl, updater); + if (async) { + getAsyncExecutorService().submit(computations); + } else { + Future<Void> task = getSyncExecutorService().submit(computations); + executeTask(task); + } + } + + @Override + public void removeGenomeVersion(MiriamData organism, String version) throws IOException { + List<ReferenceGenome> genomes = getReferenceGenomeDao().getByType(ReferenceGenomeType.UCSC); + for (ReferenceGenome referenceGenome : genomes) { + if (referenceGenome.getOrganism().equals(organism) && referenceGenome.getVersion().equals(version)) { + // removing file from big file cache might not be the best idea here + if (getBigFileCache().isCached(referenceGenome.getSourceUrl())) { + getBigFileCache().removeFile(referenceGenome.getSourceUrl()); + } + for (ReferenceGenomeGeneMapping mapping : referenceGenome.getGeneMapping()) { + if (getBigFileCache().isCached(mapping.getSourceUrl())) { + getBigFileCache().removeFile(mapping.getSourceUrl()); + } + } + getReferenceGenomeDao().delete(referenceGenome); + } + } + } + + @Override + public String getGenomeVersionFile(MiriamData organism, String version) throws FileNotAvailableException { + String filename = super.getCacheValue( + FILENAME_BY_ORGANISM_VERSION_PREFIX + organism.getResource() + "\n" + version); + if (filename != null) { + return filename; + } + FTPClient ftp = createFtpClient(); + try { + ftp.connect(SERVER); + // After connection attempt, you should check the reply code to verify + // success. + int reply = ftp.getReplyCode(); + + if (!FTPReply.isPositiveCompletion(reply)) { + throw new FileNotAvailableException( + "Cannot find file with genome for: " + organism + "; " + version + ". FTP server refused connection."); + } else { + ftp.enterLocalPassiveMode(); + ftp.login("anonymous", ""); + ftp.setFileType(FTP.BINARY_FILE_TYPE); + + String remotePath = getGenomePath(organism, version); + FTPFile[] files = ftp.listFiles(remotePath); + for (FTPFile ftpFile : files) { + if (ftpFile.getName().endsWith(".2bit")) { + if (filename != null) { + logger.warn("More than one 2bit file found in a folder: " + remotePath + ". Using first: " + filename); + } else { + filename = ftpFile.getName(); + } + } + } + ftp.logout(); + } + } catch (IOException e) { + throw new FileNotAvailableException(e); + } finally { + if (ftp.isConnected()) { + try { + ftp.disconnect(); + } catch (IOException ioe) { + throw new FileNotAvailableException( + "Cannot find file with genome for: " + organism + "; " + version + ". Problem with ftp connection.", ioe); + } + } + } + if (filename == null) { + throw new FileNotAvailableException("Cannot find file with genome for: " + organism + "; " + version); + } + String result = "ftp://" + SERVER + getGenomePath(organism, version) + filename; + super.setCacheValue(FILENAME_BY_ORGANISM_VERSION_PREFIX + organism.getResource() + "\n" + version, result); + return result; + } + @Override public Object refreshCacheQuery(Object query) throws SourceNotAvailable { String result = null; @@ -212,22 +287,13 @@ public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnect } @Override - public void removeGenomeVersion(MiriamData organism, String version) throws IOException { - List<ReferenceGenome> genomes = getReferenceGenomeDao().getByType(ReferenceGenomeType.UCSC); - for (ReferenceGenome referenceGenome : genomes) { - if (referenceGenome.getOrganism().equals(organism) && referenceGenome.getVersion().equals(version)) { - // removing file from big file cache might not be the best idea here - if (getBigFileCache().isCached(referenceGenome.getSourceUrl())) { - getBigFileCache().removeFile(referenceGenome.getSourceUrl()); - } - for (ReferenceGenomeGeneMapping mapping : referenceGenome.getGeneMapping()) { - if (getBigFileCache().isCached(mapping.getSourceUrl())) { - getBigFileCache().removeFile(mapping.getSourceUrl()); - } - } - getReferenceGenomeDao().delete(referenceGenome); - } - } + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); } /** @@ -247,9 +313,66 @@ public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnect this.taxonomyBackend = taxonomyBackend; } + /** + * Returns local path on ftp server to folder with data about given organism and + * version. + * + * @param organism + * organism of reference genome + * @param version + * of reference genome + * @return local path on ftp server to folder with data about reference genome + */ + private String getGenomePath(MiriamData organism, String version) { + return "/goldenPath/" + version + "/bigZips/"; + } + + /** + * Creates new instance of {@link FTPClient}. + * + * @return new instance of {@link FTPClient} + */ + FTPClient createFtpClient() { + FTPClient ftp = new FTPClient(); + return ftp; + } + + /** + * Extracts int from the version of the genome. The genome version look like + * follow: xxxx011. + * + * @param s + * genome version where suffix part is integer number that informs + * about version + * @return {@link Integer} representing version of the genome from string that + * describes genome version (it contains also some letters characters} + */ + int extractInt(String s) { + int startIndex = 0; + int endIndex = s.length() - 2; + for (int i = 0; i < s.length(); i++) { + startIndex = i; + if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { + break; + } + } + for (int i = startIndex; i < s.length(); i++) { + if (s.charAt(i) < '0' || s.charAt(i) > '9') { + break; + } + endIndex = i; + } + endIndex++; + if (startIndex >= endIndex) { + return 0; + } else { + return Integer.parseInt(s.substring(startIndex, endIndex)); + } + } + /** * Task that will be able to fetch genome file from ftp server. - * + * * @author Piotr Gawron * */ @@ -257,13 +380,13 @@ public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnect /** * Url to the file that we want to download. - * + * */ private String url; /** * Callback listener that will receive information about upload progress. - * + * */ private IProgressUpdater updater; @@ -279,7 +402,7 @@ public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnect /** * Default constructor. - * + * * @param url * {@link #url} * @param updater @@ -339,138 +462,4 @@ public class UcscReferenceGenomeConnector extends AbstractReferenceGenomeConnect } - @Override - public void downloadGenomeVersion(MiriamData organism, String version, IProgressUpdater updater, boolean async, - String customUrl) throws IOException, URISyntaxException, ReferenceGenomeConnectorException { - Callable<Void> computations = new DownloadGenomeVersionTask(organism, version, customUrl, updater); - if (async) { - getAsyncExecutorService().submit(computations); - } else { - Future<Void> task = getSyncExecutorService().submit(computations); - executeTask(task); - } - } - - /** - * Returns local path on ftp server to folder with data about given organism and - * version. - * - * @param organism - * organism of reference genome - * @param version - * of reference genome - * @return local path on ftp server to folder with data about reference genome - */ - private String getGenomePath(MiriamData organism, String version) { - return "/goldenPath/" + version + "/bigZips/"; - } - - @Override - public String getGenomeVersionFile(MiriamData organism, String version) throws FileNotAvailableException { - String filename = super.getCacheValue( - FILENAME_BY_ORGANISM_VERSION_PREFIX + organism.getResource() + "\n" + version); - if (filename != null) { - return filename; - } - FTPClient ftp = createFtpClient(); - try { - ftp.connect(SERVER); - // After connection attempt, you should check the reply code to verify - // success. - int reply = ftp.getReplyCode(); - - if (!FTPReply.isPositiveCompletion(reply)) { - throw new FileNotAvailableException( - "Cannot find file with genome for: " + organism + "; " + version + ". FTP server refused connection."); - } else { - ftp.enterLocalPassiveMode(); - ftp.login("anonymous", ""); - ftp.setFileType(FTP.BINARY_FILE_TYPE); - - String remotePath = getGenomePath(organism, version); - FTPFile[] files = ftp.listFiles(remotePath); - for (FTPFile ftpFile : files) { - if (ftpFile.getName().endsWith(".2bit")) { - if (filename != null) { - logger.warn("More than one 2bit file found in a folder: " + remotePath + ". Using first: " + filename); - } else { - filename = ftpFile.getName(); - } - } - } - ftp.logout(); - } - } catch (IOException e) { - throw new FileNotAvailableException(e); - } finally { - if (ftp.isConnected()) { - try { - ftp.disconnect(); - } catch (IOException ioe) { - throw new FileNotAvailableException( - "Cannot find file with genome for: " + organism + "; " + version + ". Problem with ftp connection.", ioe); - } - } - } - if (filename == null) { - throw new FileNotAvailableException("Cannot find file with genome for: " + organism + "; " + version); - } - String result = "ftp://" + SERVER + getGenomePath(organism, version) + filename; - super.setCacheValue(FILENAME_BY_ORGANISM_VERSION_PREFIX + organism.getResource() + "\n" + version, result); - return result; - } - - /** - * Creates new instance of {@link FTPClient}. - * - * @return new instance of {@link FTPClient} - */ - FTPClient createFtpClient() { - FTPClient ftp = new FTPClient(); - return ftp; - } - - /** - * Extracts int from the version of the genome. The genome version look like - * follow: xxxx011. - * - * @param s - * genome version where suffix part is integer number that informs - * about version - * @return {@link Integer} representing version of the genome from string that - * describes genome version (it contains also some letters characters} - */ - int extractInt(String s) { - int startIndex = 0; - int endIndex = s.length() - 2; - for (int i = 0; i < s.length(); i++) { - startIndex = i; - if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { - break; - } - } - for (int i = startIndex; i < s.length(); i++) { - if (s.charAt(i) < '0' || s.charAt(i) > '9') { - break; - } - endIndex = i; - } - endIndex++; - if (startIndex >= endIndex) { - return 0; - } else { - return Integer.parseInt(s.substring(startIndex, endIndex)); - } - } - - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } - } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/package-info.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/package-info.java index 4ada42b53e..3a7a415d56 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/package-info.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/package-info.java @@ -3,4 +3,3 @@ * from different type of resources. */ package lcsb.mapviewer.annotation.services; - diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/AllAnnotationTests.java b/annotation/src/test/java/lcsb/mapviewer/annotation/AllAnnotationTests.java index 90e78c71dd..51cf2c586e 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/AllAnnotationTests.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/AllAnnotationTests.java @@ -1,17 +1,17 @@ package lcsb.mapviewer.annotation; -import lcsb.mapviewer.annotation.cache.AllCacheTests; -import lcsb.mapviewer.annotation.data.AllDataTests; -import lcsb.mapviewer.annotation.services.AllServicesTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.annotation.cache.AllCacheTests; +import lcsb.mapviewer.annotation.data.AllDataTests; +import lcsb.mapviewer.annotation.services.AllServicesTests; + @RunWith(Suite.class) @SuiteClasses({ AllCacheTests.class, - AllDataTests.class, - AllServicesTests.class, + AllDataTests.class, + AllServicesTests.class, }) public class AllAnnotationTests { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java index 85396c4660..f76fa0a60d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/AnnotationTestFunctions.java @@ -1,34 +1,17 @@ package lcsb.mapviewer.annotation; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.HttpURLConnection; import java.net.URL; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; +import java.util.*; + +import javax.xml.parsers.*; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.junit.*; import org.junit.runner.RunWith; @@ -37,14 +20,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import lcsb.mapviewer.annotation.cache.PermanentDatabaseLevelCacheInterface; - import lcsb.mapviewer.common.MinervaLoggerAppender; import lcsb.mapviewer.common.UnitTestFailedWatcher; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -59,20 +39,16 @@ import lcsb.mapviewer.persist.dao.cache.CacheTypeDao; @RunWith(SpringJUnit4ClassRunner.class) public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit4SpringContextTests { + private static Map<String, Model> models = new HashMap<String, Model>(); @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - @Autowired protected PermanentDatabaseLevelCacheInterface cache; - @Autowired protected CacheTypeDao cacheTypeDao; - @Autowired protected DbUtils dbUtils; - private Logger logger = LogManager.getLogger(AnnotationTestFunctions.class); - private MinervaLoggerAppender appender; @Before @@ -156,8 +132,6 @@ public abstract class AnnotationTestFunctions extends AbstractTransactionalJUnit return doc; } - private static Map<String, Model> models = new HashMap<String, Model>(); - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { if (!fromCache) { logger.debug("File without cache: " + fileName); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/SpringAnnotationTestConfig.java b/annotation/src/test/java/lcsb/mapviewer/annotation/SpringAnnotationTestConfig.java index e29d521622..447d16adc4 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/SpringAnnotationTestConfig.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/SpringAnnotationTestConfig.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.annotation; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.*; import lcsb.mapviewer.annotation.cache.MockCacheInterface; import lcsb.mapviewer.persist.SpringPersistConfig; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/AllCacheTests.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/AllCacheTests.java index 99707b056d..f1d84ab021 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/AllCacheTests.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/AllCacheTests.java @@ -6,13 +6,13 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ApplicationLevelCacheTest.class, - BigFileCacheTest.class, - CachableInterfaceTest.class, - GeneralCacheTest.class, - GeneralCacheWithExclusionTest.class, - PermanentDatabaseLevelCacheTest.class, - SourceNotAvailableTest.class, - WebPageDownloaderTest.class, + BigFileCacheTest.class, + CachableInterfaceTest.class, + GeneralCacheTest.class, + GeneralCacheWithExclusionTest.class, + PermanentDatabaseLevelCacheTest.class, + SourceNotAvailableTest.class, + WebPageDownloaderTest.class, }) public class AllCacheTests { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java index 0e0b7f5305..826e7498f1 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/BigFileCacheTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.cache; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; import java.io.*; import java.net.URISyntaxException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceMock.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceMock.java index f58f0a89cc..54d45f3f3b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceMock.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceMock.java @@ -2,13 +2,13 @@ package lcsb.mapviewer.annotation.cache; public class CachableInterfaceMock extends CachableInterface { - public CachableInterfaceMock(Class<? extends CachableInterface> clazz) { - super(clazz); - } - - @Override - public Object refreshCacheQuery(Object query) throws SourceNotAvailable { - return null; - } + public CachableInterfaceMock(Class<? extends CachableInterface> clazz) { + super(clazz); + } + + @Override + public Object refreshCacheQuery(Object query) throws SourceNotAvailable { + return null; + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java index eb6f03d3ed..fe5428d0d8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/CachableInterfaceTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.annotation.cache; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/MockCacheInterface.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/MockCacheInterface.java index 31d47d8a99..08d20c049c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/MockCacheInterface.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/MockCacheInterface.java @@ -9,25 +9,25 @@ package lcsb.mapviewer.annotation.cache; */ public final class MockCacheInterface extends CachableInterface { - public static RuntimeException exceptionToThrow = null; - public static Error errorToThrow; + public static RuntimeException exceptionToThrow = null; + public static Error errorToThrow; - /** - * Defsault constructor. - */ - public MockCacheInterface() { - super(MockCacheInterface.class); - } + /** + * Defsault constructor. + */ + public MockCacheInterface() { + super(MockCacheInterface.class); + } - @Override - public String refreshCacheQuery(Object query) throws SourceNotAvailable { - if (exceptionToThrow != null) { - throw exceptionToThrow; - } - if (errorToThrow != null) { - throw errorToThrow; - } - return "<node>[" + query + "] Random: " + Math.random() + "</node>"; - } + @Override + public String refreshCacheQuery(Object query) throws SourceNotAvailable { + if (exceptionToThrow != null) { + throw exceptionToThrow; + } + if (errorToThrow != null) { + throw errorToThrow; + } + return "<node>[" + query + "] Random: " + Math.random() + "</node>"; + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java index a20da355c6..580b5b5c7e 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/PermanentDatabaseLevelCacheTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.annotation.cache; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.util.Calendar; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/SourceNotAvailableTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/SourceNotAvailableTest.java index ac982ca9ff..bdd47bf8d9 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/SourceNotAvailableTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/SourceNotAvailableTest.java @@ -2,29 +2,26 @@ package lcsb.mapviewer.annotation.cache; import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class SourceNotAvailableTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor() { - Exception e = new SourceNotAvailable("meessage"); - assertTrue(e.getMessage().contains("meessage")); - } + @Test + public void testConstructor() { + Exception e = new SourceNotAvailable("meessage"); + assertTrue(e.getMessage().contains("meessage")); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java index ab41debd38..c1b09b568f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/cache/WebPageDownloaderTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.annotation.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.net.HttpURLConnection; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/AllDataTests.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/AllDataTests.java index b4a981f759..ccec50eb8b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/AllDataTests.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/AllDataTests.java @@ -6,18 +6,18 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ArticleCitationComparatorTest.class, - ArticleTest.class, - ChebiRelationTest.class, - ChebiTest.class, - ChemicalTest.class, - ChemicalDirectEvidenceTest.class, - DrugTest.class, - EntrezDataTest.class, - GoTest.class, - MeSHTest.class, - MiRNATest.class, - TargetTest.class, - TargetTypeTest.class, + ArticleTest.class, + ChebiRelationTest.class, + ChebiTest.class, + ChemicalTest.class, + ChemicalDirectEvidenceTest.class, + DrugTest.class, + EntrezDataTest.class, + GoTest.class, + MeSHTest.class, + MiRNATest.class, + TargetTest.class, + TargetTypeTest.class, }) public class AllDataTests { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleCitationComparatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleCitationComparatorTest.java index 7d12657ef9..dff11ad93e 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleCitationComparatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ArticleCitationComparatorTest.java @@ -5,43 +5,40 @@ import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ArticleCitationComparatorTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCompare() { - Article a1 = new Article(); - a1.setCitationCount(2); - Article a2 = new Article(); - a2.setCitationCount(10); - Article a3 = new Article(); - a3.setCitationCount(5); - List<Article> list = new ArrayList<>(); - list.add(a1); - list.add(a2); - list.add(a3); - - list.sort(new ArticleCitationComparator()); - - assertEquals(a2,list.get(0)); - assertEquals(a3,list.get(1)); - assertEquals(a1,list.get(2)); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testCompare() { + Article a1 = new Article(); + a1.setCitationCount(2); + Article a2 = new Article(); + a2.setCitationCount(10); + Article a3 = new Article(); + a3.setCitationCount(5); + List<Article> list = new ArrayList<>(); + list.add(a1); + list.add(a2); + list.add(a3); + + list.sort(new ArticleCitationComparator()); + + assertEquals(a2, list.get(0)); + assertEquals(a3, list.get(1)); + assertEquals(a1, list.get(2)); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java index 66427fec89..2cf2947c0b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChebiTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidenceTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidenceTest.java index 157d62127c..2065be34bf 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidenceTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalDirectEvidenceTest.java @@ -2,30 +2,27 @@ package lcsb.mapviewer.annotation.data; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ChemicalDirectEvidenceTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValues() { - for (ChemicalDirectEvidence value : ChemicalDirectEvidence.values()) { - assertNotNull(ChemicalDirectEvidence.valueOf(value.toString())); - } - } + @Test + public void testValues() { + for (ChemicalDirectEvidence value : ChemicalDirectEvidence.values()) { + assertNotNull(ChemicalDirectEvidence.valueOf(value.toString())); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalTest.java index b89bfb937a..01d006c6e0 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/ChemicalTest.java @@ -6,62 +6,59 @@ import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.MiriamData; public class ChemicalTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetters() { - List<Target> inferenceNetwork = new ArrayList<>(); - List<String> synonyms = new ArrayList<>(); - List<MiriamData> directEvidencePublication = new ArrayList<>(); - Chemical chemical = new Chemical(); - chemical.setInferenceNetwork(inferenceNetwork); - chemical.setDirectEvidencePublication(directEvidencePublication); - chemical.setSynonyms(synonyms); + @Test + public void testGetters() { + List<Target> inferenceNetwork = new ArrayList<>(); + List<String> synonyms = new ArrayList<>(); + List<MiriamData> directEvidencePublication = new ArrayList<>(); + Chemical chemical = new Chemical(); + chemical.setInferenceNetwork(inferenceNetwork); + chemical.setDirectEvidencePublication(directEvidencePublication); + chemical.setSynonyms(synonyms); - assertEquals(inferenceNetwork, chemical.getInferenceNetwork()); - assertEquals(directEvidencePublication, chemical.getDirectEvidencePublication()); - assertEquals(synonyms, chemical.getSynonyms()); - - } + assertEquals(inferenceNetwork, chemical.getInferenceNetwork()); + assertEquals(directEvidencePublication, chemical.getDirectEvidencePublication()); + assertEquals(synonyms, chemical.getSynonyms()); - @Test - public void testGetSynonymsString() { - Chemical chemical = new Chemical(); - assertEquals("", chemical.getSynonymsString()); - chemical.getSynonyms().add("12"); - assertEquals("12", chemical.getSynonymsString()); - chemical.getSynonyms().add("qwe"); - assertEquals("12,qwe", chemical.getSynonymsString()); - chemical.getSynonyms().add("zc"); - assertEquals("12,qwe,zc", chemical.getSynonymsString()); - } + } - @Test - public void testToString() { - - Chemical chemical = new Chemical(); - chemical.getInferenceNetwork().add(new Target()); - chemical.getDirectEvidencePublication().add(new MiriamData()); - assertNotNull(chemical.toString()); - } + @Test + public void testGetSynonymsString() { + Chemical chemical = new Chemical(); + assertEquals("", chemical.getSynonymsString()); + chemical.getSynonyms().add("12"); + assertEquals("12", chemical.getSynonymsString()); + chemical.getSynonyms().add("qwe"); + assertEquals("12,qwe", chemical.getSynonymsString()); + chemical.getSynonyms().add("zc"); + assertEquals("12,qwe,zc", chemical.getSynonymsString()); + } + + @Test + public void testToString() { + + Chemical chemical = new Chemical(); + chemical.getInferenceNetwork().add(new Target()); + chemical.getDirectEvidencePublication().add(new MiriamData()); + assertNotNull(chemical.toString()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/EntrezDataTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/EntrezDataTest.java index 8d51c5853d..45d8c54a64 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/EntrezDataTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/EntrezDataTest.java @@ -6,46 +6,43 @@ import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.MiriamData; public class EntrezDataTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - List<MiriamData> miriamData = new ArrayList<>(); - EntrezData entrez = new EntrezData(); - entrez.setMiriamData(miriamData); - assertEquals(miriamData, entrez.getMiriamData()); - } - - @Test - public void testAddMiriamData() { - EntrezData entrez = new EntrezData(); - entrez.addMiriamData(new MiriamData()); - assertEquals(1, entrez.getMiriamData().size()); - } - - @Test - public void testToString() { - EntrezData entrez = new EntrezData(); - assertNotNull(entrez.toString()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + List<MiriamData> miriamData = new ArrayList<>(); + EntrezData entrez = new EntrezData(); + entrez.setMiriamData(miriamData); + assertEquals(miriamData, entrez.getMiriamData()); + } + + @Test + public void testAddMiriamData() { + EntrezData entrez = new EntrezData(); + entrez.addMiriamData(new MiriamData()); + assertEquals(1, entrez.getMiriamData().size()); + } + + @Test + public void testToString() { + EntrezData entrez = new EntrezData(); + assertNotNull(entrez.toString()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java index 5a99ef7c1e..12ddc0ee56 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/MeSHTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/MiRNATest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/MiRNATest.java index bff4c92797..ebfbb2493a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/MiRNATest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/MiRNATest.java @@ -6,40 +6,37 @@ import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class MiRNATest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - List<Target> inferenceNetwork = new ArrayList<>(); - MiRNA mirna = new MiRNA(); - - mirna.setTargets(inferenceNetwork); - assertEquals(inferenceNetwork, mirna.getTargets()); - } - - @Test - public void testToString() { - MiRNA mirna = new MiRNA(); - mirna.addTarget(new Target()); - String str = mirna.toString(); - assertNotNull(str); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + List<Target> inferenceNetwork = new ArrayList<>(); + MiRNA mirna = new MiRNA(); + + mirna.setTargets(inferenceNetwork); + assertEquals(inferenceNetwork, mirna.getTargets()); + } + + @Test + public void testToString() { + MiRNA mirna = new MiRNA(); + mirna.addTarget(new Target()); + String str = mirna.toString(); + assertNotNull(str); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java index c1f4d752ac..9aa043d6e6 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.annotation.data; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTypeTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTypeTest.java index 5cd268ced9..14bd965ca9 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTypeTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/data/TargetTypeTest.java @@ -2,31 +2,28 @@ package lcsb.mapviewer.annotation.data; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class TargetTypeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testValues() { - for (TargetType type : TargetType.values()) { - assertNotNull(type.getCommonName()); - assertNotNull(TargetType.valueOf(type.toString())); - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testValues() { + for (TargetType type : TargetType.values()) { + assertNotNull(type.getCommonName()); + assertNotNull(TargetType.valueOf(type.toString())); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/AllServicesTests.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/AllServicesTests.java index 228a4b67c7..cde00bdf33 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/AllServicesTests.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/AllServicesTests.java @@ -1,32 +1,32 @@ package lcsb.mapviewer.annotation.services; -import lcsb.mapviewer.annotation.services.annotators.AllAnnotatorTests; -import lcsb.mapviewer.annotation.services.genome.AllGenomeTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.annotation.services.annotators.AllAnnotatorTests; +import lcsb.mapviewer.annotation.services.genome.AllGenomeTests; + @RunWith(Suite.class) @SuiteClasses({ AllAnnotatorTests.class, - AllGenomeTests.class, - ChEMBLParserTest.class, - ChemicalParserTest.class, - ChemicalSearchExceptionTest.class, - DrugAnnotationTest.class, - DrugbankHTMLParserTest.class, - ExternalServiceStatusTest.class, - ExternalServiceStatusTypeTest.class, - ImproperAnnotationsTest.class, - MeSHParserTest.class, - MiriamConnectorTest.class, - MiRNASearchExceptionTest.class, - MissingAnnotationTest.class, - MissingRequiredAnnotationsTest.class, - MiRNAParserTest.class, - ModelAnnotatorTest.class, - PubmedParserTest.class, - TaxonomyBackendTest.class, + AllGenomeTests.class, + ChEMBLParserTest.class, + ChemicalParserTest.class, + ChemicalSearchExceptionTest.class, + DrugAnnotationTest.class, + DrugbankHTMLParserTest.class, + ExternalServiceStatusTest.class, + ExternalServiceStatusTypeTest.class, + ImproperAnnotationsTest.class, + MeSHParserTest.class, + MiriamConnectorTest.class, + MiRNASearchExceptionTest.class, + MissingAnnotationTest.class, + MissingRequiredAnnotationsTest.class, + MiRNAParserTest.class, + ModelAnnotatorTest.class, + PubmedParserTest.class, + TaxonomyBackendTest.class, }) public class AllServicesTests { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java index ab6a62d96f..dfe8729b8f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChEMBLParserTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.*; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java index bb82811c85..01df6e958b 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalParserTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.*; @@ -28,11 +28,9 @@ import lcsb.mapviewer.model.map.model.Model; @Ignore("ctd decided to block us due to too many requests") public class ChemicalParserTest extends AnnotationTestFunctions { - Logger logger = LogManager.getLogger(ChemicalParserTest.class); - final MiriamData parkinsonDiseaseId = new MiriamData(MiriamType.MESH_2012, "D010300"); final MiriamData dystoniaDisease = new MiriamData(MiriamType.MESH_2012, "C538007"); - + Logger logger = LogManager.getLogger(ChemicalParserTest.class); MiriamData glutathioneDisulfideChemicalId = new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "D019803"); MiriamData stilbeneOxideChemicalId = new MiriamData(MiriamType.TOXICOGENOMIC_CHEMICAL, "C025906"); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalSearchExceptionTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalSearchExceptionTest.java index 48e93bd829..3c58cb2741 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalSearchExceptionTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ChemicalSearchExceptionTest.java @@ -1,30 +1,27 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ChemicalSearchExceptionTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor() { - ChemicalSearchException e = new ChemicalSearchException("msg"); - assertEquals("msg", e.getMessage()); - } + @Test + public void testConstructor() { + ChemicalSearchException e = new ChemicalSearchException("msg"); + assertEquals("msg", e.getMessage()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java index 3ba3717a96..3a1e5e52a8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugAnnotationTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Collection; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java index e5e204064e..21451bcdb8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/DrugbankHTMLParserTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTest.java index 7953bf1799..d8f7938bd8 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTest.java @@ -1,34 +1,31 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ExternalServiceStatusTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetters() { - String name = "b"; - String page = "page"; + @Test + public void testGetters() { + String name = "b"; + String page = "page"; - ExternalServiceStatus status = new ExternalServiceStatus(name, page); - assertEquals(name, status.getName()); - assertEquals(page, status.getPage()); - } + ExternalServiceStatus status = new ExternalServiceStatus(name, page); + assertEquals(name, status.getName()); + assertEquals(page, status.getPage()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTypeTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTypeTest.java index 1eb86e29c9..bb363bd747 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTypeTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ExternalServiceStatusTypeTest.java @@ -2,32 +2,29 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ExternalServiceStatusTypeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testValues() { - for (ExternalServiceStatusType type : ExternalServiceStatusType.values()) { - assertNotNull(type.getCommonName()); - assertNotNull(type.getLevel()); - assertNotNull(ExternalServiceStatusType.valueOf(type.toString())); - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testValues() { + for (ExternalServiceStatusType type : ExternalServiceStatusType.values()) { + assertNotNull(type.getCommonName()); + assertNotNull(type.getLevel()); + assertNotNull(ExternalServiceStatusType.valueOf(type.toString())); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java index b7316ecc36..6d21ec34b4 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/ImproperAnnotationsTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.annotation.services; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java index 2232a229ca..896b49de79 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MeSHParserTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.List; @@ -182,7 +183,7 @@ public class MeSHParserTest extends AnnotationTestFunctions { meshParser.refreshCacheQuery(query); } - @Test(expected=SourceNotAvailable.class) + @Test(expected = SourceNotAvailable.class) public void testRefreshWhenProblemWithSourceDb() throws Exception { WebPageDownloader downloader = meshParser.getWebPageDownloader(); GeneralCacheInterface cache = meshParser.getCache(); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java index ba35eb5f63..d6d84474f9 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNAParserTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; import java.util.*; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNASearchExceptionTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNASearchExceptionTest.java index 9e191033dc..8bcc30754a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNASearchExceptionTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiRNASearchExceptionTest.java @@ -5,35 +5,32 @@ import static org.junit.Assert.assertTrue; import java.io.IOException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class MiRNASearchExceptionTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor1() { - MiRNASearchException exception = new MiRNASearchException(new IOException()); - assertTrue(exception.getCause().getClass().equals(IOException.class)); - } - - @Test - public void testConstructor2() { - MiRNASearchException exception = new MiRNASearchException("xsd"); - assertEquals("xsd", exception.getMessage()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor1() { + MiRNASearchException exception = new MiRNASearchException(new IOException()); + assertTrue(exception.getCause().getClass().equals(IOException.class)); + } + + @Test + public void testConstructor2() { + MiRNASearchException exception = new MiRNASearchException("xsd"); + assertEquals("xsd", exception.getMessage()); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java index 7231d20416..ed031f64d7 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MiriamConnectorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.lang.reflect.Field; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java index 84490b1219..0978edf024 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingAnnotationTest.java @@ -2,31 +2,28 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.species.GenericProtein; public class MissingAnnotationTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void test() { - MissingAnnotation annotation = new MissingAnnotation(new GenericProtein("id")); - assertTrue(annotation.toString().contains("misses annotations")); - } + @Test + public void test() { + MissingAnnotation annotation = new MissingAnnotation(new GenericProtein("id")); + assertTrue(annotation.toString().contains("misses annotations")); + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java index 9b901b6e7b..0e901ee712 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/MissingRequiredAnnotationsTest.java @@ -5,10 +5,7 @@ import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamType; @@ -16,37 +13,37 @@ import lcsb.mapviewer.model.map.species.GenericProtein; public class MissingRequiredAnnotationsTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructorWithInvalidParams() { - try { - new MissingRequiredAnnotations(new GenericProtein("id"), new ArrayList<>()); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); - } - } - - @Test - public void testGetMessage() { - try { - List<MiriamType> list = new ArrayList<>(); - list.add(MiriamType.CAS); - MissingRequiredAnnotations mre = new MissingRequiredAnnotations(new GenericProtein("id"), list); - assertTrue(mre.toString().contains("misses one of the following annotations")); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructorWithInvalidParams() { + try { + new MissingRequiredAnnotations(new GenericProtein("id"), new ArrayList<>()); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); + } + } + + @Test + public void testGetMessage() { + try { + List<MiriamType> list = new ArrayList<>(); + list.add(MiriamType.CAS); + MissingRequiredAnnotations mre = new MissingRequiredAnnotations(new GenericProtein("id"), list); + assertTrue(mre.toString().contains("misses one of the following annotations")); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("List of improper annotations cannot be null")); + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java index 83aa54626c..bc984854dd 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/PubmedParserTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; @@ -22,18 +23,15 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; public class PubmedParserTest extends AnnotationTestFunctions { + @Autowired + protected PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCacheInterface; Logger logger = LogManager.getLogger(PubmedParserTest.class); - private boolean status2; - @Autowired PubmedParser pubmedParser; - + private boolean status2; @Autowired private GeneralCacheInterface cache; - @Autowired - protected PermanentDatabaseLevelCacheInterface permanentDatabaseLevelCacheInterface; - @Before public void setUp() throws Exception { status2 = Configuration.isApplicationCacheOn(); @@ -96,7 +94,8 @@ public class PubmedParserTest extends AnnotationTestFunctions { /** * This case was problematic with old API used to retrieve data from pubmed - * @throws PubmedSearchException + * + * @throws PubmedSearchException */ @Test public void testProblematicCase() throws PubmedSearchException { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java index 6c90220d69..d0b73d3eab 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/TaxonomyBackendTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/AnnotatorExceptionTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/AnnotatorExceptionTest.java index 29befabb84..9b3ff91e0c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/AnnotatorExceptionTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/AnnotatorExceptionTest.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class AnnotatorExceptionTest { diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java index 153d02adcc..fd3483f31f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotatorTest.java @@ -8,11 +8,9 @@ import static org.mockito.Mockito.when; import java.io.IOException; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java index feea977aa6..fe852a34f3 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/CazyAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java index 4af51cf203..19cbd5b90f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotatorTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorImplementationsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorImplementationsTest.java index 9fc4231272..41a17b548a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorImplementationsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorImplementationsTest.java @@ -4,11 +4,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -23,23 +22,19 @@ import lcsb.mapviewer.annotation.SpringAnnotationTestConfig; import lcsb.mapviewer.annotation.services.ModelAnnotator; import lcsb.mapviewer.annotation.services.annotators.ElementAnnotator.BioEntityProxy; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.SquareCompartment; import lcsb.mapviewer.model.map.reaction.type.TransportReaction; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.user.annotator.*; import lcsb.mapviewer.persist.DbUtils; @RunWith(Parameterized.class) public class ElementAnnotatorImplementationsTest extends AnnotationTestFunctions { + static ApplicationContext applicationContext; @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(ElementAnnotatorImplementationsTest.class); - @Parameter public String testName; @Parameter(1) @@ -49,8 +44,6 @@ public class ElementAnnotatorImplementationsTest extends AnnotationTestFunctions @Parameter(3) public BioEntity bioEntity; - static ApplicationContext applicationContext; - @Parameters(name = "{0}") public static Collection<Object[]> data() throws IOException { List<Object[]> result = new ArrayList<>(); @@ -126,7 +119,7 @@ public class ElementAnnotatorImplementationsTest extends AnnotationTestFunctions parameters.addAnnotatorParameter(parameter); } } - for (MiriamType type: MiriamType.values()) { + for (MiriamType type : MiriamType.values()) { AnnotatorOutputParameter parameter = new AnnotatorOutputParameter(type); if (!annotator.getAvailableOuputProperties().contains(parameter)) { parameters.addAnnotatorParameter(parameter); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java index c2b91fbff5..405f213e31 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ElementAnnotatorTest.java @@ -1,8 +1,10 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.Arrays; @@ -23,12 +25,11 @@ import lcsb.mapviewer.model.user.annotator.*; public class ElementAnnotatorTest extends AnnotationTestFunctions { + static AnnotatorData allOutputFieldsAndAnnotations = new AnnotatorData(Object.class); ElementAnnotator annotator = Mockito.mock(ElementAnnotator.class, Mockito.CALLS_REAL_METHODS); - @Autowired HgncAnnotator autowiredAnnotator; - static AnnotatorData allOutputFieldsAndAnnotations = new AnnotatorData(Object.class); { for (BioEntityField field : BioEntityField.values()) { allOutputFieldsAndAnnotations.addAnnotatorParameter(new AnnotatorOutputParameter(field)); diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java index 78a2dd104c..e511d41685 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EnsemblAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java index 819b0363c3..0029230e3d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/EntrezAnnotatorTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java index e907c37532..e441d8b257 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/GoAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java index a57e8f255c..42af972fe9 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/HgncAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.List; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java index 6609554d4c..cb535e502c 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/KeggAnnotatorTest.java @@ -1,8 +1,10 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.*; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java index e2b2294988..adf9801d94 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java index b73292ab9f..568f3583c5 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/PdbAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.util.Set; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java index 475f7d55ad..51d7680d4a 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/ReconAnnotatorTest.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java index 0ad50e1a8e..827f624a06 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StitchAnnotatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java index e39e0d2732..b3313bc2c3 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/StringAnnotatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java index d2d97a1103..0a123f4b7f 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/TairAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java index a85c04eceb..85e746031d 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.annotation.services.annotators; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.io.IOException; import java.util.Collection; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java index 6d5a6e730b..ce2fae9fa4 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/genome/UcscReferenceGenomeConnectorTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.annotation.services.genome; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URISyntaxException; diff --git a/commons/src/main/java/lcsb/mapviewer/common/Comparator.java b/commons/src/main/java/lcsb/mapviewer/common/Comparator.java index f1ac82c46a..7dd64a8a0a 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/Comparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/Comparator.java @@ -4,7 +4,7 @@ import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; diff --git a/commons/src/main/java/lcsb/mapviewer/common/Configuration.java b/commons/src/main/java/lcsb/mapviewer/common/Configuration.java index f4f5352500..36532d2444 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/Configuration.java +++ b/commons/src/main/java/lcsb/mapviewer/common/Configuration.java @@ -1,14 +1,11 @@ package lcsb.mapviewer.common; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; +import java.io.*; import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; /** * Basic configuration parameters of the system (these values cannot be modified @@ -20,24 +17,6 @@ import org.apache.logging.log4j.*; */ public final class Configuration { - /** - * Default value for {@link #memorySaturationRatioTriggerClean}. It defines at - * what memory usage level application should release cached objects (to prevent - * unnecessary out of memory exceptions). - * - */ - private static final double DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN = 0.9; - - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(Configuration.class); - - /** - * How many elements should be visible in auto-complete lists. - */ - private static final int DEFAULT_AUTOCOMPLETE_SIZE = 5; - /** * What is the minimal zoom level in the Google Maps API. It cannot be set to 0 * because Google Maps API was designed to visualize map of Earth which is based @@ -47,61 +26,65 @@ public final class Configuration { * be unaware of that fact. */ public static final int MIN_ZOOM_LEVEL = 2; - /** * This constant describes minimum size (in square pixels) of object visible * during nesting (it is a soft limit, can be override by depth of the depending * tree). */ public static final double MIN_VISIBLE_OBJECT_SIZE = 55000; - /** * This constant describes maximum size (in square pixels) of object visible * during nesting. */ public static final double MAX_VISIBLE_OBJECT_SIZE = 80000; - /** * Where the main web page is located. */ public static final String MAIN_PAGE = "/index.xhtml"; - /** * Name of the cookie for authentication token. */ public static final String AUTH_TOKEN = "MINERVA_AUTH_TOKEN"; - /** * Guest account. */ public static final String ANONYMOUS_LOGIN = "anonymous"; - + /** + * Epsilon used for different types of comparisons. + */ + public static final double EPSILON = 1e-6; + /** + * Default value for {@link #memorySaturationRatioTriggerClean}. It defines at + * what memory usage level application should release cached objects (to prevent + * unnecessary out of memory exceptions). + * + */ + private static final double DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN = 0.9; + /** + * How many elements should be visible in auto-complete lists. + */ + private static final int DEFAULT_AUTOCOMPLETE_SIZE = 5; + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(Configuration.class); /** * Max session length in seconds. */ private static int sessionLength = 60 * 120; - /** * Should the application cache be turned on. */ private static boolean applicationCacheOn = true; - /** * This constant defines at what memory usage level application should release * cached objects (to prevent unnecessary out of memory exceptions). */ private static Double memorySaturationRatioTriggerClean = DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN; - /** * What is the size of auto-complete elements. */ private static int autocompleteSize = DEFAULT_AUTOCOMPLETE_SIZE; - - /** - * Epsilon used for different types of comparisons. - */ - public static final double EPSILON = 1e-6; - /** * Git version from which framework was built. */ @@ -341,6 +324,13 @@ public final class Configuration { Configuration.xFrametDomain = xFrametDomains; } + /** + * @return the {@link #webAppDir} + */ + public static String getWebAppDir() { + return Configuration.webAppDir; + } + /** * @param path * the path to webapps to set @@ -350,13 +340,6 @@ public final class Configuration { Configuration.webAppDir = path; } - /** - * @return the {@link #webAppDir} - */ - public static String getWebAppDir() { - return Configuration.webAppDir; - } - /** * @return the memorySaturationRatioTriggerClean * @see #memorySaturationRatioTriggerClean diff --git a/commons/src/main/java/lcsb/mapviewer/common/FrameworkVersion.java b/commons/src/main/java/lcsb/mapviewer/common/FrameworkVersion.java index f59648ac18..00bff73803 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/FrameworkVersion.java +++ b/commons/src/main/java/lcsb/mapviewer/common/FrameworkVersion.java @@ -10,82 +10,82 @@ import java.io.Serializable; * */ public class FrameworkVersion implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Version of the framework. - */ - private String version; + /** + * Version of the framework. + */ + private String version; - /** - * When this version was committed to git. - */ - private String gitVersion; + /** + * When this version was committed to git. + */ + private String gitVersion; - /** - * When the framework was built. - */ - private String time; + /** + * When the framework was built. + */ + private String time; - /** - * Default constructor. - * - */ - public FrameworkVersion() { - } + /** + * Default constructor. + * + */ + public FrameworkVersion() { + } - /** - * @return the version - * @see #version - */ - public String getVersion() { - return version; - } + /** + * @return the version + * @see #version + */ + public String getVersion() { + return version; + } - /** - * @param version - * the version to set - * @see #version - */ - public void setVersion(String version) { - this.version = version; - } + /** + * @param version + * the version to set + * @see #version + */ + public void setVersion(String version) { + this.version = version; + } - /** - * @return the gitVersion - * @see #gitVersion - */ - public String getGitVersion() { - return gitVersion; - } + /** + * @return the gitVersion + * @see #gitVersion + */ + public String getGitVersion() { + return gitVersion; + } - /** - * @param gitVersion - * the gitVersion to set - * @see #gitVersion - */ - public void setGitVersion(String gitVersion) { - this.gitVersion = gitVersion; - } + /** + * @param gitVersion + * the gitVersion to set + * @see #gitVersion + */ + public void setGitVersion(String gitVersion) { + this.gitVersion = gitVersion; + } - /** - * @return the time - * @see #time - */ - public String getTime() { - return time; - } + /** + * @return the time + * @see #time + */ + public String getTime() { + return time; + } - /** - * @param time - * the time to set - * @see #time - */ - public void setTime(String time) { - this.time = time; - } + /** + * @param time + * the time to set + * @see #time + */ + public void setTime(String time) { + this.time = time; + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/IProgressUpdater.java b/commons/src/main/java/lcsb/mapviewer/common/IProgressUpdater.java index a74aa0557a..89ac9aef9f 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/IProgressUpdater.java +++ b/commons/src/main/java/lcsb/mapviewer/common/IProgressUpdater.java @@ -8,20 +8,20 @@ package lcsb.mapviewer.common; * */ public interface IProgressUpdater { - /** - * Maximum progress value. - */ - double MAX_PROGRESS = 100.0; - /** - * Defines the minimum progress value change that should be propagated. - */ - double PROGRESS_BAR_UPDATE_RESOLUTION = 0.5; + /** + * Maximum progress value. + */ + double MAX_PROGRESS = 100.0; + /** + * Defines the minimum progress value change that should be propagated. + */ + double PROGRESS_BAR_UPDATE_RESOLUTION = 0.5; - /** - * Set progress status. - * - * @param progress - * progress value (between 0 and 100) - */ - void setProgress(double progress); + /** + * Set progress status. + * + * @param progress + * progress value (between 0 and 100) + */ + void setProgress(double progress); } diff --git a/commons/src/main/java/lcsb/mapviewer/common/MinervaLoggerAppender.java b/commons/src/main/java/lcsb/mapviewer/common/MinervaLoggerAppender.java index 5fc9f78100..6cf1094c34 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/MinervaLoggerAppender.java +++ b/commons/src/main/java/lcsb/mapviewer/common/MinervaLoggerAppender.java @@ -5,10 +5,7 @@ import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.core.Filter; -import org.apache.logging.log4j.core.Layout; -import org.apache.logging.log4j.core.LogEvent; -import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.*; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.Property; import org.apache.logging.log4j.core.impl.MutableLogEvent; @@ -24,53 +21,45 @@ import org.apache.logging.log4j.core.layout.PatternLayout; */ public class MinervaLoggerAppender extends AbstractAppender { + /** + * Every logger must have different name. We use this counter to create new + * names. + */ + private static int loggerCounter = 0; /** * List of {@link LogLevel#DEBUG} logs. */ private List<LogEvent> debugEvents = new ArrayList<>(); - /** * List of {@link LogLevel#INFO} logs. */ private List<LogEvent> infoEvents = new ArrayList<>(); - /** * List of {@link LogLevel#WARN} logs. */ private List<LogEvent> warnEvents = new ArrayList<>(); - /** * List of {@link LogLevel#ERROR} logs. */ private List<LogEvent> errorEvents = new ArrayList<>(); - /** * List of {@link LogLevel#FATAL} logs. */ private List<LogEvent> fatalEvents = new ArrayList<>(); - /** * List of logs with unknown log level. */ private List<LogEvent> otherEvents = new ArrayList<>(); - /** * Identifier of {@link Thread} that created this object. */ private long threadId; - /** * Flag that describe if we log only entries for current thread ( * <code>true</code>) or for all threads (<code>false</code>). */ private boolean currentThreadLogOnly = true; - /** - * Every logger must have different name. We use this counter to create new - * names. - */ - private static int loggerCounter = 0; - /** * Private constructor preventing instantiation. Appender should be created * using factory method: {@link MinervaLoggerAppender#createAppender()}. diff --git a/commons/src/main/java/lcsb/mapviewer/common/ObjectUtils.java b/commons/src/main/java/lcsb/mapviewer/common/ObjectUtils.java index b5fd056b5e..5d18f1d867 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/ObjectUtils.java +++ b/commons/src/main/java/lcsb/mapviewer/common/ObjectUtils.java @@ -12,41 +12,41 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; */ public final class ObjectUtils { - /** - * Default constructor. Prevents instatiation. - */ - private ObjectUtils() { - } + /** + * Default constructor. Prevents instatiation. + */ + private ObjectUtils() { + } - /** - * Returns object identifier. It assumes that object contains getId method - * that returns Integer. - * - * @param object - * object for which identifier is looked for - * @return object identifier - */ - public static Integer getIdOfObject(Object object) { - Integer id = (Integer) getParamByGetter(object, "getId"); - return id; - } + /** + * Returns object identifier. It assumes that object contains getId method that + * returns Integer. + * + * @param object + * object for which identifier is looked for + * @return object identifier + */ + public static Integer getIdOfObject(Object object) { + Integer id = (Integer) getParamByGetter(object, "getId"); + return id; + } - /** - * Returns object param using string getter function. - * - * @param object - * object from which parameter will be taken - * @param getterName - * string with name of the getter function - * @return object field - */ - public static Object getParamByGetter(Object object, String getterName) { - try { - Method method = object.getClass().getMethod(getterName); - Object result = method.invoke(object); - return result; - } catch (Exception e) { - throw new InvalidArgumentException(e.getMessage()); - } - } + /** + * Returns object param using string getter function. + * + * @param object + * object from which parameter will be taken + * @param getterName + * string with name of the getter function + * @return object field + */ + public static Object getParamByGetter(Object object, String getterName) { + try { + Method method = object.getClass().getMethod(getterName); + Object result = method.invoke(object); + return result; + } catch (Exception e) { + throw new InvalidArgumentException(e.getMessage()); + } + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/Pair.java b/commons/src/main/java/lcsb/mapviewer/common/Pair.java index 32fb0263a8..0b486d1627 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/Pair.java +++ b/commons/src/main/java/lcsb/mapviewer/common/Pair.java @@ -15,70 +15,70 @@ import java.io.Serializable; */ public class Pair<L, R> implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * First object. - */ - private final L left; + /** + * First object. + */ + private final L left; - /** - * Second object. - */ - private final R right; + /** + * Second object. + */ + private final R right; - /** - * Default constructor. - * - * @param left - * {@link #left} - * @param right - * {@link #right} - */ - public Pair(L left, R right) { - this.left = left; - this.right = right; - } + /** + * Default constructor. + * + * @param left + * {@link #left} + * @param right + * {@link #right} + */ + public Pair(L left, R right) { + this.left = left; + this.right = right; + } - /** - * - * @return {@link #left} - */ - public L getLeft() { - return left; - } + /** + * + * @return {@link #left} + */ + public L getLeft() { + return left; + } - /** - * - * @return {@link #right} - */ - public R getRight() { - return right; - } + /** + * + * @return {@link #right} + */ + public R getRight() { + return right; + } - @Override - public int hashCode() { - return left.hashCode() ^ right.hashCode(); - } + @Override + public int hashCode() { + return left.hashCode() ^ right.hashCode(); + } - @Override - public boolean equals(Object o) { - if (o == null) { - return false; - } - if (!(o instanceof Pair)) { - return false; - } - Pair<?, ?> pairo = (Pair<?, ?>) o; - return this.left.equals(pairo.getLeft()) && this.right.equals(pairo.getRight()); - } + @Override + public boolean equals(Object o) { + if (o == null) { + return false; + } + if (!(o instanceof Pair)) { + return false; + } + Pair<?, ?> pairo = (Pair<?, ?>) o; + return this.left.equals(pairo.getLeft()) && this.right.equals(pairo.getRight()); + } - @Override - public String toString() { - return "Pair: " + getLeft().toString() + ", " + getRight().toString(); - } + @Override + public String toString() { + return "Pair: " + getLeft().toString() + ", " + getRight().toString(); + } } \ No newline at end of file diff --git a/commons/src/main/java/lcsb/mapviewer/common/SystemClipboard.java b/commons/src/main/java/lcsb/mapviewer/common/SystemClipboard.java index bfb7431ef6..c5a88f5298 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/SystemClipboard.java +++ b/commons/src/main/java/lcsb/mapviewer/common/SystemClipboard.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.common; -import java.awt.Toolkit; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.ClipboardOwner; -import java.awt.datatransfer.DataFlavor; -import java.awt.datatransfer.StringSelection; -import java.awt.datatransfer.Transferable; +import java.awt.*; +import java.awt.datatransfer.*; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; /** * Class allowing access to system clipboard. @@ -17,48 +13,48 @@ import org.apache.logging.log4j.*; * */ public class SystemClipboard implements ClipboardOwner { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(SystemClipboard.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(SystemClipboard.class); - @Override - public void lostOwnership(Clipboard clipboard, Transferable contents) { - } + @Override + public void lostOwnership(Clipboard clipboard, Transferable contents) { + } - /** - * Place a String on the clipboard, and make this class the owner of the - * Clipboard's contents. - * - * @param aString - * what we want to put into clipboard - */ - public void setClipboardContents(String aString) { - StringSelection stringSelection = new StringSelection(aString); - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.setContents(stringSelection, this); - } + /** + * Get the String residing on the clipboard. + * + * @return any text found on the Clipboard; if none found, return an empty + * String. + */ + public String getClipboardContents() { + String result = null; + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + // odd: the Object param of getContents is not currently used + Transferable contents = clipboard.getContents(null); + boolean hasTransferableText = contents.isDataFlavorSupported(DataFlavor.stringFlavor); + if (hasTransferableText) { + try { + result = (String) contents.getTransferData(DataFlavor.stringFlavor); + } catch (Exception ex) { + logger.error(ex, ex); + } + } + return result; + } - /** - * Get the String residing on the clipboard. - * - * @return any text found on the Clipboard; if none found, return an empty - * String. - */ - public String getClipboardContents() { - String result = null; - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - // odd: the Object param of getContents is not currently used - Transferable contents = clipboard.getContents(null); - boolean hasTransferableText = contents.isDataFlavorSupported(DataFlavor.stringFlavor); - if (hasTransferableText) { - try { - result = (String) contents.getTransferData(DataFlavor.stringFlavor); - } catch (Exception ex) { - logger.error(ex, ex); - } - } - return result; - } + /** + * Place a String on the clipboard, and make this class the owner of the + * Clipboard's contents. + * + * @param aString + * what we want to put into clipboard + */ + public void setClipboardContents(String aString) { + StringSelection stringSelection = new StringSelection(aString); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, this); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/TextFileUtils.java b/commons/src/main/java/lcsb/mapviewer/common/TextFileUtils.java index 3f0b8226e2..f0d5e24336 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/TextFileUtils.java +++ b/commons/src/main/java/lcsb/mapviewer/common/TextFileUtils.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.common; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.io.*; import java.util.HashMap; import java.util.Map; diff --git a/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java b/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java index 35e9b2821c..3309e00cac 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java +++ b/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java @@ -1,26 +1,12 @@ package lcsb.mapviewer.common; -import java.awt.Color; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.io.StringWriter; +import java.awt.*; +import java.io.*; import java.util.ArrayList; import java.util.List; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Templates; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; +import javax.xml.parsers.*; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; @@ -29,17 +15,12 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.commons.text.StringEscapeUtils; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; -import org.w3c.dom.Document; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; +import lcsb.mapviewer.common.exception.*; /** * Abstract class with methods which help in parsing xml using DOM. @@ -49,16 +30,14 @@ import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; */ final public class XmlParser { - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(XmlParser.class); - /** * Base of the hex representation. */ private static final int HEX_BASE = 16; - + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(XmlParser.class); /** * {@link DocumentBuilder} objects that will manipulate xml nodes. */ diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/BooleanComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/BooleanComparator.java index c7f3bd733c..fcd34e630b 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/BooleanComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/BooleanComparator.java @@ -10,18 +10,18 @@ import java.util.Comparator; */ public class BooleanComparator implements Comparator<Boolean> { - @Override - public int compare(Boolean arg0, Boolean arg1) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return 1; - } - } else if (arg1 == null) { - return -1; - } - return arg0.compareTo(arg1); - } + @Override + public int compare(Boolean arg0, Boolean arg1) { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return 1; + } + } else if (arg1 == null) { + return -1; + } + return arg0.compareTo(arg1); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/ColorComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/ColorComparator.java index efaf121466..a788fe958a 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/ColorComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/ColorComparator.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.common.comparator; -import java.awt.Color; +import java.awt.*; import java.util.Comparator; /** @@ -11,19 +11,19 @@ import java.util.Comparator; */ public class ColorComparator implements Comparator<Color> { - @Override - public int compare(Color arg0, Color arg1) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return 1; - } + @Override + public int compare(Color arg0, Color arg1) { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return 1; + } - } else if (arg1 == null) { - return -1; - } - return ((Integer) arg0.getRGB()).compareTo(arg1.getRGB()); - } + } else if (arg1 == null) { + return -1; + } + return ((Integer) arg0.getRGB()).compareTo(arg1.getRGB()); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/DoubleComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/DoubleComparator.java index a1320b5f13..d5ee693a0f 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/DoubleComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/DoubleComparator.java @@ -12,45 +12,45 @@ import lcsb.mapviewer.common.Configuration; */ public class DoubleComparator implements Comparator<Double> { - /** - * Epsilon value used for comparison of doubles. - */ - private double epsilon; - - /** - * Default constructor. - */ - public DoubleComparator() { - this(Configuration.EPSILON); - } - - /** - * Constructor that requires {@link #epsilon} parameter. - * - * @param epsilon - * {@link #epsilon} - */ - public DoubleComparator(double epsilon) { - this.epsilon = epsilon; - } - - @Override - public int compare(Double arg0, Double arg1) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return 1; - } - - } else if (arg1 == null) { - return -1; - } - if (Math.abs(arg0 - arg1) < epsilon) { - return 0; - } else { - return arg0.compareTo(arg1); - } - } + /** + * Epsilon value used for comparison of doubles. + */ + private double epsilon; + + /** + * Default constructor. + */ + public DoubleComparator() { + this(Configuration.EPSILON); + } + + /** + * Constructor that requires {@link #epsilon} parameter. + * + * @param epsilon + * {@link #epsilon} + */ + public DoubleComparator(double epsilon) { + this.epsilon = epsilon; + } + + @Override + public int compare(Double arg0, Double arg1) { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return 1; + } + + } else if (arg1 == null) { + return -1; + } + if (Math.abs(arg0 - arg1) < epsilon) { + return 0; + } else { + return arg0.compareTo(arg1); + } + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/EnumComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/EnumComparator.java index 55c899d983..fc596aec83 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/EnumComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/EnumComparator.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.common.comparator; -import java.awt.Color; +import java.awt.*; import java.util.Comparator; /** @@ -11,19 +11,19 @@ import java.util.Comparator; */ public class EnumComparator<E extends Enum<E>> implements Comparator<E> { - @Override - public int compare(E arg0, E arg1) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return 1; - } + @Override + public int compare(E arg0, E arg1) { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return 1; + } - } else if (arg1 == null) { - return -1; - } - return arg0.compareTo(arg1); - } + } else if (arg1 == null) { + return -1; + } + return arg0.compareTo(arg1); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/LineComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/LineComparator.java index 97fffceab0..f747b5bc06 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/LineComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/LineComparator.java @@ -4,7 +4,7 @@ import java.awt.geom.Line2D; import java.util.Comparator; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/ListComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/ListComparator.java index 485d1025eb..1ceb3d00a0 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/ListComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/ListComparator.java @@ -4,8 +4,7 @@ import java.util.Comparator; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; - +import org.apache.logging.log4j.Logger; /** * Comparator used for comparing lists of objects. diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/PointComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/PointComparator.java index 4283684288..7fd74e3cc3 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/PointComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/PointComparator.java @@ -13,46 +13,46 @@ import lcsb.mapviewer.common.Configuration; */ public class PointComparator implements Comparator<Point2D> { - /** - * Epsilon value used for comparison of doubles. - */ - private double epsilon; - - /** - * Constructor that requires {@link #epsilon} parameter. - * - * @param epsilon - * {@link #epsilon} - */ - public PointComparator(double epsilon) { - this.epsilon = epsilon; - } - - /** - * Default constructor. - */ - public PointComparator() { - this(Configuration.EPSILON); - } - - @Override - public int compare(Point2D arg0, Point2D arg1) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return 1; - } - - } else if (arg1 == null) { - return -1; - } - if (Math.abs(arg0.distance(arg1)) < epsilon) { - return 0; - } else { - // this could be modified to assure monotonousness of comparison - return -1; - } - } + /** + * Epsilon value used for comparison of doubles. + */ + private double epsilon; + + /** + * Constructor that requires {@link #epsilon} parameter. + * + * @param epsilon + * {@link #epsilon} + */ + public PointComparator(double epsilon) { + this.epsilon = epsilon; + } + + /** + * Default constructor. + */ + public PointComparator() { + this(Configuration.EPSILON); + } + + @Override + public int compare(Point2D arg0, Point2D arg1) { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return 1; + } + + } else if (arg1 == null) { + return -1; + } + if (Math.abs(arg0.distance(arg1)) < epsilon) { + return 0; + } else { + // this could be modified to assure monotonousness of comparison + return -1; + } + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/SetComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/SetComparator.java index 61fa44f4e0..3ad0a9e05b 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/SetComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/SetComparator.java @@ -4,8 +4,7 @@ import java.util.Comparator; import java.util.Set; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; - +import org.apache.logging.log4j.Logger; /** * Comparator used for comparing sets of strings. diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/StringComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/StringComparator.java index 900ebb7fea..737c4cde77 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/StringComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/StringComparator.java @@ -3,8 +3,7 @@ package lcsb.mapviewer.common.comparator; import java.util.Comparator; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; - +import org.apache.logging.log4j.Logger; /** * Comparator used for {@link String} class. It's null safe (it allows to @@ -14,45 +13,45 @@ import org.apache.logging.log4j.*; * */ public class StringComparator implements Comparator<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(StringComparator.class); - - @Override - public int compare(String arg0, String arg1) { - return compare(arg0, arg1, false); - } - - /** - * Allows to compare two strings ignoring whitespace difference. - * - * @param arg0 - * first string to compare - * @param arg1 - * second string to compare - * @param ignoreWhiteSpaceDifference - * should the difference in whitespace be ignored - * @return 0 when strings are identical, -1/1 when they are different - */ - public int compare(String arg0, String arg1, boolean ignoreWhiteSpaceDifference) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return 1; - } - } else if (arg1 == null) { - return -1; - } - - if (ignoreWhiteSpaceDifference) { - String str1 = arg0.replaceAll("[\n\r\t\\ ]+", "\n"); - String str2 = arg1.replaceAll("[\n\r\t\\ ]+", "\n"); - return str1.trim().compareTo(str2.trim()); - } - return arg0.trim().compareTo(arg1.trim()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(StringComparator.class); + + @Override + public int compare(String arg0, String arg1) { + return compare(arg0, arg1, false); + } + + /** + * Allows to compare two strings ignoring whitespace difference. + * + * @param arg0 + * first string to compare + * @param arg1 + * second string to compare + * @param ignoreWhiteSpaceDifference + * should the difference in whitespace be ignored + * @return 0 when strings are identical, -1/1 when they are different + */ + public int compare(String arg0, String arg1, boolean ignoreWhiteSpaceDifference) { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return 1; + } + } else if (arg1 == null) { + return -1; + } + + if (ignoreWhiteSpaceDifference) { + String str1 = arg0.replaceAll("[\n\r\t\\ ]+", "\n"); + String str2 = arg1.replaceAll("[\n\r\t\\ ]+", "\n"); + return str1.trim().compareTo(str2.trim()); + } + return arg0.trim().compareTo(arg1.trim()); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/StringListComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/StringListComparator.java index 0d9eac4d59..64e715cff2 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/StringListComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/StringListComparator.java @@ -4,7 +4,7 @@ import java.util.Comparator; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; /** * Comparator used for list of strings. diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/StringSetComparator.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/StringSetComparator.java index adbcd10916..39e6dcea24 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/StringSetComparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/StringSetComparator.java @@ -4,8 +4,7 @@ import java.util.Comparator; import java.util.Set; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; - +import org.apache.logging.log4j.Logger; /** * Comparator used for comparing sets of strings. diff --git a/commons/src/main/java/lcsb/mapviewer/common/comparator/package-info.java b/commons/src/main/java/lcsb/mapviewer/common/comparator/package-info.java index 7303e6069b..cb75259e62 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/comparator/package-info.java +++ b/commons/src/main/java/lcsb/mapviewer/common/comparator/package-info.java @@ -2,4 +2,3 @@ * Package with comparators for common classes. */ package lcsb.mapviewer.common.comparator; - diff --git a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidArgumentException.java b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidArgumentException.java index cc38a4c8f2..05cf420d4a 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidArgumentException.java +++ b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidArgumentException.java @@ -7,50 +7,50 @@ package lcsb.mapviewer.common.exception; * */ public class InvalidArgumentException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor - initializes instance variable to unknown. - */ - - public InvalidArgumentException() { - super(); // call superclass constructor - } - - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - - public InvalidArgumentException(final String e) { - super(e); - } - - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - public InvalidArgumentException(final Exception e) { - super(e); - } - - /** - * Public constructor with parent exception that was catched. - * - * @param message - * exception message - * @param e - * parent exception - */ - public InvalidArgumentException(final String message, final Exception e) { - super(message, e); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor - initializes instance variable to unknown. + */ + + public InvalidArgumentException() { + super(); // call superclass constructor + } + + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + + public InvalidArgumentException(final String e) { + super(e); + } + + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + public InvalidArgumentException(final Exception e) { + super(e); + } + + /** + * Public constructor with parent exception that was catched. + * + * @param message + * exception message + * @param e + * parent exception + */ + public InvalidArgumentException(final String message, final Exception e) { + super(message, e); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidClassException.java b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidClassException.java index c09f00529a..d6f5736b32 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidClassException.java +++ b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidClassException.java @@ -8,31 +8,30 @@ package lcsb.mapviewer.common.exception; */ public class InvalidClassException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public InvalidClassException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public InvalidClassException(String string) { + super(string); + } - /** - * Default constructor with message passed in the argument and super - * exception. - * - * @param string - * message of this exception - * @param e - * exception catched and passed to this object - */ - public InvalidClassException(String string, Exception e) { - super(string, e); - } + /** + * Default constructor with message passed in the argument and super exception. + * + * @param string + * message of this exception + * @param e + * exception catched and passed to this object + */ + public InvalidClassException(String string, Exception e) { + super(string, e); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidStateException.java b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidStateException.java index 6c1405dfba..0c14d73324 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidStateException.java +++ b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidStateException.java @@ -9,48 +9,48 @@ package lcsb.mapviewer.common.exception; */ public class InvalidStateException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - */ - public InvalidStateException() { - super(); - } + /** + * Default constructor. + */ + public InvalidStateException() { + super(); + } - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public InvalidStateException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public InvalidStateException(String string) { + super(string); + } - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - public InvalidStateException(Exception e) { - super(e); - } + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + public InvalidStateException(Exception e) { + super(e); + } - /** - * Public constructor with parent exception that was catched. - * - * @param string - * message of this exception - * @param e - * parent exception - */ - public InvalidStateException(String string, Exception e) { - super(string, e); - } + /** + * Public constructor with parent exception that was catched. + * + * @param string + * message of this exception + * @param e + * parent exception + */ + public InvalidStateException(String string, Exception e) { + super(string, e); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaException.java b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaException.java index 42194290a3..ba04b7b49a 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaException.java +++ b/commons/src/main/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaException.java @@ -7,50 +7,50 @@ package lcsb.mapviewer.common.exception; * */ public class InvalidXmlSchemaException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor - initializes instance variable to unknown. - */ - - public InvalidXmlSchemaException() { - super(); // call superclass constructor - } - - /** - * Constructor receives some kind of message. - * - * @param err - * message associated with exception - */ - - public InvalidXmlSchemaException(final String err) { - super(err); - } - - /** - * Constructor receives some kind of message and parent exception. - * - * @param err - * message associated with exception - * @param throwable - * parent exception - */ - public InvalidXmlSchemaException(final String err, final Throwable throwable) { - super(err, throwable); - } - - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - - public InvalidXmlSchemaException(final Exception e) { - super(e); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor - initializes instance variable to unknown. + */ + + public InvalidXmlSchemaException() { + super(); // call superclass constructor + } + + /** + * Constructor receives some kind of message. + * + * @param err + * message associated with exception + */ + + public InvalidXmlSchemaException(final String err) { + super(err); + } + + /** + * Constructor receives some kind of message and parent exception. + * + * @param err + * message associated with exception + * @param throwable + * parent exception + */ + public InvalidXmlSchemaException(final String err, final Throwable throwable) { + super(err, throwable); + } + + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + + public InvalidXmlSchemaException(final Exception e) { + super(e); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/exception/NotImplementedException.java b/commons/src/main/java/lcsb/mapviewer/common/exception/NotImplementedException.java index 816128136c..fe6a08252a 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/exception/NotImplementedException.java +++ b/commons/src/main/java/lcsb/mapviewer/common/exception/NotImplementedException.java @@ -10,26 +10,26 @@ package lcsb.mapviewer.common.exception; */ public class NotImplementedException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - */ - public NotImplementedException() { - super(); - } + /** + * Default constructor. + */ + public NotImplementedException() { + super(); + } - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public NotImplementedException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public NotImplementedException(String string) { + super(string); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/exception/package-info.java b/commons/src/main/java/lcsb/mapviewer/common/exception/package-info.java index fb2c61871f..f7cc179a8d 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/exception/package-info.java +++ b/commons/src/main/java/lcsb/mapviewer/common/exception/package-info.java @@ -2,4 +2,3 @@ * Common exceptions thrown by the system. */ package lcsb.mapviewer.common.exception; - diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/ColorParser.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/ColorParser.java index d9bc3ab0bb..52db39243a 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/ColorParser.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/ColorParser.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.common.geometry; -import java.awt.Color; +import java.awt.*; import java.util.HashMap; import java.util.Map; @@ -47,7 +47,7 @@ public class ColorParser { * @return {@link Color} obtained from input text */ public Color parse(String string) { - if (string==null || string.isEmpty()) { + if (string == null || string.isEmpty()) { throw new InvalidArgumentException( "Invalid color value: " + string + ". Correct format: #xxxxxx (where x is a hex value)"); } diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/CompositeStroke.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/CompositeStroke.java index df71302607..bdcd1bcd79 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/CompositeStroke.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/CompositeStroke.java @@ -1,7 +1,6 @@ package lcsb.mapviewer.common.geometry; -import java.awt.Shape; -import java.awt.Stroke; +import java.awt.*; /** * This class represent {@link Stroke} that consist of two nested {@link Stroke @@ -12,30 +11,32 @@ import java.awt.Stroke; * */ public class CompositeStroke implements Stroke { - - /** - * Outside stroke. - */ - private Stroke stroke1; - - /** - * Inside stroke used as a border of outside stroke. - */ - private Stroke stroke2; - /** - * DEfault constructor. - * - * @param stroke1 {@link #stroke1} - * @param stroke2 {@link #stroke2} - */ - public CompositeStroke(Stroke stroke1, Stroke stroke2) { - this.stroke1 = stroke1; - this.stroke2 = stroke2; - } + /** + * Outside stroke. + */ + private Stroke stroke1; - @Override - public Shape createStrokedShape(Shape shape) { - return stroke2.createStrokedShape(stroke1.createStrokedShape(shape)); - } + /** + * Inside stroke used as a border of outside stroke. + */ + private Stroke stroke2; + + /** + * DEfault constructor. + * + * @param stroke1 + * {@link #stroke1} + * @param stroke2 + * {@link #stroke2} + */ + public CompositeStroke(Stroke stroke1, Stroke stroke2) { + this.stroke1 = stroke1; + this.stroke2 = stroke2; + } + + @Override + public Shape createStrokedShape(Shape shape) { + return stroke2.createStrokedShape(stroke1.createStrokedShape(shape)); + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/EllipseTransformation.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/EllipseTransformation.java index e01a511c93..705f365f86 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/EllipseTransformation.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/EllipseTransformation.java @@ -4,11 +4,10 @@ import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; - /** * This class contains basic operators on ellipse used by converters. * diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/LineTransformation.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/LineTransformation.java index 232dc780a6..97ea610093 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/LineTransformation.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/LineTransformation.java @@ -1,11 +1,9 @@ package lcsb.mapviewer.common.geometry; -import java.awt.geom.Line2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/PointTransformation.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/PointTransformation.java index 45c960554c..fc550dd531 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/PointTransformation.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/PointTransformation.java @@ -80,8 +80,8 @@ public class PointTransformation { * @return {@link Point2D} on line defined by input points */ public Point2D getPointOnLine(Point2D start, Point2D end, double coef) { - double x = start.getX()+(end.getX()-start.getX())*coef; - double y = start.getY()+(end.getY()-start.getY())*coef; + double x = start.getX() + (end.getX() - start.getX()) * coef; + double y = start.getY() + (end.getY() - start.getY()) * coef; return new Point2D.Double(x, y); } diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/TextAlignment.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/TextAlignment.java index d4bfcdc62c..5094095e61 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/TextAlignment.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/TextAlignment.java @@ -8,18 +8,18 @@ package lcsb.mapviewer.common.geometry; */ public enum TextAlignment { - /** - * Text should be aligned to left. - */ - LEFT, + /** + * Text should be aligned to left. + */ + LEFT, - /** - * Text should be aligned to right. - */ - RIGHT, + /** + * Text should be aligned to right. + */ + RIGHT, - /** - * Text should be centered. - */ - CENTER; + /** + * Text should be centered. + */ + CENTER; } diff --git a/commons/src/main/java/lcsb/mapviewer/common/geometry/package-info.java b/commons/src/main/java/lcsb/mapviewer/common/geometry/package-info.java index 333ba68b32..c156b8180b 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/geometry/package-info.java +++ b/commons/src/main/java/lcsb/mapviewer/common/geometry/package-info.java @@ -9,4 +9,3 @@ * . */ package lcsb.mapviewer.common.geometry; - diff --git a/commons/src/main/java/lcsb/mapviewer/common/package-info.java b/commons/src/main/java/lcsb/mapviewer/common/package-info.java index fd4528e939..e02a29d4a6 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/package-info.java +++ b/commons/src/main/java/lcsb/mapviewer/common/package-info.java @@ -2,4 +2,3 @@ * Common objects for the whole project that aren't related to the project. */ package lcsb.mapviewer.common; - diff --git a/commons/src/test/java/lcsb/mapviewer/common/AllCommonTests.java b/commons/src/test/java/lcsb/mapviewer/common/AllCommonTests.java index 7c6b6fa400..b09bf968af 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/AllCommonTests.java +++ b/commons/src/test/java/lcsb/mapviewer/common/AllCommonTests.java @@ -10,16 +10,16 @@ import lcsb.mapviewer.common.geometry.AllGeometryTests; @RunWith(Suite.class) @SuiteClasses({ AllComparatorTests.class, - AllExceptionTests.class, - AllGeometryTests.class, - ConfigurationTest.class, - GlobalLoggerAppenderTest.class, - MimeTypeTest.class, - ObjectUtilsTest.class, - PairTest.class, - SystemClipboardTest.class, - TextFileUtilsTest.class, - XmlParserTest.class, + AllExceptionTests.class, + AllGeometryTests.class, + ConfigurationTest.class, + GlobalLoggerAppenderTest.class, + MimeTypeTest.class, + ObjectUtilsTest.class, + PairTest.class, + SystemClipboardTest.class, + TextFileUtilsTest.class, + XmlParserTest.class, }) public class AllCommonTests { diff --git a/commons/src/test/java/lcsb/mapviewer/common/ConfigurationTest.java b/commons/src/test/java/lcsb/mapviewer/common/ConfigurationTest.java index 55034269a6..b09dcf34b9 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/ConfigurationTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/ConfigurationTest.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.io.File; import java.lang.reflect.Constructor; @@ -10,117 +8,114 @@ import java.util.ArrayList; import java.util.List; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ConfigurationTest extends CommonTestFunctions{ - - Logger logger = LogManager.getLogger(ConfigurationTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - Configuration.setApplicationCacheOn(false); - assertFalse(Configuration.isApplicationCacheOn()); - Configuration.setAutocompleteSize(1); - assertEquals(1, Configuration.getAutocompleteSize()); - } - - @Test - public void testLoadSystemBuildVersion() { - Configuration.loadSystemVersion((String) null); - assertEquals("Unknown", Configuration.getSystemBuildVersion(null)); - assertEquals("Unknown", Configuration.getSystemBuild(null)); - assertEquals("Unknown", Configuration.getSystemVersion(null)); - } - - @Test - public void testLoadSystemBuildVersion2() { - Configuration.loadSystemVersion((String) null); - Configuration.loadSystemVersion(new File("unknown.xxx")); - assertEquals("Unknown", Configuration.getSystemBuildVersion(null)); - assertEquals("Unknown", Configuration.getSystemBuild(null)); - assertEquals("Unknown", Configuration.getSystemVersion(null)); - } - - @Test - public void testGetSystemBuildVersion() { - assertEquals("100", Configuration.getSystemBuildVersion("testFiles/version/", true)); - assertEquals("100", Configuration.getSystemBuildVersion(null, false)); - assertEquals("101", Configuration.getSystemVersion("testFiles/version/", true)); - } - - @Test - public void testGetSystemBuild() { - assertEquals("102", Configuration.getSystemBuild("testFiles/version/", true)); - assertEquals("102", Configuration.getSystemBuild(null, false)); - } - - @Test - public void testXGetSystemVersion() { - List<String> frame = new ArrayList<>(); - frame.add("test"); - Configuration.setxFrameDomain(frame); - assertEquals(frame, Configuration.getxFrameDomain()); - } - - @Test - public void testWebAppDir() { - String dir = "test2"; - Configuration.setWebAppDir(dir); - assertEquals(dir, Configuration.getWebAppDir()); - } - - - @Test - public void testLoadInvalidSystemBuildVersion() { - Configuration.loadSystemBuildVersion(new File("invalid_path")); - assertEquals(1, super.getErrors().size()); - } - - @Test - public void testLoadInvalidSystemVersion() { - Configuration.loadSystemVersion(new File("testFiles/version/INVALID_CHANGELOG")); - assertEquals(1, super.getErrors().size()); - } - - @Test - public void testGetFrameworkVersion() { - FrameworkVersion version = Configuration.getFrameworkVersion(null); - assertEquals("Unknown", version.getGitVersion()); - assertEquals("Unknown", version.getTime()); - assertEquals("Unknown", version.getVersion()); - } - - @Test - public void testGetMemorySaturationRatioTriggerClean() { - double newRatio = 33; - double oldRatio = Configuration.getMemorySaturationRatioTriggerClean(); - try { - Configuration.setMemorySaturationRatioTriggerClean(newRatio); - assertEquals(newRatio, Configuration.getMemorySaturationRatioTriggerClean(), Configuration.EPSILON); - } finally { - Configuration.setMemorySaturationRatioTriggerClean(oldRatio); - } - } - - @Test - public void testPrivateConstructor() throws Exception { - try { - Constructor<?> constr = Configuration.class.getDeclaredConstructor(new Class<?>[] {}); - constr.setAccessible(true); - assertNotNull(constr.newInstance(new Object[] {})); - } catch (Exception e) { - throw e; - } - } +import org.apache.logging.log4j.Logger; +import org.junit.*; + +public class ConfigurationTest extends CommonTestFunctions { + + Logger logger = LogManager.getLogger(ConfigurationTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + Configuration.setApplicationCacheOn(false); + assertFalse(Configuration.isApplicationCacheOn()); + Configuration.setAutocompleteSize(1); + assertEquals(1, Configuration.getAutocompleteSize()); + } + + @Test + public void testLoadSystemBuildVersion() { + Configuration.loadSystemVersion((String) null); + assertEquals("Unknown", Configuration.getSystemBuildVersion(null)); + assertEquals("Unknown", Configuration.getSystemBuild(null)); + assertEquals("Unknown", Configuration.getSystemVersion(null)); + } + + @Test + public void testLoadSystemBuildVersion2() { + Configuration.loadSystemVersion((String) null); + Configuration.loadSystemVersion(new File("unknown.xxx")); + assertEquals("Unknown", Configuration.getSystemBuildVersion(null)); + assertEquals("Unknown", Configuration.getSystemBuild(null)); + assertEquals("Unknown", Configuration.getSystemVersion(null)); + } + + @Test + public void testGetSystemBuildVersion() { + assertEquals("100", Configuration.getSystemBuildVersion("testFiles/version/", true)); + assertEquals("100", Configuration.getSystemBuildVersion(null, false)); + assertEquals("101", Configuration.getSystemVersion("testFiles/version/", true)); + } + + @Test + public void testGetSystemBuild() { + assertEquals("102", Configuration.getSystemBuild("testFiles/version/", true)); + assertEquals("102", Configuration.getSystemBuild(null, false)); + } + + @Test + public void testXGetSystemVersion() { + List<String> frame = new ArrayList<>(); + frame.add("test"); + Configuration.setxFrameDomain(frame); + assertEquals(frame, Configuration.getxFrameDomain()); + } + + @Test + public void testWebAppDir() { + String dir = "test2"; + Configuration.setWebAppDir(dir); + assertEquals(dir, Configuration.getWebAppDir()); + } + + @Test + public void testLoadInvalidSystemBuildVersion() { + Configuration.loadSystemBuildVersion(new File("invalid_path")); + assertEquals(1, super.getErrors().size()); + } + + @Test + public void testLoadInvalidSystemVersion() { + Configuration.loadSystemVersion(new File("testFiles/version/INVALID_CHANGELOG")); + assertEquals(1, super.getErrors().size()); + } + + @Test + public void testGetFrameworkVersion() { + FrameworkVersion version = Configuration.getFrameworkVersion(null); + assertEquals("Unknown", version.getGitVersion()); + assertEquals("Unknown", version.getTime()); + assertEquals("Unknown", version.getVersion()); + } + + @Test + public void testGetMemorySaturationRatioTriggerClean() { + double newRatio = 33; + double oldRatio = Configuration.getMemorySaturationRatioTriggerClean(); + try { + Configuration.setMemorySaturationRatioTriggerClean(newRatio); + assertEquals(newRatio, Configuration.getMemorySaturationRatioTriggerClean(), Configuration.EPSILON); + } finally { + Configuration.setMemorySaturationRatioTriggerClean(oldRatio); + } + } + + @Test + public void testPrivateConstructor() throws Exception { + try { + Constructor<?> constr = Configuration.class.getDeclaredConstructor(new Class<?>[] {}); + constr.setAccessible(true); + assertNotNull(constr.newInstance(new Object[] {})); + } catch (Exception e) { + throw e; + } + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java b/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java index d96a0f6883..dbc65e319e 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/GlobalLoggerAppenderTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/commons/src/test/java/lcsb/mapviewer/common/MimeTypeTest.java b/commons/src/test/java/lcsb/mapviewer/common/MimeTypeTest.java index 50189c2ae3..49af59112d 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/MimeTypeTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/MimeTypeTest.java @@ -3,30 +3,28 @@ package lcsb.mapviewer.common; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class MimeTypeTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testValidValues() { - for (MimeType type : MimeType.values()) { - assertNotNull(type); - assertNotNull(type.getTextRepresentation()); - assertFalse(type.getTextRepresentation().isEmpty()); - - //for coverage tests - MimeType.valueOf(type.toString()); - } - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testValidValues() { + for (MimeType type : MimeType.values()) { + assertNotNull(type); + assertNotNull(type.getTextRepresentation()); + assertFalse(type.getTextRepresentation().isEmpty()); + + // for coverage tests + MimeType.valueOf(type.toString()); + } + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java b/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java index 7cf9e2ff1a..55d750b9a8 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/ObjectUtilsTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.lang.reflect.Constructor; diff --git a/commons/src/test/java/lcsb/mapviewer/common/PairTest.java b/commons/src/test/java/lcsb/mapviewer/common/PairTest.java index 33178d5e6a..eeceb237b1 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/PairTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/PairTest.java @@ -1,70 +1,66 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class PairTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor() { - Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); - assertEquals("test str", pair.getLeft()); - assertEquals((Integer) 12, pair.getRight()); - } + @Test + public void testConstructor() { + Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); + assertEquals("test str", pair.getLeft()); + assertEquals((Integer) 12, pair.getRight()); + } - @Test - public void testEquals() { - Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); - Pair<String, Integer> pair2 = new Pair<String, Integer>("test str", 12); - Pair<String, String> pair3 = new Pair<String, String>("test str", "str"); - Pair<String, Integer> pair4 = new Pair<String, Integer>("test str", 124); - Pair<String, Integer> pair5 = new Pair<String, Integer>("test str1", 12); - assertTrue(pair.equals(pair2)); - assertFalse(pair.equals(pair3)); - assertFalse(pair.equals(pair4)); - assertFalse(pair.equals(pair5)); + @Test + public void testEquals() { + Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); + Pair<String, Integer> pair2 = new Pair<String, Integer>("test str", 12); + Pair<String, String> pair3 = new Pair<String, String>("test str", "str"); + Pair<String, Integer> pair4 = new Pair<String, Integer>("test str", 124); + Pair<String, Integer> pair5 = new Pair<String, Integer>("test str1", 12); + assertTrue(pair.equals(pair2)); + assertFalse(pair.equals(pair3)); + assertFalse(pair.equals(pair4)); + assertFalse(pair.equals(pair5)); - assertTrue(pair2.equals(pair)); - assertFalse(pair3.equals(pair)); - assertFalse(pair4.equals(pair)); - assertFalse(pair5.equals(pair)); - assertFalse(pair4.equals(new Object())); - } + assertTrue(pair2.equals(pair)); + assertFalse(pair3.equals(pair)); + assertFalse(pair4.equals(pair)); + assertFalse(pair5.equals(pair)); + assertFalse(pair4.equals(new Object())); + } - @Test - public void testHashCode() { - Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); - Pair<String, Integer> pair2 = new Pair<String, Integer>("test str", 12); - Pair<String, Integer> pair3 = new Pair<String, Integer>("test str", 124); - assertEquals(pair.hashCode(), pair2.hashCode()); - assertTrue(pair.hashCode() != pair3.hashCode()); - } + @Test + public void testHashCode() { + Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); + Pair<String, Integer> pair2 = new Pair<String, Integer>("test str", 12); + Pair<String, Integer> pair3 = new Pair<String, Integer>("test str", 124); + assertEquals(pair.hashCode(), pair2.hashCode()); + assertTrue(pair.hashCode() != pair3.hashCode()); + } - @Test - public void testNullEquals() { - Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); - Pair<String, Integer> pair2 = null; - assertFalse(pair.equals(pair2)); - } + @Test + public void testNullEquals() { + Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); + Pair<String, Integer> pair2 = null; + assertFalse(pair.equals(pair2)); + } - @Test - public void testToString() { - Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); - assertTrue(pair.toString().contains(pair.getLeft().toString())); - assertTrue(pair.toString().contains(pair.getRight().toString())); - } + @Test + public void testToString() { + Pair<String, Integer> pair = new Pair<String, Integer>("test str", 12); + assertTrue(pair.toString().contains(pair.getLeft().toString())); + assertTrue(pair.toString().contains(pair.getRight().toString())); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java b/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java index 938661d59e..2e0372a475 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/SystemClipboardTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.common; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; -import java.awt.Toolkit; +import java.awt.*; import java.awt.datatransfer.*; import java.io.IOException; @@ -38,13 +39,13 @@ public class SystemClipboardTest extends CommonTestFunctions { clipboard.setContents(new Transferable() { @Override - public boolean isDataFlavorSupported(DataFlavor flavor) { - return true; + public DataFlavor[] getTransferDataFlavors() { + return null; } @Override - public DataFlavor[] getTransferDataFlavors() { - return null; + public boolean isDataFlavorSupported(DataFlavor flavor) { + return true; } @Override diff --git a/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java b/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java index fbaed58e78..6773a4fd1f 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/XmlParserTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.common; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.List; @@ -20,6 +20,7 @@ import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; public class XmlParserTest extends CommonTestFunctions { Logger logger = LogManager.getLogger(XmlParserTest.class); + boolean threadSucceded; @Before public void setUp() throws Exception { @@ -98,8 +99,6 @@ public class XmlParserTest extends CommonTestFunctions { assertTrue(str.contains(xml)); } - boolean threadSucceded; - @Test public void testConcurrencyParse() throws Exception { StringBuilder builder = new StringBuilder("<doc>"); diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/BooleanComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/BooleanComparatorTest.java index d8329fcc9c..5391935129 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/BooleanComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/BooleanComparatorTest.java @@ -1,36 +1,35 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class BooleanComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNotNullComparison() { - BooleanComparator comp = new BooleanComparator(); - assertTrue(comp.compare(new Boolean(true), new Boolean(true)) == 0); - assertTrue(comp.compare(new Boolean(false), new Boolean(false)) == 0); - assertFalse(comp.compare(new Boolean(false), new Boolean(true)) == 0); - assertFalse(comp.compare(new Boolean(true), new Boolean(false)) == 0); - } - - @Test - public void testNullComparison() { - BooleanComparator comp = new BooleanComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(new Boolean(false), null) == 0); - assertFalse(comp.compare(null, new Boolean(false)) == 0); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparison() { + BooleanComparator comp = new BooleanComparator(); + assertTrue(comp.compare(new Boolean(true), new Boolean(true)) == 0); + assertTrue(comp.compare(new Boolean(false), new Boolean(false)) == 0); + assertFalse(comp.compare(new Boolean(false), new Boolean(true)) == 0); + assertFalse(comp.compare(new Boolean(true), new Boolean(false)) == 0); + } + + @Test + public void testNullComparison() { + BooleanComparator comp = new BooleanComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(new Boolean(false), null) == 0); + assertFalse(comp.compare(null, new Boolean(false)) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/ColorComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/ColorComparatorTest.java index febdaff65a..8bb20493c9 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/ColorComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/ColorComparatorTest.java @@ -1,38 +1,37 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ColorComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNotNullComparison() { - ColorComparator comp = new ColorComparator(); - assertTrue(comp.compare(Color.BLACK, Color.BLACK) == 0); - assertTrue(comp.compare(Color.RED, Color.RED) == 0); - assertFalse(comp.compare(Color.RED, Color.BLACK) == 0); - assertFalse(comp.compare(Color.BLACK, Color.RED) == 0); - } - - @Test - public void testNullComparison() { - ColorComparator comp = new ColorComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(Color.RED, null) == 0); - assertFalse(comp.compare(null, Color.RED) == 0); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparison() { + ColorComparator comp = new ColorComparator(); + assertTrue(comp.compare(Color.BLACK, Color.BLACK) == 0); + assertTrue(comp.compare(Color.RED, Color.RED) == 0); + assertFalse(comp.compare(Color.RED, Color.BLACK) == 0); + assertFalse(comp.compare(Color.BLACK, Color.RED) == 0); + } + + @Test + public void testNullComparison() { + ColorComparator comp = new ColorComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(Color.RED, null) == 0); + assertFalse(comp.compare(null, Color.RED) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/DoubleComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/DoubleComparatorTest.java index 91243e054d..3a647d5c6f 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/DoubleComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/DoubleComparatorTest.java @@ -1,44 +1,43 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class DoubleComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNotNullComparison() { - DoubleComparator comp = new DoubleComparator(); - assertTrue(comp.compare(new Double(5.01), new Double(5.01)) == 0); - assertTrue(comp.compare(new Double(2.73), new Double(2.73)) == 0); - assertFalse(comp.compare(new Double(2.73), new Double(5.01)) == 0); - assertFalse(comp.compare(new Double(5.01), new Double(2.73)) == 0); - } - - @Test - public void testEpsilonComp() { - DoubleComparator comp = new DoubleComparator(10); - assertTrue(comp.compare(new Double(5.01), new Double(1.01)) == 0); - assertFalse(comp.compare(new Double(2.73), new Double(-105.01)) == 0); - assertTrue(comp.compare(new Double(5.01), new Double(-2.73)) == 0); - } - - @Test - public void testNullComparison() { - DoubleComparator comp = new DoubleComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(new Double(2.73), null) == 0); - assertFalse(comp.compare(null, new Double(2.73)) == 0); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparison() { + DoubleComparator comp = new DoubleComparator(); + assertTrue(comp.compare(new Double(5.01), new Double(5.01)) == 0); + assertTrue(comp.compare(new Double(2.73), new Double(2.73)) == 0); + assertFalse(comp.compare(new Double(2.73), new Double(5.01)) == 0); + assertFalse(comp.compare(new Double(5.01), new Double(2.73)) == 0); + } + + @Test + public void testEpsilonComp() { + DoubleComparator comp = new DoubleComparator(10); + assertTrue(comp.compare(new Double(5.01), new Double(1.01)) == 0); + assertFalse(comp.compare(new Double(2.73), new Double(-105.01)) == 0); + assertTrue(comp.compare(new Double(5.01), new Double(-2.73)) == 0); + } + + @Test + public void testNullComparison() { + DoubleComparator comp = new DoubleComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(new Double(2.73), null) == 0); + assertFalse(comp.compare(null, new Double(2.73)) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/IntegerComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/IntegerComparatorTest.java index 65b7ab4653..5406cfad4d 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/IntegerComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/IntegerComparatorTest.java @@ -1,35 +1,34 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class IntegerComparatorTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testNotNullComparison() { - IntegerComparator comp = new IntegerComparator(); - assertTrue(comp.compare(new Integer(13), new Integer(13)) == 0); - assertTrue(comp.compare(new Integer(-59), new Integer(-59)) == 0); - assertFalse(comp.compare(new Integer(-59), new Integer(13)) == 0); - assertFalse(comp.compare(new Integer(13), new Integer(-59)) == 0); - } + @Test + public void testNotNullComparison() { + IntegerComparator comp = new IntegerComparator(); + assertTrue(comp.compare(new Integer(13), new Integer(13)) == 0); + assertTrue(comp.compare(new Integer(-59), new Integer(-59)) == 0); + assertFalse(comp.compare(new Integer(-59), new Integer(13)) == 0); + assertFalse(comp.compare(new Integer(13), new Integer(-59)) == 0); + } - @Test - public void testNullComparison() { - IntegerComparator comp = new IntegerComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(new Integer(-59), null) == 0); - assertFalse(comp.compare(null, new Integer(-59)) == 0); - } + @Test + public void testNullComparison() { + IntegerComparator comp = new IntegerComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(new Integer(-59), null) == 0); + assertFalse(comp.compare(null, new Integer(-59)) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/LineComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/LineComparatorTest.java index d776645605..e2e2d145f5 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/LineComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/LineComparatorTest.java @@ -6,17 +6,14 @@ import static org.junit.Assert.assertTrue; import java.awt.geom.Line2D; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class LineComparatorTest { - + Point2D p1 = new Point2D.Double(106, 5.01); Point2D p1close = new Point2D.Double(106, 5.11); Point2D p2 = new Point2D.Double(106, 2.73); Point2D p2far = new Point2D.Double(106, 202.73); - @Before public void setUp() throws Exception { diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/ListComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/ListComparatorTest.java index b7e6912654..9cd9736ba0 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/ListComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/ListComparatorTest.java @@ -3,9 +3,8 @@ package lcsb.mapviewer.common.comparator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import java.awt.Color; -import java.util.ArrayList; -import java.util.Comparator; +import java.awt.*; +import java.util.*; import java.util.List; import org.junit.Test; diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/PointComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/PointComparatorTest.java index 0d2097325e..49910828c9 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/PointComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/PointComparatorTest.java @@ -5,43 +5,41 @@ import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class PointComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNotNullComparison() { - PointComparator comp = new PointComparator(); - assertTrue(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, 5.01)) == 0); - assertTrue(comp.compare(new Point2D.Double(106, 2.73), new Point2D.Double(106, 2.73)) == 0); - assertFalse(comp.compare(new Point2D.Double(106, 2.73), new Point2D.Double(106, 5.01)) == 0); - assertFalse(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, 2.73)) == 0); - } - - @Test - public void testEpsilonComp() { - PointComparator comp = new PointComparator(10); - assertTrue(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, 1.01)) == 0); - assertFalse(comp.compare(new Point2D.Double(106, 2.73), new Point2D.Double(106, -105.01)) == 0); - assertTrue(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, -2.73)) == 0); - } - - @Test - public void testNullComparison() { - PointComparator comp = new PointComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(new Point2D.Double(106, 2.73), null) == 0); - assertFalse(comp.compare(null, new Point2D.Double(106, 2.73)) == 0); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparison() { + PointComparator comp = new PointComparator(); + assertTrue(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, 5.01)) == 0); + assertTrue(comp.compare(new Point2D.Double(106, 2.73), new Point2D.Double(106, 2.73)) == 0); + assertFalse(comp.compare(new Point2D.Double(106, 2.73), new Point2D.Double(106, 5.01)) == 0); + assertFalse(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, 2.73)) == 0); + } + + @Test + public void testEpsilonComp() { + PointComparator comp = new PointComparator(10); + assertTrue(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, 1.01)) == 0); + assertFalse(comp.compare(new Point2D.Double(106, 2.73), new Point2D.Double(106, -105.01)) == 0); + assertTrue(comp.compare(new Point2D.Double(106, 5.01), new Point2D.Double(106, -2.73)) == 0); + } + + @Test + public void testNullComparison() { + PointComparator comp = new PointComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(new Point2D.Double(106, 2.73), null) == 0); + assertFalse(comp.compare(null, new Point2D.Double(106, 2.73)) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/SetComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/SetComparatorTest.java index 4060b46bd6..59e01e39ea 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/SetComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/SetComparatorTest.java @@ -1,11 +1,10 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; +import java.awt.*; +import java.util.*; import org.junit.Test; diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/StringComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/StringComparatorTest.java index 88b635ee56..665eb30672 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/StringComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/StringComparatorTest.java @@ -1,44 +1,43 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class StringComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNotNullComparison() { - StringComparator comp = new StringComparator(); - assertTrue(comp.compare("test1", "test1") == 0); - assertTrue(comp.compare("xxx3", "xxx3") == 0); - assertFalse(comp.compare("xxx3", "test1") == 0); - assertFalse(comp.compare("test1", "xxx3") == 0); - } - - @Test - public void testComparisonWithoutWhitespace() { - StringComparator comp = new StringComparator(); - assertTrue(comp.compare("test1 32", "test1 32",true) == 0); - assertTrue(comp.compare("test1\t32", "test1 \n32",true) == 0); - assertFalse(comp.compare("test132", "test1 32",true) == 0); - } - - @Test - public void testNullComparison() { - StringComparator comp = new StringComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare("xxx3", null) == 0); - assertFalse(comp.compare(null, "xxx3") == 0); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparison() { + StringComparator comp = new StringComparator(); + assertTrue(comp.compare("test1", "test1") == 0); + assertTrue(comp.compare("xxx3", "xxx3") == 0); + assertFalse(comp.compare("xxx3", "test1") == 0); + assertFalse(comp.compare("test1", "xxx3") == 0); + } + + @Test + public void testComparisonWithoutWhitespace() { + StringComparator comp = new StringComparator(); + assertTrue(comp.compare("test1 32", "test1 32", true) == 0); + assertTrue(comp.compare("test1\t32", "test1 \n32", true) == 0); + assertFalse(comp.compare("test132", "test1 32", true) == 0); + } + + @Test + public void testNullComparison() { + StringComparator comp = new StringComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare("xxx3", null) == 0); + assertFalse(comp.compare(null, "xxx3") == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/StringListComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/StringListComparatorTest.java index e22dbc1cb5..f636610c85 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/StringListComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/StringListComparatorTest.java @@ -1,56 +1,54 @@ package lcsb.mapviewer.common.comparator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class StringListComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void testNotNullComparisonEqualLength() { - List<String> list1 = new ArrayList<>(); - List<String> list2 = new ArrayList<>(); - List<String> list3 = new ArrayList<>(); - list1.add("str1"); - list2.add("str2"); - list3.add("str1"); - StringListComparator comp = new StringListComparator(); - assertTrue(comp.compare(list1, list3) == 0); - assertFalse(comp.compare(list1, list2) == 0); - assertFalse(comp.compare(list2, list3) == 0); - } - - @Test - public void testNotNullComparisonDiffLength() { - List<String> list1 = new ArrayList<>(); - List<String> list2 = new ArrayList<>(); - list1.add("str1"); - list2.add("str2"); - list2.add("str1"); - StringListComparator comp = new StringListComparator(); - assertFalse(comp.compare(list1, list2) == 0); - } - - @Test - public void testNullComparison() { - StringListComparator comp = new StringListComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(new ArrayList<>(), null) == 0); - assertFalse(comp.compare(null, new ArrayList<>()) == 0); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparisonEqualLength() { + List<String> list1 = new ArrayList<>(); + List<String> list2 = new ArrayList<>(); + List<String> list3 = new ArrayList<>(); + list1.add("str1"); + list2.add("str2"); + list3.add("str1"); + StringListComparator comp = new StringListComparator(); + assertTrue(comp.compare(list1, list3) == 0); + assertFalse(comp.compare(list1, list2) == 0); + assertFalse(comp.compare(list2, list3) == 0); + } + + @Test + public void testNotNullComparisonDiffLength() { + List<String> list1 = new ArrayList<>(); + List<String> list2 = new ArrayList<>(); + list1.add("str1"); + list2.add("str2"); + list2.add("str1"); + StringListComparator comp = new StringListComparator(); + assertFalse(comp.compare(list1, list2) == 0); + } + + @Test + public void testNullComparison() { + StringListComparator comp = new StringListComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(new ArrayList<>(), null) == 0); + assertFalse(comp.compare(null, new ArrayList<>()) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/comparator/StringSetComparatorTest.java b/commons/src/test/java/lcsb/mapviewer/common/comparator/StringSetComparatorTest.java index d74ca665e1..cebce07970 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/comparator/StringSetComparatorTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/comparator/StringSetComparatorTest.java @@ -6,56 +6,53 @@ import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class StringSetComparatorTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testNotNullComparisonEqualLength() { - Set<String> list1 = new HashSet<>(); - Set<String> list2 = new HashSet<>(); - Set<String> list3 = new HashSet<>(); - list1.add("str1"); - list1.add("x"); - list2.add("str2"); - list2.add("x"); - list3.add("x"); - list3.add("str1"); - StringSetComparator comp = new StringSetComparator(); - assertTrue(comp.compare(list1, list3) == 0); - assertFalse(comp.compare(list1, list2) == 0); - assertFalse(comp.compare(list2, list3) == 0); - } - - @Test - public void testNotNullComparisonDiffLength() { - Set<String> list1 = new HashSet<>(); - Set<String> list2 = new HashSet<>(); - list1.add("str1"); - list2.add("str2"); - list2.add("str1"); - StringSetComparator comp = new StringSetComparator(); - assertFalse(comp.compare(list1, list2) == 0); - assertFalse(comp.compare(list2, list1) == 0); - } - - @Test - public void testNullComparison() { - StringSetComparator comp = new StringSetComparator(); - assertTrue(comp.compare(null, null) == 0); - assertFalse(comp.compare(new HashSet<>(), null) == 0); - assertFalse(comp.compare(null, new HashSet<>()) == 0); - } - + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testNotNullComparisonEqualLength() { + Set<String> list1 = new HashSet<>(); + Set<String> list2 = new HashSet<>(); + Set<String> list3 = new HashSet<>(); + list1.add("str1"); + list1.add("x"); + list2.add("str2"); + list2.add("x"); + list3.add("x"); + list3.add("str1"); + StringSetComparator comp = new StringSetComparator(); + assertTrue(comp.compare(list1, list3) == 0); + assertFalse(comp.compare(list1, list2) == 0); + assertFalse(comp.compare(list2, list3) == 0); + } + + @Test + public void testNotNullComparisonDiffLength() { + Set<String> list1 = new HashSet<>(); + Set<String> list2 = new HashSet<>(); + list1.add("str1"); + list2.add("str2"); + list2.add("str1"); + StringSetComparator comp = new StringSetComparator(); + assertFalse(comp.compare(list1, list2) == 0); + assertFalse(comp.compare(list2, list1) == 0); + } + + @Test + public void testNullComparison() { + StringSetComparator comp = new StringSetComparator(); + assertTrue(comp.compare(null, null) == 0); + assertFalse(comp.compare(new HashSet<>(), null) == 0); + assertFalse(comp.compare(null, new HashSet<>()) == 0); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/exception/AllExceptionTests.java b/commons/src/test/java/lcsb/mapviewer/common/exception/AllExceptionTests.java index c97eba1515..cdb80a357e 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/exception/AllExceptionTests.java +++ b/commons/src/test/java/lcsb/mapviewer/common/exception/AllExceptionTests.java @@ -5,8 +5,9 @@ import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) -@SuiteClasses({ InvalidArgumentExceptionTest.class, InvalidClassExceptionTest.class, InvalidStateExceptionTest.class, InvalidXmlSchemaExceptionTest.class, - NotImplementedExceptionTest.class }) +@SuiteClasses({ InvalidArgumentExceptionTest.class, InvalidClassExceptionTest.class, InvalidStateExceptionTest.class, + InvalidXmlSchemaExceptionTest.class, + NotImplementedExceptionTest.class }) public class AllExceptionTests { } diff --git a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidArgumentExceptionTest.java b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidArgumentExceptionTest.java index 4f29bfe219..187b22ca08 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidArgumentExceptionTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidArgumentExceptionTest.java @@ -1,39 +1,37 @@ package lcsb.mapviewer.common.exception; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class InvalidArgumentExceptionTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor1() { - assertNotNull(new InvalidArgumentException()); - } - - @Test - public void testConstructor2() { - assertNotNull(new InvalidArgumentException("str")); - } - - @Test - public void testConstructor3() { - assertNotNull(new InvalidArgumentException(new Exception())); - } - - @Test - public void testConstructor4() { - assertNotNull(new InvalidArgumentException("dsr", new Exception())); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor1() { + assertNotNull(new InvalidArgumentException()); + } + + @Test + public void testConstructor2() { + assertNotNull(new InvalidArgumentException("str")); + } + + @Test + public void testConstructor3() { + assertNotNull(new InvalidArgumentException(new Exception())); + } + + @Test + public void testConstructor4() { + assertNotNull(new InvalidArgumentException("dsr", new Exception())); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidClassExceptionTest.java b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidClassExceptionTest.java index 4dcb0c5896..ee2f20b839 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidClassExceptionTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidClassExceptionTest.java @@ -2,28 +2,26 @@ package lcsb.mapviewer.common.exception; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class InvalidClassExceptionTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor1() { - assertNotNull(new InvalidClassException("str")); - } + @Test + public void testConstructor1() { + assertNotNull(new InvalidClassException("str")); + } - @Test - public void testConstructor2() { - assertNotNull(new InvalidClassException("dsr", new Exception())); - } + @Test + public void testConstructor2() { + assertNotNull(new InvalidClassException("dsr", new Exception())); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidStateExceptionTest.java b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidStateExceptionTest.java index 4ff04ade68..4cc1abdb91 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidStateExceptionTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidStateExceptionTest.java @@ -1,39 +1,37 @@ package lcsb.mapviewer.common.exception; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class InvalidStateExceptionTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor1() { - assertNotNull(new InvalidStateException()); - } - - @Test - public void testConstructor2() { - assertNotNull(new InvalidStateException("str")); - } - - @Test - public void testConstructor3() { - assertNotNull(new InvalidStateException(new Exception())); - } - - @Test - public void testConstructor4() { - assertNotNull(new InvalidStateException("dsr", new Exception())); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor1() { + assertNotNull(new InvalidStateException()); + } + + @Test + public void testConstructor2() { + assertNotNull(new InvalidStateException("str")); + } + + @Test + public void testConstructor3() { + assertNotNull(new InvalidStateException(new Exception())); + } + + @Test + public void testConstructor4() { + assertNotNull(new InvalidStateException("dsr", new Exception())); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaExceptionTest.java b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaExceptionTest.java index 95ae7bbc05..1898b30907 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaExceptionTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/exception/InvalidXmlSchemaExceptionTest.java @@ -1,39 +1,37 @@ package lcsb.mapviewer.common.exception; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class InvalidXmlSchemaExceptionTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor1() { - assertNotNull(new InvalidXmlSchemaException()); - } - - @Test - public void testConstructor2() { - assertNotNull(new InvalidXmlSchemaException("str")); - } - - @Test - public void testConstructor3() { - assertNotNull(new InvalidXmlSchemaException(new Exception())); - } - - @Test - public void testConstructor4() { - assertNotNull(new InvalidXmlSchemaException("dsr", new Exception())); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor1() { + assertNotNull(new InvalidXmlSchemaException()); + } + + @Test + public void testConstructor2() { + assertNotNull(new InvalidXmlSchemaException("str")); + } + + @Test + public void testConstructor3() { + assertNotNull(new InvalidXmlSchemaException(new Exception())); + } + + @Test + public void testConstructor4() { + assertNotNull(new InvalidXmlSchemaException("dsr", new Exception())); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/exception/NotImplementedExceptionTest.java b/commons/src/test/java/lcsb/mapviewer/common/exception/NotImplementedExceptionTest.java index 17d933b020..45f0214c9a 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/exception/NotImplementedExceptionTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/exception/NotImplementedExceptionTest.java @@ -1,29 +1,27 @@ package lcsb.mapviewer.common.exception; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class NotImplementedExceptionTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor1() { - assertNotNull(new NotImplementedException()); - } + @Test + public void testConstructor1() { + assertNotNull(new NotImplementedException()); + } - @Test - public void testConstructor2() { - assertNotNull(new NotImplementedException("str")); - } + @Test + public void testConstructor2() { + assertNotNull(new NotImplementedException("str")); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/AllGeometryTests.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/AllGeometryTests.java index acf62ccd69..6eabaa75d7 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/AllGeometryTests.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/AllGeometryTests.java @@ -6,11 +6,11 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ColorParserTest.class, - CompositeStrokeTest.class, - EllipseTransformationTest.class, - LineTransformationTest.class, - PointTransformationTest.class, - TextAlignmentTest.class, + CompositeStrokeTest.class, + EllipseTransformationTest.class, + LineTransformationTest.class, + PointTransformationTest.class, + TextAlignmentTest.class, }) public class AllGeometryTests { diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java index bc6e7abe34..8a2580fc5a 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/ColorParserTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.common.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import java.awt.Color; +import java.awt.*; import org.junit.*; diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/CompositeStrokeTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/CompositeStrokeTest.java index a4251214cd..2ede377702 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/CompositeStrokeTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/CompositeStrokeTest.java @@ -1,26 +1,24 @@ package lcsb.mapviewer.common.geometry; -import java.awt.BasicStroke; +import java.awt.*; import java.awt.geom.Line2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CompositeStrokeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void test() { - CompositeStroke cs = new CompositeStroke(new BasicStroke(10f), new BasicStroke(0.5f)); - cs.createStrokedShape(new Line2D.Double(0.1, 0.1, 0.1, 0.1)); - } + @Test + public void test() { + CompositeStroke cs = new CompositeStroke(new BasicStroke(10f), new BasicStroke(0.5f)); + cs.createStrokedShape(new Line2D.Double(0.1, 0.1, 0.1, 0.1)); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/EllipseTransformationTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/EllipseTransformationTest.java index e73ada3547..501ca1183d 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/EllipseTransformationTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/EllipseTransformationTest.java @@ -1,83 +1,82 @@ package lcsb.mapviewer.common.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; public class EllipseTransformationTest { - Logger logger = LogManager.getLogger(EllipseTransformationTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testPointOnEllipse() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 0); - assertTrue(point.distance(0, 100) <= Configuration.EPSILON); - } - - @Test - public void testPointOnEllipse2() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 90); - assertTrue(point.distance(100, 0) <= Configuration.EPSILON); - } - - @Test - public void testPointOnEllipse3() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 180); - assertTrue(point.distance(200, 100) <= Configuration.EPSILON); - } - - @Test - public void testPointOnEllipse4() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 270); - assertTrue(point.distance(100, 200) <= Configuration.EPSILON); - } - - @Test - public void testPointOnEllipse5() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 360); - assertTrue(point.distance(0, 100) <= Configuration.EPSILON); - } - - @Test - public void testPointOnEllipse6() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 300); - assertNotNull(point); - } - - @Test - public void testPointOnEllipse7() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, -360); - assertTrue(point.distance(0, 100) <= Configuration.EPSILON); - } - - @Test - public void testPointOnEllipse8() { - EllipseTransformation et = new EllipseTransformation(); - Point2D point = et.getPointOnEllipseByDegree(new Ellipse2D.Double(0, 0, 200, 200), -360); - assertTrue(point.distance(0, 100) <= Configuration.EPSILON); - } + Logger logger = LogManager.getLogger(EllipseTransformationTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPointOnEllipse() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 0); + assertTrue(point.distance(0, 100) <= Configuration.EPSILON); + } + + @Test + public void testPointOnEllipse2() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 90); + assertTrue(point.distance(100, 0) <= Configuration.EPSILON); + } + + @Test + public void testPointOnEllipse3() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 180); + assertTrue(point.distance(200, 100) <= Configuration.EPSILON); + } + + @Test + public void testPointOnEllipse4() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 270); + assertTrue(point.distance(100, 200) <= Configuration.EPSILON); + } + + @Test + public void testPointOnEllipse5() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 360); + assertTrue(point.distance(0, 100) <= Configuration.EPSILON); + } + + @Test + public void testPointOnEllipse6() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, 300); + assertNotNull(point); + } + + @Test + public void testPointOnEllipse7() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(0, 0, 200, 200, -360); + assertTrue(point.distance(0, 100) <= Configuration.EPSILON); + } + + @Test + public void testPointOnEllipse8() { + EllipseTransformation et = new EllipseTransformation(); + Point2D point = et.getPointOnEllipseByDegree(new Ellipse2D.Double(0, 0, 200, 200), -360); + assertTrue(point.distance(0, 100) <= Configuration.EPSILON); + } } diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/LineTransformationTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/LineTransformationTest.java index cf3bf6483d..b6faf2f5a8 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/LineTransformationTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/LineTransformationTest.java @@ -1,23 +1,13 @@ package lcsb.mapviewer.common.geometry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.geom.RoundRectangle2D; +import static org.junit.Assert.*; + +import java.awt.*; +import java.awt.geom.*; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; @@ -84,9 +74,9 @@ public class LineTransformationTest { p = lineTransformation.getIntersectionWithPathIterator(line, new PathIterator() { @Override - public void next() { + public int getWindingRule() { // TODO Auto-generated method stub - + return 0; } @Override @@ -95,19 +85,19 @@ public class LineTransformationTest { } @Override - public int getWindingRule() { + public void next() { // TODO Auto-generated method stub - return 0; + } @Override - public int currentSegment(double[] coords) { + public int currentSegment(float[] coords) { // TODO Auto-generated method stub return 0; } @Override - public int currentSegment(float[] coords) { + public int currentSegment(double[] coords) { // TODO Auto-generated method stub return 0; } diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/PointTransformationTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/PointTransformationTest.java index f9bb7c1b83..fdcfe8c7da 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/PointTransformationTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/PointTransformationTest.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.common.geometry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.Configuration; @@ -58,7 +54,7 @@ public class PointTransformationTest { Point2D p1 = new Point2D.Double(1, 0); Point2D p2 = new Point2D.Double(12, 38); Point2D result = pt.getPointOnLine(p1, p2, 0); - + assertEquals(p1, result); } @@ -68,7 +64,7 @@ public class PointTransformationTest { Point2D p1 = new Point2D.Double(1, 0); Point2D p2 = new Point2D.Double(12, 38); Point2D result = pt.getPointOnLine(p1, p2, 1); - + assertEquals(p2, result); } @@ -78,7 +74,7 @@ public class PointTransformationTest { Point2D p1 = new Point2D.Double(1, 0); Point2D p2 = new Point2D.Double(12, 38); Point2D result = pt.getPointOnLine(p1, p2, 0.5); - + assertEquals(new Point2D.Double(6.5, 19), result); } @@ -88,7 +84,7 @@ public class PointTransformationTest { Point2D p1 = new Point2D.Double(2, 0); Point2D p2 = new Point2D.Double(12, 20); Point2D result = pt.getPointOnLine(p1, p2, 0.4); - + assertEquals(new Point2D.Double(6, 8), result); } diff --git a/commons/src/test/java/lcsb/mapviewer/common/geometry/TextAlignmentTest.java b/commons/src/test/java/lcsb/mapviewer/common/geometry/TextAlignmentTest.java index b14349b8ef..a7dae046f8 100644 --- a/commons/src/test/java/lcsb/mapviewer/common/geometry/TextAlignmentTest.java +++ b/commons/src/test/java/lcsb/mapviewer/common/geometry/TextAlignmentTest.java @@ -2,28 +2,26 @@ package lcsb.mapviewer.common.geometry; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class TextAlignmentTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (TextAlignment type : TextAlignment.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (TextAlignment type : TextAlignment.values()) { + assertNotNull(type); - // for coverage tests - TextAlignment.valueOf(type.toString()); - } - } + // for coverage tests + TextAlignment.valueOf(type.toString()); + } + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollection.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollection.java index cf70051535..bfdabc4292 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollection.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerElementCollection.java @@ -1,25 +1,14 @@ package lcsb.mapviewer.converter.model.celldesigner; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -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.model.map.species.*; import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; import lcsb.mapviewer.model.map.species.field.ModificationResidue; @@ -40,14 +29,20 @@ public class CellDesignerElementCollection { * Element by element identifier (it's CellDesigner identifier). */ private Map<String, CellDesignerElement<?>> elementById = new HashMap<>(); + /** + * + */ + private Map<String, String> sbmlIdByElement = new HashMap<>(); + private Map<String, String> modificationResidueIdByHash = new HashMap<>(); + private Set<String> usedModificationResidueIds = new HashSet<>(); /** * Returns element by given identifier. - * + * * @param speciesId * element identifier * @return element by given identifier - * + * * @param <T> * type of returned object */ @@ -56,15 +51,10 @@ public class CellDesignerElementCollection { return (T) elementById.get(speciesId); } - /** - * - */ - private Map<String, String> sbmlIdByElement = new HashMap<>(); - /** * Returns element identifier that should be used for model element when * creating cell designer xml file. - * + * * @param modelElement * model element for which we want to obtain identifier * @return identifier of cell designer element that will be exported @@ -88,7 +78,7 @@ public class CellDesignerElementCollection { /** * Creates a String that identifies element as distinct SBML entity. - * + * * @param modelElement * element that we want to identify * @param useComplex @@ -174,7 +164,7 @@ public class CellDesignerElementCollection { /** * Checks if complex parenting is cyclic. - * + * * @param complex * complex for which data is checked * @return true if parent of the complex is also a (grand)child of this complex, @@ -194,7 +184,7 @@ public class CellDesignerElementCollection { /** * Adds cell designer structures. - * + * * @param elements * list of objects to add */ @@ -206,7 +196,7 @@ public class CellDesignerElementCollection { /** * Adds cell designer object. - * + * * @param element * object to add */ @@ -217,7 +207,7 @@ public class CellDesignerElementCollection { /** * Adds CellDesigner element with custom id (instead the one obtained from * CellDesigner structure). - * + * * @param element * element to be add * @param id @@ -234,7 +224,7 @@ public class CellDesignerElementCollection { /** * Adds CellDesigner structure in a way that it would be accessed via identifier * for model structure. Method used only for unit test. - * + * * @param modelElement * model element that will create identifier * @param element @@ -247,9 +237,6 @@ public class CellDesignerElementCollection { } } - private Map<String, String> modificationResidueIdByHash = new HashMap<>(); - private Set<String> usedModificationResidueIds = new HashSet<>(); - /** * This method computes modificationResidueId that should be used when exporting * modification residue to CellDesigner. The identifier relies on type and 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 28bd63f9eb..37084d1bd0 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 @@ -11,19 +11,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.apache.xerces.parsers.DOMParser; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import lcsb.mapviewer.common.MimeType; -import lcsb.mapviewer.common.MinervaLoggerAppender; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.XmlParser; +import org.w3c.dom.*; + +import lcsb.mapviewer.common.*; 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.*; import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.alias.AliasCollectionXmlParser; import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; @@ -33,27 +25,17 @@ import lcsb.mapviewer.converter.model.celldesigner.parameter.ParameterCollection import lcsb.mapviewer.converter.model.celldesigner.reaction.ReactionCollectionXmlParser; import lcsb.mapviewer.converter.model.celldesigner.species.InternalModelSpeciesData; import lcsb.mapviewer.converter.model.celldesigner.species.SpeciesCollectionXmlParser; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompartment; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.converter.model.celldesigner.unit.UnitCollectionXmlParser; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.layout.graphics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.Element; -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; /** * This class is a parser for CellDesigner files. There are two typical use @@ -251,9 +233,29 @@ public class CellDesignerXmlParser extends Converter { return model; } + @Override + public String model2String(Model model) throws InconsistentModelException { + return model2Xml(model, true); + } + + @Override + public String getCommonName() { + return "CellDesigner SBML"; + } + + @Override + public MimeType getMimeType() { + return MimeType.SBML; + } + + @Override + public String getFileExtension() { + return "xml"; + } + /** * Computes bound of the model. - * + * * @param model * object for which computaion is done * @return bound of the model @@ -341,7 +343,7 @@ public class CellDesignerXmlParser extends Converter { /** * Parse annotation part of CellDesigner xml. - * + * * @param model * model that is parsed (and will be updated) * @param modelData @@ -507,7 +509,7 @@ public class CellDesignerXmlParser extends Converter { /** * Parses celldesigner:listOfComplexSpeciesAliases node for annotation part of * the CellDEsigner format. - * + * * @param model * model that is parsed * @param aliasNode @@ -545,7 +547,7 @@ public class CellDesignerXmlParser extends Converter { /** * Parses celldesigner:listOfSpeciesAliases node for annotation part of the * CellDesigner format. - * + * * @param model * model that is parsed * @param aliasNode @@ -581,14 +583,9 @@ public class CellDesignerXmlParser extends Converter { } } - @Override - public String model2String(Model model) throws InconsistentModelException { - return model2Xml(model, true); - } - /** * Transforms model into CellDesigner xml. - * + * * @param model * model that should be transformed * @return CellDesigner xml string for the model @@ -661,7 +658,7 @@ public class CellDesignerXmlParser extends Converter { /** * Generates xml node that should be in annotation part of the model. - * + * * @param model * model to transform * @param elements @@ -714,19 +711,4 @@ public class CellDesignerXmlParser extends Converter { result.append("</annotation>\n"); return result.toString(); } - - @Override - public String getCommonName() { - return "CellDesigner SBML"; - } - - @Override - public MimeType getMimeType() { - return MimeType.SBML; - } - - @Override - public String getFileExtension() { - return "xml"; - } } 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 ec94fbd251..dc0038372a 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,15 +1,14 @@ package lcsb.mapviewer.converter.model.celldesigner; -import java.awt.Color; -import java.awt.Dimension; +import java.awt.*; import java.awt.geom.Point2D; +import org.w3c.dom.Node; + import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.SingleLine; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.View; -import org.w3c.dom.Node; - /** * Class with parsers for common CellDesigner objects. * @@ -17,90 +16,90 @@ import org.w3c.dom.Node; * */ public class CommonXmlParser { - /** - * Parse xml representation of position into Poin2D object. - * - * @param node - * xml node to parse - * @return Point2D object - */ - public Point2D getPosition(Node node) { - double x = Double.parseDouble(XmlParser.getNodeAttr("x", node)); - double y = Double.parseDouble(XmlParser.getNodeAttr("y", node)); - return new Point2D.Double(x, y); + /** + * Parse xml representation of position into Poin2D object. + * + * @param node + * xml node to parse + * @return Point2D object + */ + public Point2D getPosition(Node node) { + double x = Double.parseDouble(XmlParser.getNodeAttr("x", node)); + double y = Double.parseDouble(XmlParser.getNodeAttr("y", node)); + return new Point2D.Double(x, y); - } + } - /** - * Parse xml representation of dimension. - * - * @param node - * xml node to parse - * @return dimension (with width and height fields) - */ - public Dimension getDimension(Node node) { - double width = Double.parseDouble(XmlParser.getNodeAttr("width", node)); - double height = Double.parseDouble(XmlParser.getNodeAttr("height", node)); - Dimension result = new Dimension(); - result.setSize(width, height); - return result; - } + /** + * Parse xml representation of dimension. + * + * @param node + * xml node to parse + * @return dimension (with width and height fields) + */ + public Dimension getDimension(Node node) { + double width = Double.parseDouble(XmlParser.getNodeAttr("width", node)); + double height = Double.parseDouble(XmlParser.getNodeAttr("height", node)); + Dimension result = new Dimension(); + result.setSize(width, height); + return result; + } - /** - * Parse xml representation of CellDesigner SingleLine. - * - * @param node - * xml node to parse - * @return sinle line object (with width field) - */ - public SingleLine getSingleLine(Node node) { - SingleLine result = new SingleLine(); - result.setWidth(Double.parseDouble(XmlParser.getNodeAttr("width", node))); - return result; - } + /** + * Parse xml representation of CellDesigner SingleLine. + * + * @param node + * xml node to parse + * @return sinle line object (with width field) + */ + public SingleLine getSingleLine(Node node) { + SingleLine result = new SingleLine(); + result.setWidth(Double.parseDouble(XmlParser.getNodeAttr("width", node))); + return result; + } - /** - * Parse xml representation of CellDesigner color. - * - * @param node - * xml node to parse - * @return Color value stored in xml - */ - public Color getColor(Node node) { - String color = XmlParser.getNodeAttr("color", node); - return XmlParser.stringToColor(color); - } + /** + * Parse xml representation of CellDesigner color. + * + * @param node + * xml node to parse + * @return Color value stored in xml + */ + public Color getColor(Node node) { + String color = XmlParser.getNodeAttr("color", node); + return XmlParser.stringToColor(color); + } - /** - * Parse xml representation of CellDesigner view. - * - * @param node - * xml node to parse - * @return view parsed from xml - * @see View - */ - public View getView(Node node) { - View result = new View(); - Node tmpNode = XmlParser.getNode("celldesigner:innerPosition", node.getChildNodes()); - if (tmpNode != null) { - result.setInnerPosition(getPosition(tmpNode)); - } + /** + * Parse xml representation of CellDesigner view. + * + * @param node + * xml node to parse + * @return view parsed from xml + * @see View + */ + public View getView(Node node) { + View result = new View(); + Node tmpNode = XmlParser.getNode("celldesigner:innerPosition", node.getChildNodes()); + if (tmpNode != null) { + result.setInnerPosition(getPosition(tmpNode)); + } - tmpNode = XmlParser.getNode("celldesigner:boxSize", node.getChildNodes()); - if (tmpNode != null) { - result.setBoxSize(getDimension(tmpNode)); - } + tmpNode = XmlParser.getNode("celldesigner:boxSize", node.getChildNodes()); + if (tmpNode != null) { + result.setBoxSize(getDimension(tmpNode)); + } - tmpNode = XmlParser.getNode("celldesigner:singleLine", node.getChildNodes()); - if (tmpNode != null) { - result.setSingleLine(getSingleLine(tmpNode)); - } + tmpNode = XmlParser.getNode("celldesigner:singleLine", node.getChildNodes()); + if (tmpNode != null) { + result.setSingleLine(getSingleLine(tmpNode)); + } - tmpNode = XmlParser.getNode("celldesigner:paint", node.getChildNodes()); - if (tmpNode != null) { - result.setColor(getColor(tmpNode)); - } - return result; - } + tmpNode = XmlParser.getNode("celldesigner:paint", node.getChildNodes()); + if (tmpNode != null) { + result.setColor(getColor(tmpNode)); + } + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupException.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupException.java index 9f854ba231..8016abea06 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupException.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupException.java @@ -9,51 +9,51 @@ import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; * */ public class InvalidGroupException extends InvalidXmlSchemaException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor - initializes instance variable to unknown. - */ - - public InvalidGroupException() { - super(); - } - - /** - * Constructor receives some kind of message. - * - * @param err - * message associated with exception - */ - - public InvalidGroupException(final String err) { - super(err); - } - - /** - * Constructor receives some kind of message and parent exception. - * - * @param err - * message associated with exception - * @param throwable - * parent exception - */ - public InvalidGroupException(final String err, final Throwable throwable) { - super(err, throwable); - } - - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - - public InvalidGroupException(final Exception e) { - super(e); - } + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor - initializes instance variable to unknown. + */ + + public InvalidGroupException() { + super(); + } + + /** + * Constructor receives some kind of message. + * + * @param err + * message associated with exception + */ + + public InvalidGroupException(final String err) { + super(err); + } + + /** + * Constructor receives some kind of message and parent exception. + * + * @param err + * message associated with exception + * @param throwable + * parent exception + */ + public InvalidGroupException(final String err, final Throwable throwable) { + super(err, throwable); + } + + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + + public InvalidGroupException(final Exception e) { + super(e); + } } 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 e06a9ba21d..c37f312dd2 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 @@ -1,12 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; +import java.util.*; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -14,15 +14,10 @@ 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; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.layout.BlockDiagram; import lcsb.mapviewer.model.map.layout.ElementGroup; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.layout.graphics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AbstractAliasXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AbstractAliasXmlParser.java index 35c9d295ab..c70a43f7a5 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AbstractAliasXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/AbstractAliasXmlParser.java @@ -1,9 +1,8 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import org.apache.logging.log4j.*; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -87,5 +86,5 @@ public abstract class AbstractAliasXmlParser<T extends Element> { protected String createFontTag(T alias) { return "<celldesigner:font size=\"" + alias.getFontSize().intValue() + "\"/>"; } - + } 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 04cf980173..028d1895f6 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,10 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -28,213 +27,216 @@ import lcsb.mapviewer.model.map.species.Species; */ public class AliasCollectionXmlParser { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(AliasCollectionXmlParser.class.getName()); - - /** - * Single SpeciesAlias parser for CellDesigner node. - */ - private SpeciesAliasXmlParser speciesAliasParser = null; - - /** - * Single ComplexAlias parser for CellDesigner node. - */ - private ComplexAliasXmlParser complexAliasParser = null; - - /** - * Single CompartmentAlias parser for CellDesigner node. - */ - private CompartmentAliasXmlParser compartmentAliasParser = null; - - /** - * Annotation parser. - */ - private RestAnnotationParser rap = new RestAnnotationParser(); - - /** - * Default parser. As an 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 - */ - public AliasCollectionXmlParser(CellDesignerElementCollection elements, Model model) { - speciesAliasParser = new SpeciesAliasXmlParser(elements, model); - complexAliasParser = new ComplexAliasXmlParser(elements, model); - compartmentAliasParser = new CompartmentAliasXmlParser(elements, model); - } - - /** - * Parses xml node containing list of species aliases into collection of - * SpeciesAlias. - * - * @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 - */ - public List<Species> parseXmlSpeciesAliasCollection(Node aliasListNode) throws InvalidXmlSchemaException { - List<Species> result = new ArrayList<Species>(); - NodeList nodes = aliasListNode.getChildNodes(); - for (int x = 0; x < nodes.getLength(); x++) { - Node node = nodes.item(x); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equalsIgnoreCase("celldesigner:speciesAlias")) { - Species alias = speciesAliasParser.parseXmlAlias(node); - rap.processNotes(alias); - result.add(alias); - } else { - throw new InvalidXmlSchemaException("Unknown element of celldesigner:listOfSpeciesAliases: " + node.getNodeName()); - } - } - } - return result; - } - - /** - * Creates xml string representing collection of SpeciesAlias. - * - * @param collection - * collection of SpeciesAlias - * @return xml string representing collection of SpeciesAlias - */ - public String speciesAliasCollectionToXmlString(Collection<Species> collection) { - StringBuilder sb = new StringBuilder("<celldesigner:listOfSpeciesAliases>\n"); - for (Species alias : collection) { - sb.append(speciesAliasParser.toXml(alias)); - } - sb.append("</celldesigner:listOfSpeciesAliases>\n"); - return sb.toString(); - } - - /** - * Parses xml node containing list of complex aliases into collection of - * ComplexAlias. - * - * @param aliasListNode - * xml node to be parsed - * @return collection of ComplexAlias obtained from xml node - * @throws InvalidXmlSchemaException - * thrown when xmlString is invalid - */ - public List<Complex> parseXmlComplexAliasCollection(Node aliasListNode) throws InvalidXmlSchemaException { - List<Complex> result = new ArrayList<Complex>(); - NodeList nodes = aliasListNode.getChildNodes(); - for (int x = 0; x < nodes.getLength(); x++) { - Node node = nodes.item(x); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equalsIgnoreCase("celldesigner:complexSpeciesAlias")) { - Complex alias = complexAliasParser.parseXmlAlias(node); - result.add(alias); - } else { - throw new InvalidXmlSchemaException("Unknown element of celldesigner:listOfComplexSpeciesAliases: " + node.getNodeName()); - } - } - } - for (Complex complexAlias : result) { - complexAliasParser.addReference(complexAlias); - } - return result; - } - - /** - * Creates xml string representing collection of ComplexAlias. - * - * @param collection - * collection of ComplexAlias - * @return xml string representing collection of ComplexAlias - */ - public String complexAliasCollectionToXmlString(Collection<Complex> collection) { - StringBuilder sb = new StringBuilder("<celldesigner:listOfComplexSpeciesAliases>\n"); - for (Complex alias : collection) { - sb.append(complexAliasParser.toXml(alias)); - } - sb.append("</celldesigner:listOfComplexSpeciesAliases>\n"); - return sb.toString(); - } - - /** - * Parses xml node containing list of compartment aliases into collection of - * CompartmentAlias. - * - * @param aliasListNode - * xml node to be parsed - * @return collection of CompartmentAlias obtained from xml node - * @throws InvalidXmlSchemaException - * thrown when xmlString is invalid - */ - public List<Compartment> parseXmlCompartmentAliasCollection(Node aliasListNode) throws InvalidXmlSchemaException { - List<Compartment> result = new ArrayList<>(); - NodeList nodes = aliasListNode.getChildNodes(); - for (int x = 0; x < nodes.getLength(); x++) { - Node node = nodes.item(x); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equalsIgnoreCase("celldesigner:compartmentAlias")) { - Compartment alias = compartmentAliasParser.parseXmlAlias(node); - result.add(alias); - } else { - throw new InvalidXmlSchemaException("Unknown element of celldesigner:listOfCompartmentAliases: " + node.getNodeName()); - } - } - } - assignParents(result); - - return result; - } - - /** - * Assing compartment parents for list of compartments. - * - * @param compartments - * compartments that are looking for parents - */ - private void assignParents(List<Compartment> compartments) { - Compartment nullParent = new Compartment("null"); - nullParent.setWidth(Double.MAX_VALUE); - nullParent.setHeight(Double.MAX_VALUE); - nullParent.setX(0.0); - nullParent.setY(0.0); - for (Compartment child : compartments) { - Compartment parent = nullParent; - for (Compartment potentialParent : compartments) { - if (potentialParent.contains(child)) { - if (parent.getSize() > potentialParent.getSize()) { - parent = potentialParent; - } - } - } - if (parent != nullParent) { - child.setCompartment(parent); - parent.addElement(child); - } - } - } - - /** - * Creates xml string representing collection of CompartmentAlias. - * - * @param collection - * collection of CompartmentAlias - * @return xml string representing collection of CompartmentAlias - */ - public String compartmentAliasCollectionToXmlString(Collection<Compartment> collection) { - StringBuilder sb = new StringBuilder("<celldesigner:listOfCompartmentAliases>\n"); - for (Compartment compartment : collection) { - // artifitial compartment aliases cannot be exported - if (!(compartment instanceof PathwayCompartment)) { - sb.append(compartmentAliasParser.toXml(compartment)); - } - } - sb.append("</celldesigner:listOfCompartmentAliases>\n"); - return sb.toString(); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(AliasCollectionXmlParser.class.getName()); + + /** + * Single SpeciesAlias parser for CellDesigner node. + */ + private SpeciesAliasXmlParser speciesAliasParser = null; + + /** + * Single ComplexAlias parser for CellDesigner node. + */ + private ComplexAliasXmlParser complexAliasParser = null; + + /** + * Single CompartmentAlias parser for CellDesigner node. + */ + private CompartmentAliasXmlParser compartmentAliasParser = null; + + /** + * Annotation parser. + */ + private RestAnnotationParser rap = new RestAnnotationParser(); + + /** + * Default parser. As an 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 + */ + public AliasCollectionXmlParser(CellDesignerElementCollection elements, Model model) { + speciesAliasParser = new SpeciesAliasXmlParser(elements, model); + complexAliasParser = new ComplexAliasXmlParser(elements, model); + compartmentAliasParser = new CompartmentAliasXmlParser(elements, model); + } + + /** + * Parses xml node containing list of species aliases into collection of + * SpeciesAlias. + * + * @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 + */ + public List<Species> parseXmlSpeciesAliasCollection(Node aliasListNode) throws InvalidXmlSchemaException { + List<Species> result = new ArrayList<Species>(); + NodeList nodes = aliasListNode.getChildNodes(); + for (int x = 0; x < nodes.getLength(); x++) { + Node node = nodes.item(x); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equalsIgnoreCase("celldesigner:speciesAlias")) { + Species alias = speciesAliasParser.parseXmlAlias(node); + rap.processNotes(alias); + result.add(alias); + } else { + throw new InvalidXmlSchemaException( + "Unknown element of celldesigner:listOfSpeciesAliases: " + node.getNodeName()); + } + } + } + return result; + } + + /** + * Creates xml string representing collection of SpeciesAlias. + * + * @param collection + * collection of SpeciesAlias + * @return xml string representing collection of SpeciesAlias + */ + public String speciesAliasCollectionToXmlString(Collection<Species> collection) { + StringBuilder sb = new StringBuilder("<celldesigner:listOfSpeciesAliases>\n"); + for (Species alias : collection) { + sb.append(speciesAliasParser.toXml(alias)); + } + sb.append("</celldesigner:listOfSpeciesAliases>\n"); + return sb.toString(); + } + + /** + * Parses xml node containing list of complex aliases into collection of + * ComplexAlias. + * + * @param aliasListNode + * xml node to be parsed + * @return collection of ComplexAlias obtained from xml node + * @throws InvalidXmlSchemaException + * thrown when xmlString is invalid + */ + public List<Complex> parseXmlComplexAliasCollection(Node aliasListNode) throws InvalidXmlSchemaException { + List<Complex> result = new ArrayList<Complex>(); + NodeList nodes = aliasListNode.getChildNodes(); + for (int x = 0; x < nodes.getLength(); x++) { + Node node = nodes.item(x); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equalsIgnoreCase("celldesigner:complexSpeciesAlias")) { + Complex alias = complexAliasParser.parseXmlAlias(node); + result.add(alias); + } else { + throw new InvalidXmlSchemaException( + "Unknown element of celldesigner:listOfComplexSpeciesAliases: " + node.getNodeName()); + } + } + } + for (Complex complexAlias : result) { + complexAliasParser.addReference(complexAlias); + } + return result; + } + + /** + * Creates xml string representing collection of ComplexAlias. + * + * @param collection + * collection of ComplexAlias + * @return xml string representing collection of ComplexAlias + */ + public String complexAliasCollectionToXmlString(Collection<Complex> collection) { + StringBuilder sb = new StringBuilder("<celldesigner:listOfComplexSpeciesAliases>\n"); + for (Complex alias : collection) { + sb.append(complexAliasParser.toXml(alias)); + } + sb.append("</celldesigner:listOfComplexSpeciesAliases>\n"); + return sb.toString(); + } + + /** + * Parses xml node containing list of compartment aliases into collection of + * CompartmentAlias. + * + * @param aliasListNode + * xml node to be parsed + * @return collection of CompartmentAlias obtained from xml node + * @throws InvalidXmlSchemaException + * thrown when xmlString is invalid + */ + public List<Compartment> parseXmlCompartmentAliasCollection(Node aliasListNode) throws InvalidXmlSchemaException { + List<Compartment> result = new ArrayList<>(); + NodeList nodes = aliasListNode.getChildNodes(); + for (int x = 0; x < nodes.getLength(); x++) { + Node node = nodes.item(x); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equalsIgnoreCase("celldesigner:compartmentAlias")) { + Compartment alias = compartmentAliasParser.parseXmlAlias(node); + result.add(alias); + } else { + throw new InvalidXmlSchemaException( + "Unknown element of celldesigner:listOfCompartmentAliases: " + node.getNodeName()); + } + } + } + assignParents(result); + + return result; + } + + /** + * Assing compartment parents for list of compartments. + * + * @param compartments + * compartments that are looking for parents + */ + private void assignParents(List<Compartment> compartments) { + Compartment nullParent = new Compartment("null"); + nullParent.setWidth(Double.MAX_VALUE); + nullParent.setHeight(Double.MAX_VALUE); + nullParent.setX(0.0); + nullParent.setY(0.0); + for (Compartment child : compartments) { + Compartment parent = nullParent; + for (Compartment potentialParent : compartments) { + if (potentialParent.contains(child)) { + if (parent.getSize() > potentialParent.getSize()) { + parent = potentialParent; + } + } + } + if (parent != nullParent) { + child.setCompartment(parent); + parent.addElement(child); + } + } + } + + /** + * Creates xml string representing collection of CompartmentAlias. + * + * @param collection + * collection of CompartmentAlias + * @return xml string representing collection of CompartmentAlias + */ + public String compartmentAliasCollectionToXmlString(Collection<Compartment> collection) { + StringBuilder sb = new StringBuilder("<celldesigner:listOfCompartmentAliases>\n"); + for (Compartment compartment : collection) { + // artifitial compartment aliases cannot be exported + if (!(compartment instanceof PathwayCompartment)) { + sb.append(compartmentAliasParser.toXml(compartment)); + } + } + sb.append("</celldesigner:listOfCompartmentAliases>\n"); + return sb.toString(); + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParser.java index c8cd11454c..9ab997e868 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/CompartmentAliasXmlParser.java @@ -1,22 +1,17 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerCompartment; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; -import lcsb.mapviewer.model.map.compartment.BottomSquareCompartment; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.compartment.LeftSquareCompartment; -import lcsb.mapviewer.model.map.compartment.OvalCompartment; -import lcsb.mapviewer.model.map.compartment.RightSquareCompartment; -import lcsb.mapviewer.model.map.compartment.SquareCompartment; -import lcsb.mapviewer.model.map.compartment.TopSquareCompartment; +import lcsb.mapviewer.model.map.compartment.*; import lcsb.mapviewer.model.map.model.Model; /** diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParser.java index cecd43d6b1..ee84daedd6 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParser.java @@ -3,14 +3,13 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.*; +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.XmlParser; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; @@ -167,51 +166,6 @@ public class ComplexAliasXmlParser extends AbstractAliasXmlParser<Complex> { return result; } - /** - * Process node with information about alias state and puts data into alias. - * - * @param node - * node where information about alias state is stored - * @param alias - * alias object to be modified if necessary - */ - private void processAliasState(Node node, Species alias) { - String state = XmlParser.getNodeAttr("state", node); - if ("open".equalsIgnoreCase(state)) { - String prefix = XmlParser.getNodeAttr("prefix", node); - String label = XmlParser.getNodeAttr("label", node); - alias.setStatePrefix(prefix); - alias.setStateLabel(label); - } else if ("empty".equalsIgnoreCase(state)) { - return; - } else if (state == null || state.isEmpty()) { - return; - } else { - throw new NotImplementedException("[Alias: " + alias.getElementId() + "] Unkown alias state: " + state); - } - - } - - /** - * Adds parent reference for the complexAlias. - * - * @param alias - * alias for which we want to add parent information - */ - public void addReference(Complex alias) { - String parentId = parents.get(alias.getElementId()); - if (parentId != null) { - Complex ca = complexAliasesMapById.get(parentId); - if (ca == null) { - throw new InvalidArgumentException( - "Parent complex alias does not exist: " + parentId + " for alias: " + alias.getElementId()); - } else { - alias.setComplex(ca); - ca.addSpecies(alias); - } - } - } - @Override public String toXml(Complex alias) { Compartment ca = null; @@ -286,4 +240,49 @@ public class ComplexAliasXmlParser extends AbstractAliasXmlParser<Complex> { sb.append("</celldesigner:complexSpeciesAlias>\n"); return sb.toString(); } + + /** + * Process node with information about alias state and puts data into alias. + * + * @param node + * node where information about alias state is stored + * @param alias + * alias object to be modified if necessary + */ + private void processAliasState(Node node, Species alias) { + String state = XmlParser.getNodeAttr("state", node); + if ("open".equalsIgnoreCase(state)) { + String prefix = XmlParser.getNodeAttr("prefix", node); + String label = XmlParser.getNodeAttr("label", node); + alias.setStatePrefix(prefix); + alias.setStateLabel(label); + } else if ("empty".equalsIgnoreCase(state)) { + return; + } else if (state == null || state.isEmpty()) { + return; + } else { + throw new NotImplementedException("[Alias: " + alias.getElementId() + "] Unkown alias state: " + state); + } + + } + + /** + * Adds parent reference for the complexAlias. + * + * @param alias + * alias for which we want to add parent information + */ + public void addReference(Complex alias) { + String parentId = parents.get(alias.getElementId()); + if (parentId != null) { + Complex ca = complexAliasesMapById.get(parentId); + if (ca == null) { + throw new InvalidArgumentException( + "Parent complex alias does not exist: " + parentId + " for alias: " + alias.getElementId()); + } else { + alias.setComplex(ca); + ca.addSpecies(alias); + } + } + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParser.java index b00bd68b1d..88744fd1d0 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParser.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.XmlParser; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.View; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; @@ -159,31 +156,6 @@ public class SpeciesAliasXmlParser extends AbstractAliasXmlParser<Species> { } } - /** - * Process node with information about alias state and puts data into alias. - * - * @param node - * node where information about alias state is stored - * @param alias - * alias object to be modified if necessary - */ - private void processAliasState(Node node, Species alias) { - String state = XmlParser.getNodeAttr("state", node); - if ("open".equalsIgnoreCase(state)) { - String prefix = XmlParser.getNodeAttr("prefix", node); - String label = XmlParser.getNodeAttr("label", node); - alias.setStatePrefix(prefix); - alias.setStateLabel(label); - } else if ("empty".equalsIgnoreCase(state)) { - return; - } else if (state == null || state.isEmpty()) { - return; - } else { - throw new NotImplementedException("[Alias: " + alias.getElementId() + "] Unkown alias state: " + state); - } - - } - @Override public String toXml(Species species) { Compartment ca = null; @@ -262,4 +234,29 @@ public class SpeciesAliasXmlParser extends AbstractAliasXmlParser<Species> { sb.append("</celldesigner:speciesAlias>\n"); return sb.toString(); } + + /** + * Process node with information about alias state and puts data into alias. + * + * @param node + * node where information about alias state is stored + * @param alias + * alias object to be modified if necessary + */ + private void processAliasState(Node node, Species alias) { + String state = XmlParser.getNodeAttr("state", node); + if ("open".equalsIgnoreCase(state)) { + String prefix = XmlParser.getNodeAttr("prefix", node); + String label = XmlParser.getNodeAttr("label", node); + alias.setStatePrefix(prefix); + alias.setStateLabel(label); + } else if ("empty".equalsIgnoreCase(state)) { + return; + } else if (state == null || state.isEmpty()) { + return; + } else { + throw new NotImplementedException("[Alias: " + alias.getElementId() + "] Unkown alias state: " + state); + } + + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/package-info.java index 4790cb66ee..34a3a4fb6b 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/alias/package-info.java @@ -3,4 +3,3 @@ * aliases. */ package lcsb.mapviewer.converter.model.celldesigner.alias; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java index 0eaf20fcd9..3844d7afa5 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteField.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.annotation; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.Drawable; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java index 28222d70a2..152bc605dd 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/RestAnnotationParser.java @@ -1,10 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.annotation; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -14,20 +10,10 @@ import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.StringComparator; -import lcsb.mapviewer.common.comparator.StringListComparator; -import lcsb.mapviewer.common.comparator.StringSetComparator; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.comparator.*; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.Drawable; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.layout.graphics.LayerText; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/package-info.java index d69c31ead7..3d155d34e8 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/annotation/package-info.java @@ -2,4 +2,3 @@ * Contains parser for annotation nodes. */ package lcsb.mapviewer.converter.model.celldesigner.annotation; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParser.java index cd43a8ba32..78e48e5872 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParser.java @@ -1,12 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -63,7 +60,7 @@ public class CompartmentCollectionXmlParser { * @return list of compartments obtained from xml node * @throws InvalidXmlSchemaException * thrown when there is a problem with xml - * @throws CompartmentParserException + * @throws CompartmentParserException * thrown when there is a problem with parsing a compartment */ public List<CellDesignerCompartment> parseXmlCompartmentCollection(Node compartmentsNode) diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserException.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserException.java index 0a95ae8de7..1c5796a73b 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserException.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserException.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerParserException; import lcsb.mapviewer.model.map.compartment.Compartment; @@ -13,17 +14,15 @@ import lcsb.mapviewer.model.map.compartment.Compartment; * */ public class CompartmentParserException extends CellDesignerParserException { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(CompartmentParserException.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Identifier of compartment that was a reason for this exception. */ 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 61f10f6800..794d0a9fc8 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,11 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.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; @@ -84,9 +85,48 @@ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerC } } + @Override + public String toXml(Compartment compartment) { + StringBuilder sb = new StringBuilder(""); + sb.append("<compartment "); + sb.append("metaid=\"" + elements.getElementId(compartment) + "\" "); + sb.append("id=\"" + elements.getElementId(compartment) + "\" "); + sb.append("name=\"" + encodeName(compartment.getName()) + "\" "); + sb.append("size=\"1\" "); + sb.append("units=\"volume\" "); + String parentName = "default"; + + if (compartment.getCompartment() != null && !(compartment.getCompartment() instanceof PathwayCompartment)) { + parentName = elements.getElementId(compartment.getCompartment()); + } + + // default is the top level compartment + if (!compartment.getElementId().equals("default")) { + sb.append("outside=\"" + parentName + "\" "); + } + sb.append(">\n"); + sb.append("<notes>"); + sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title/></head><body>"); + RestAnnotationParser rap = new RestAnnotationParser(); + sb.append(rap.createAnnotationString(compartment)); + if (compartment.getNotes() != null) { + sb.append(compartment.getNotes()); + } + sb.append("</body></html>"); + sb.append("</notes>\n"); + sb.append("<annotation>\n"); + sb.append("<celldesigner:extension>\n"); + sb.append("<celldesigner:name>" + encodeName(compartment.getName()) + "</celldesigner:name>\n"); + sb.append("</celldesigner:extension>\n"); + sb.append(xmlAnnotationParser.dataSetToXmlString(compartment.getMiriamData(), elements.getElementId(compartment))); + sb.append("</annotation>\n"); + sb.append("</compartment>\n"); + return sb.toString(); + } + /** * Process annotation part of the xml node. - * + * * @param compartment * object that we create * @param xmlNode @@ -113,7 +153,7 @@ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerC /** * Process extension part of the xml node. - * + * * @param compartment * object that we create * @param xmlNode @@ -136,43 +176,4 @@ public class CompartmentXmlParser extends AbstractElementXmlParser<CellDesignerC } } } - - @Override - public String toXml(Compartment compartment) { - StringBuilder sb = new StringBuilder(""); - sb.append("<compartment "); - sb.append("metaid=\"" + elements.getElementId(compartment) + "\" "); - sb.append("id=\"" + elements.getElementId(compartment) + "\" "); - sb.append("name=\"" + encodeName(compartment.getName()) + "\" "); - sb.append("size=\"1\" "); - sb.append("units=\"volume\" "); - String parentName = "default"; - - if (compartment.getCompartment() != null && !(compartment.getCompartment() instanceof PathwayCompartment)) { - parentName = elements.getElementId(compartment.getCompartment()); - } - - // default is the top level compartment - if (!compartment.getElementId().equals("default")) { - sb.append("outside=\"" + parentName + "\" "); - } - sb.append(">\n"); - sb.append("<notes>"); - sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title/></head><body>"); - RestAnnotationParser rap = new RestAnnotationParser(); - sb.append(rap.createAnnotationString(compartment)); - if (compartment.getNotes() != null) { - sb.append(compartment.getNotes()); - } - sb.append("</body></html>"); - sb.append("</notes>\n"); - sb.append("<annotation>\n"); - sb.append("<celldesigner:extension>\n"); - sb.append("<celldesigner:name>" + encodeName(compartment.getName()) + "</celldesigner:name>\n"); - sb.append("</celldesigner:extension>\n"); - sb.append(xmlAnnotationParser.dataSetToXmlString(compartment.getMiriamData(), elements.getElementId(compartment))); - sb.append("</annotation>\n"); - sb.append("</compartment>\n"); - return sb.toString(); - } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/package-info.java index 8d5a65ecbb..6341586150 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/compartment/package-info.java @@ -3,4 +3,3 @@ * compartments. */ package lcsb.mapviewer.converter.model.celldesigner.compartment; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParser.java index c536f2f32f..c85215482a 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParser.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.function; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; @@ -27,7 +28,8 @@ public class FunctionXmlParser { throw new InvalidXmlSchemaException("Function " + functionId + " doesn't contain MathML definition (math node)"); } String definition = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">" - + XmlParser.nodeToString(mathDefinition).replace(" xmlns=\"http://www.w3.org/1998/Math/MathML\"", "") + "</math>"; + + XmlParser.nodeToString(mathDefinition).replace(" xmlns=\"http://www.w3.org/1998/Math/MathML\"", "") + + "</math>"; result.setDefinition(definition); result.setArguments(parseArgumentsFromMath(mathDefinition, functionId)); diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverter.java index 3b0eb4869f..9b8166a77d 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverter.java @@ -1,21 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.common.geometry.LineTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerEllipseTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerPolygonTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerRectangleTransformation; +import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.*; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -31,61 +25,50 @@ import lcsb.mapviewer.model.map.species.field.ModificationResidue; */ public abstract class AbstractCellDesignerAliasConverter<T extends Element> implements ICellDesignerAliasConverter<T> { + /** + * What is the distance between homodimer aliases when homodimer>1. + */ + public static final int HOMODIMER_OFFSET = 6; /** * PI value. */ private static final double PI = Math.PI; - /** * Constant determining angle of the top right corner. */ protected static final double RIGHT_TOP_RESIDUE_MAX_ANGLE = 0.25 * PI; - /** * Constant determining angle of the top left corner. */ protected static final double TOP_RESIDUE_MAX_ANGLE = 0.75 * PI; - /** * Constant determining angle of the bottom left corner. */ protected static final double LEFT_RESIDUE_MAX_ANGLE = 1.25 * PI; - /** * Constant determining angle of the bottom right corner. */ protected static final double BOTTOM_RESIDUE_MAX_ANGLE = 1.75 * PI; - /** * Default class logger. */ private static Logger logger = LogManager.getLogger(AbstractCellDesignerAliasConverter.class); - /** * CellDesigner graphical helper with polygon transformation functions. */ private CellDesignerPolygonTransformation polygonTransformation = new CellDesignerPolygonTransformation(); - /** * CellDesigner graphical helper with line transformation functions. */ private LineTransformation lineTransformation = new LineTransformation(); - /** * CellDesigner graphical helper with ellipse transformation functions. */ private CellDesignerEllipseTransformation ellipseTransformation = new CellDesignerEllipseTransformation(); - /** * CellDesigner graphical helper with rectangle transformation functions. */ private CellDesignerRectangleTransformation rectangleTransformation = new CellDesignerRectangleTransformation(); - - /** - * What is the distance between homodimer aliases when homodimer>1. - */ - public static final int HOMODIMER_OFFSET = 6; - /** * Should the converter use SBGN standard. */ @@ -139,10 +122,130 @@ public abstract class AbstractCellDesignerAliasConverter<T extends Element> impl } } + /** + * Returns coordinates on the {@link Species} border for given angle for + * residues. + * + * @param species + * object on border which the point is looked for + * @param angle + * CellDEsigner specific angle defining coordinates (;/) + * @return coordinates on the alias border that correspond to the angle + */ + @Override + public Point2D getResidueCoordinates(final T species, double angle) { + Point2D result = null; + if (species.getWidth() == 0 && species.getHeight() == 0) { + result = species.getCenter(); + } else { + double x = 0; + double y = 0; + while (angle > 2 * PI) { + angle -= 2 * PI; + } + while (angle < 0) { + angle += 2 * PI; + } + if (angle < RIGHT_TOP_RESIDUE_MAX_ANGLE) { + // CHECKSTYLE:OFF 0.5 is much readable than any other suggestion + double ratio = 0.5 + angle / (PI / 2); + // CHECKSTYLE:ON + x = species.getX() + species.getWidth(); + y = species.getY() + species.getHeight() * (1 - ratio); + } else if (angle < TOP_RESIDUE_MAX_ANGLE) { + double ratio = (angle - RIGHT_TOP_RESIDUE_MAX_ANGLE) / (PI / 2); + y = species.getY(); + x = species.getX() + species.getWidth() * (1 - ratio); + } else if (angle < LEFT_RESIDUE_MAX_ANGLE) { + double ratio = (angle - TOP_RESIDUE_MAX_ANGLE) / (PI / 2); + y = species.getY() + species.getHeight() * (ratio); + x = species.getX(); + } else if (angle < BOTTOM_RESIDUE_MAX_ANGLE) { + double ratio = (angle - LEFT_RESIDUE_MAX_ANGLE) / (PI / 2); + y = species.getY() + species.getHeight(); + x = species.getX() + species.getWidth() * ratio; + } else if (angle <= 2 * PI + Configuration.EPSILON) { + double ratio = (angle - BOTTOM_RESIDUE_MAX_ANGLE) / (PI / 2); + y = species.getY() + species.getHeight() * (1 - ratio); + x = species.getX() + species.getWidth(); + } else { + throw new InvalidStateException(); + } + Point2D center = species.getCenter(); + double correctedAngle = -Math.atan2((y - center.getY()), (x - center.getX())); + result = getPointCoordinatesOnBorder(species, correctedAngle); + } + return result; + + } + + @Override + public Double getAngleForPoint(T element, Point2D position) { + double result = -1; + Point2D pointOnBorder = getClosestPositionOnBorder(element, position); + + double epsilon = Configuration.EPSILON; + double distanceRight = Math.abs(pointOnBorder.getX() - element.getX() - element.getWidth()); + double distanceTop = Math.abs(pointOnBorder.getY() - element.getY()); + double distanceLeft = Math.abs(pointOnBorder.getX() - element.getX()); + double distanceBottom = Math.abs(pointOnBorder.getY() - element.getY() - element.getHeight()); + + double minDist = Math.min(Math.min(distanceLeft, distanceRight), Math.min(distanceTop, distanceBottom)); + + if (distanceRight == minDist && + pointOnBorder.getY() - element.getY() - element.getHeight() / 2 < epsilon) { + double ratio = 1 - (pointOnBorder.getY() - element.getY()) / element.getHeight(); + result = (ratio - 0.5) * (PI / 2); + } else if (distanceTop == minDist) { + double ratio = 1 - (pointOnBorder.getX() - element.getX()) / element.getWidth(); + result = ratio * (PI / 2) + RIGHT_TOP_RESIDUE_MAX_ANGLE; + } else if (distanceLeft == minDist) { + double ratio = (pointOnBorder.getY() - element.getY()) / element.getHeight(); + result = ratio * (PI / 2) + TOP_RESIDUE_MAX_ANGLE; + } else if (distanceBottom == minDist) { + double ratio = (pointOnBorder.getX() - element.getX()) / element.getWidth(); + result = ratio * (PI / 2) + LEFT_RESIDUE_MAX_ANGLE; + } else if (distanceRight == minDist && + pointOnBorder.getY() - element.getY() - element.getHeight() < epsilon) { + double ratio = 1 - (pointOnBorder.getY() - element.getY()) / element.getHeight(); + result = ratio * (PI / 2) + BOTTOM_RESIDUE_MAX_ANGLE; + } else { + result = PI / 2; + logger.warn("Problem with finding angle. Using default"); + } + + return result; + } + + @Override + public Double getCellDesignerPositionByCoordinates(ModificationResidue mr) { + return null; + } + + @Override + public Point2D getCoordinatesByPosition(Element element, Double pos) { + return this.getCoordinatesByPosition(element, pos, 0.0); + } + + @Override + public Point2D getCoordinatesByPosition(Element element, Double pos, Double width) { + throw new NotImplementedException("Not implemented for: " + this.getClass()); + } + + @Override + public Double getCellDesignerSize(ModificationResidue mr) { + throw new NotImplementedException("Not implemented for: " + this.getClass()); + } + + @Override + public Double getWidthBySize(Element element, Double size) { + throw new NotImplementedException("Not implemented for: " + this.getClass()); + } + /** * This method computes coordinates that should be associated with the angle on * the border of the alias. - * + * * @param alias * alias to be investigated * @param angle @@ -171,7 +274,7 @@ public abstract class AbstractCellDesignerAliasConverter<T extends Element> impl /** * This method returns border of the alias as a PathIterator. - * + * * @param alias * object for which we want to find a border * @return border of the alias @@ -180,7 +283,7 @@ public abstract class AbstractCellDesignerAliasConverter<T extends Element> impl /** * Checks if anchor is valid for the alias to find a point on the border. - * + * * @param alias * object to be checked * @param anchor @@ -267,66 +370,9 @@ public abstract class AbstractCellDesignerAliasConverter<T extends Element> impl return sbgn; } - /** - * Returns coordinates on the {@link Species} border for given angle for - * residues. - * - * @param species - * object on border which the point is looked for - * @param angle - * CellDEsigner specific angle defining coordinates (;/) - * @return coordinates on the alias border that correspond to the angle - */ - @Override - public Point2D getResidueCoordinates(final T species, double angle) { - Point2D result = null; - if (species.getWidth() == 0 && species.getHeight() == 0) { - result = species.getCenter(); - } else { - double x = 0; - double y = 0; - while (angle > 2 * PI) { - angle -= 2 * PI; - } - while (angle < 0) { - angle += 2 * PI; - } - if (angle < RIGHT_TOP_RESIDUE_MAX_ANGLE) { - // CHECKSTYLE:OFF 0.5 is much readable than any other suggestion - double ratio = 0.5 + angle / (PI / 2); - // CHECKSTYLE:ON - x = species.getX() + species.getWidth(); - y = species.getY() + species.getHeight() * (1 - ratio); - } else if (angle < TOP_RESIDUE_MAX_ANGLE) { - double ratio = (angle - RIGHT_TOP_RESIDUE_MAX_ANGLE) / (PI / 2); - y = species.getY(); - x = species.getX() + species.getWidth() * (1 - ratio); - } else if (angle < LEFT_RESIDUE_MAX_ANGLE) { - double ratio = (angle - TOP_RESIDUE_MAX_ANGLE) / (PI / 2); - y = species.getY() + species.getHeight() * (ratio); - x = species.getX(); - } else if (angle < BOTTOM_RESIDUE_MAX_ANGLE) { - double ratio = (angle - LEFT_RESIDUE_MAX_ANGLE) / (PI / 2); - y = species.getY() + species.getHeight(); - x = species.getX() + species.getWidth() * ratio; - } else if (angle <= 2 * PI + Configuration.EPSILON) { - double ratio = (angle - BOTTOM_RESIDUE_MAX_ANGLE) / (PI / 2); - y = species.getY() + species.getHeight() * (1 - ratio); - x = species.getX() + species.getWidth(); - } else { - throw new InvalidStateException(); - } - Point2D center = species.getCenter(); - double correctedAngle = -Math.atan2((y - center.getY()), (x - center.getX())); - result = getPointCoordinatesOnBorder(species, correctedAngle); - } - return result; - - } - /** * Returns coordinates on the {@link Element} border for given angle. - * + * * @param elemnt * {@link Element} on border which the point is looked for * @param angle @@ -352,44 +398,6 @@ public abstract class AbstractCellDesignerAliasConverter<T extends Element> impl } - @Override - public Double getAngleForPoint(T element, Point2D position) { - double result = -1; - Point2D pointOnBorder = getClosestPositionOnBorder(element, position); - - double epsilon = Configuration.EPSILON; - double distanceRight = Math.abs(pointOnBorder.getX() - element.getX() - element.getWidth()); - double distanceTop = Math.abs(pointOnBorder.getY() - element.getY()); - double distanceLeft = Math.abs(pointOnBorder.getX() - element.getX()); - double distanceBottom = Math.abs(pointOnBorder.getY() - element.getY() - element.getHeight()); - - double minDist = Math.min(Math.min(distanceLeft, distanceRight), Math.min(distanceTop, distanceBottom)); - - if (distanceRight == minDist && - pointOnBorder.getY() - element.getY() - element.getHeight() / 2 < epsilon) { - double ratio = 1 - (pointOnBorder.getY() - element.getY()) / element.getHeight(); - result = (ratio - 0.5) * (PI / 2); - } else if (distanceTop == minDist) { - double ratio = 1 - (pointOnBorder.getX() - element.getX()) / element.getWidth(); - result = ratio * (PI / 2) + RIGHT_TOP_RESIDUE_MAX_ANGLE; - } else if (distanceLeft == minDist) { - double ratio = (pointOnBorder.getY() - element.getY()) / element.getHeight(); - result = ratio * (PI / 2) + TOP_RESIDUE_MAX_ANGLE; - } else if (distanceBottom == minDist) { - double ratio = (pointOnBorder.getX() - element.getX()) / element.getWidth(); - result = ratio * (PI / 2) + LEFT_RESIDUE_MAX_ANGLE; - } else if (distanceRight == minDist && - pointOnBorder.getY() - element.getY() - element.getHeight() < epsilon) { - double ratio = 1 - (pointOnBorder.getY() - element.getY()) / element.getHeight(); - result = ratio * (PI / 2) + BOTTOM_RESIDUE_MAX_ANGLE; - } else { - result = PI / 2; - logger.warn("Problem with finding angle. Using default"); - } - - return result; - } - private Point2D getClosestPositionOnBorder(T element, Point2D position) { double correctedAngle = -Math.atan2((position.getY() - element.getCenterY()), (position.getX() - element.getCenterX())); @@ -414,29 +422,4 @@ public abstract class AbstractCellDesignerAliasConverter<T extends Element> impl return pointOnBorder; } - @Override - public Double getCellDesignerPositionByCoordinates(ModificationResidue mr) { - return null; - } - - @Override - public Point2D getCoordinatesByPosition(Element element, Double pos) { - return this.getCoordinatesByPosition(element, pos, 0.0); - } - - @Override - public Point2D getCoordinatesByPosition(Element element, Double pos, Double width) { - throw new NotImplementedException("Not implemented for: " + this.getClass()); - } - - @Override - public Double getCellDesignerSize(ModificationResidue mr) { - throw new NotImplementedException("Not implemented for: " + this.getClass()); - } - - @Override - public Double getWidthBySize(Element element, Double size) { - throw new NotImplementedException("Not implemented for: " + this.getClass()); - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverter.java index 613c3b51b2..a30af25d86 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverter.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; import java.util.ArrayList; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -22,9 +19,15 @@ import lcsb.mapviewer.model.map.species.field.ModificationResidue; */ public class AntisenseRnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Species> { + /** + * How big should be the arc in rectangle for nucleic acid feature + * representation. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 5; + /** * Default constructor. - * + * * @param sbgn * Should the converter use sbgn standard */ @@ -32,12 +35,6 @@ public class AntisenseRnaCellDesignerAliasConverter extends AbstractCellDesigner super(sbgn); } - /** - * How big should be the arc in rectangle for nucleic acid feature - * representation. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 5; - @Override public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { if (invalidAnchorPosition(alias, anchor)) { @@ -51,6 +48,32 @@ public class AntisenseRnaCellDesignerAliasConverter extends AbstractCellDesigner return getPolygonTransformation().getPointOnPolygonByAnchor(points, anchor); } + @Override + public Double getCellDesignerPositionByCoordinates(ModificationResidue mr) { + return (mr.getPosition().getX() - mr.getSpecies().getX()) / (mr.getSpecies().getWidth() * 3.0 / 4.0); + } + + @Override + public Point2D getCoordinatesByPosition(Element element, Double pos, Double width) { + double x = element.getX() + element.getWidth() * 3.0 / 4.0 * pos; + x = Math.max(element.getX() + width / 2, x); + x = Math.min(element.getX() + element.getWidth() * 3.0 / 4.0 - width / 2, x); + return new Point2D.Double(x, element.getY()); + } + + @Override + public Double getCellDesignerSize(ModificationResidue mr) { + if (mr instanceof AbstractRegionModification) { + return ((AbstractRegionModification) mr).getWidth() / (mr.getSpecies().getWidth() * 3.0 / 4.0); + } + throw new NotImplementedException("Not implemented for: " + this.getClass() + ", " + mr.getClass()); + } + + @Override + public Double getWidthBySize(Element element, Double size) { + return size * (element.getWidth() * 3.0 / 4.0); + } + @Override protected PathIterator getBoundPathIterator(Species alias) { return getAntisebseRnaPath(alias).getPathIterator(new AffineTransform()); @@ -58,7 +81,7 @@ public class AntisenseRnaCellDesignerAliasConverter extends AbstractCellDesigner /** * Returns shape of the AntisenseRna as a list of points. - * + * * @param alias * alias for which we are looking for a border * @return list of points defining border of the given alias @@ -85,7 +108,7 @@ public class AntisenseRnaCellDesignerAliasConverter extends AbstractCellDesigner /** * Returns shape of the AntisenseRna as a GeneralPath object. - * + * * @param alias * alias for which we are looking for a border * @return GeneralPath object defining border of the given alias @@ -117,30 +140,4 @@ public class AntisenseRnaCellDesignerAliasConverter extends AbstractCellDesigner return path; } - @Override - public Double getCellDesignerPositionByCoordinates(ModificationResidue mr) { - return (mr.getPosition().getX() - mr.getSpecies().getX()) / (mr.getSpecies().getWidth() * 3.0 / 4.0); - } - - @Override - public Point2D getCoordinatesByPosition(Element element, Double pos, Double width) { - double x = element.getX() + element.getWidth() * 3.0 / 4.0 * pos; - x = Math.max(element.getX() + width / 2, x); - x = Math.min(element.getX() + element.getWidth() * 3.0 / 4.0 - width / 2, x); - return new Point2D.Double(x, element.getY()); - } - - @Override - public Double getCellDesignerSize(ModificationResidue mr) { - if (mr instanceof AbstractRegionModification) { - return ((AbstractRegionModification) mr).getWidth() / (mr.getSpecies().getWidth() * 3.0 / 4.0); - } - throw new NotImplementedException("Not implemented for: " + this.getClass() + ", " + mr.getClass()); - } - - @Override - public Double getWidthBySize(Element element, Double size) { - return size * (element.getWidth() * 3.0 / 4.0); - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverter.java index 6fd5c93ca8..16f9f42479 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/CellDesignerAliasConverter.java @@ -2,24 +2,14 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -43,11 +33,28 @@ public class CellDesignerAliasConverter implements ICellDesignerAliasConverter<E * Class helping with transforming objects into meaningful identifiers. */ private static ElementUtils eu = new ElementUtils(); + /** + * Converter used for operations on the {@link Element} given in constructor. + */ + @SuppressWarnings("rawtypes") + private ICellDesignerAliasConverter converter = null; + + /** + * Default constructor. + * + * @param sbgn + * Should the converter use SBGN standard + * @param element + * element for which this converter will be used + */ + public CellDesignerAliasConverter(Element element, boolean sbgn) { + converter = getConverterForAlias(element, sbgn); + } /** * Returns a converter for given {@link Element}. If converter doesn't exist * exception is thrown. - * + * * @param element * element for which we are looking for a converter * @param sbgn @@ -85,24 +92,6 @@ public class CellDesignerAliasConverter implements ICellDesignerAliasConverter<E } } - /** - * Converter used for operations on the {@link Element} given in constructor. - */ - @SuppressWarnings("rawtypes") - private ICellDesignerAliasConverter converter = null; - - /** - * Default constructor. - * - * @param sbgn - * Should the converter use SBGN standard - * @param element - * element for which this converter will be used - */ - public CellDesignerAliasConverter(Element element, boolean sbgn) { - converter = getConverterForAlias(element, sbgn); - } - @SuppressWarnings("unchecked") @Override public CellDesignerAnchor getAnchorForCoordinates(Element element, Point2D point) { @@ -123,14 +112,14 @@ public class CellDesignerAliasConverter implements ICellDesignerAliasConverter<E @SuppressWarnings("unchecked") @Override - public Double getAngleForPoint(Element element, Point2D position) { - return converter.getAngleForPoint(element, position); + public Point2D getResidueCoordinates(Element species, double angle) { + return converter.getResidueCoordinates(species, angle); } @SuppressWarnings("unchecked") @Override - public Point2D getResidueCoordinates(Element species, double angle) { - return converter.getResidueCoordinates(species, angle); + public Double getAngleForPoint(Element element, Point2D position) { + return converter.getAngleForPoint(element, position); } @Override @@ -143,6 +132,11 @@ public class CellDesignerAliasConverter implements ICellDesignerAliasConverter<E return converter.getCoordinatesByPosition(element, pos); } + @Override + public Point2D getCoordinatesByPosition(Element element, Double pos, Double width) { + return converter.getCoordinatesByPosition(element, pos, width); + } + @Override public Double getCellDesignerSize(ModificationResidue mr) { return converter.getCellDesignerSize(mr); @@ -153,9 +147,4 @@ public class CellDesignerAliasConverter implements ICellDesignerAliasConverter<E return converter.getWidthBySize(element, size); } - @Override - public Point2D getCoordinatesByPosition(Element element, Double pos, Double width) { - return converter.getCoordinatesByPosition(element, pos, width); - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexCellDesignerAliasConverter.java index f3de602426..6061140387 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexCellDesignerAliasConverter.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; -import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Complex; +import lcsb.mapviewer.model.map.species.Element; /** * Class that provides CellDesigner specific graphical information for @@ -18,53 +15,54 @@ import lcsb.mapviewer.model.map.species.Complex; */ public class ComplexCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Complex> { - /** - * Default constructor. - * - * @param sbgn - * Should the converter use sbgn standard - */ - protected ComplexCellDesignerAliasConverter(boolean sbgn) { - super(sbgn); - } + /** + * How big is the triangle trimmed part of the complex. + */ + private static final int TRIMMED_CORNER_SIZE = 5; - /** - * How big is the triangle trimmed part of the complex. - */ - private static final int TRIMMED_CORNER_SIZE = 5; + /** + * Default constructor. + * + * @param sbgn + * Should the converter use sbgn standard + */ + protected ComplexCellDesignerAliasConverter(boolean sbgn) { + super(sbgn); + } - @Override - public Point2D getPointCoordinates(Complex alias, CellDesignerAnchor anchor) { - if (invalidAnchorPosition(alias, anchor)) { - return alias.getCenter(); - } - return getRectangleTransformation().getPointOnRectangleByAnchor(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), anchor); - } + @Override + public Point2D getPointCoordinates(Complex alias, CellDesignerAnchor anchor) { + if (invalidAnchorPosition(alias, anchor)) { + return alias.getCenter(); + } + return getRectangleTransformation().getPointOnRectangleByAnchor(alias.getX(), alias.getY(), alias.getWidth(), + alias.getHeight(), anchor); + } - @Override - public PathIterator getBoundPathIterator(Complex alias) { - return getAliasPath(alias).getPathIterator(new AffineTransform()); - } + @Override + public PathIterator getBoundPathIterator(Complex alias) { + return getAliasPath(alias).getPathIterator(new AffineTransform()); + } - /** - * Returns the border of complex alias. - * - * @param alias - * exact object for which we want to get a border - * @return border of the alias - */ - private GeneralPath getAliasPath(Element alias) { - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - path.moveTo(alias.getX() + TRIMMED_CORNER_SIZE, alias.getY()); - path.lineTo(alias.getX() + alias.getWidth() - TRIMMED_CORNER_SIZE, alias.getY()); - path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + TRIMMED_CORNER_SIZE); - path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight() - TRIMMED_CORNER_SIZE); - path.lineTo(alias.getX() + alias.getWidth() - TRIMMED_CORNER_SIZE, alias.getY() + alias.getHeight()); - path.lineTo(alias.getX() + TRIMMED_CORNER_SIZE, alias.getY() + alias.getHeight()); - path.lineTo(alias.getX(), alias.getY() + alias.getHeight() - TRIMMED_CORNER_SIZE); - path.lineTo(alias.getX(), alias.getY() + TRIMMED_CORNER_SIZE); - path.closePath(); - return path; - } + /** + * Returns the border of complex alias. + * + * @param alias + * exact object for which we want to get a border + * @return border of the alias + */ + private GeneralPath getAliasPath(Element alias) { + GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); + path.moveTo(alias.getX() + TRIMMED_CORNER_SIZE, alias.getY()); + path.lineTo(alias.getX() + alias.getWidth() - TRIMMED_CORNER_SIZE, alias.getY()); + path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + TRIMMED_CORNER_SIZE); + path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight() - TRIMMED_CORNER_SIZE); + path.lineTo(alias.getX() + alias.getWidth() - TRIMMED_CORNER_SIZE, alias.getY() + alias.getHeight()); + path.lineTo(alias.getX() + TRIMMED_CORNER_SIZE, alias.getY() + alias.getHeight()); + path.lineTo(alias.getX(), alias.getY() + alias.getHeight() - TRIMMED_CORNER_SIZE); + path.lineTo(alias.getX(), alias.getY() + TRIMMED_CORNER_SIZE); + path.closePath(); + return path; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverter.java index 3c3a031e06..b76fb57f5f 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverter.java @@ -17,91 +17,91 @@ import lcsb.mapviewer.model.map.species.Species; */ public class DegradedCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Species> { - /** - * Default constructor. - * - * @param sbgn - * Should the converter use sbgn standard - */ - protected DegradedCellDesignerAliasConverter(boolean sbgn) { - super(sbgn); - } + /** + * Part of height of the line used to cross degraded circle that goes behind + * this circle. + */ + private static final int DEGRADED_MARGIN = 7; - /** - * Part of height of the line used to cross degraded circle that goes behind - * this circle. - */ - private static final int DEGRADED_MARGIN = 7; + /** + * Default constructor. + * + * @param sbgn + * Should the converter use sbgn standard + */ + protected DegradedCellDesignerAliasConverter(boolean sbgn) { + super(sbgn); + } - @Override - public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { - double diameter = getDiameter(alias); - double x = getXCoord(alias, diameter); - double y = getYCoord(alias); - if (invalidAnchorPosition(alias, anchor)) { - return alias.getCenter(); - } + @Override + public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { + double diameter = getDiameter(alias); + double x = getXCoord(alias, diameter); + double y = getYCoord(alias); + if (invalidAnchorPosition(alias, anchor)) { + return alias.getCenter(); + } - return getEllipseTransformation().getPointOnEllipseByAnchor(x, y, diameter, diameter, anchor); - } + return getEllipseTransformation().getPointOnEllipseByAnchor(x, y, diameter, diameter, anchor); + } - /** - * Returns transformed y coordinate for the degraded alias. - * - * @param alias - * object alias to to which we are looking for y coordinate - * @return y coordinate of the alias - */ - private double getYCoord(Element alias) { - double y = alias.getY() + DEGRADED_MARGIN; - return y; - } + @Override + public Point2D getAnchorPointCoordinates(Species alias, double angle) { + if (alias.getWidth() == 0 && alias.getHeight() == 0) { + return alias.getCenter(); + } + double diameter = getDiameter(alias); + double x = getXCoord(alias, diameter); + double y = getYCoord(alias); + Point2D result = getEllipseTransformation().getPointOnEllipseByRadian(x, y, diameter, diameter, angle); + return result; - /** - * Returns transformed x coordinate for the degraded alias. - * - * @param alias - * object alias to to which we are looking for x coordinate - * @param diameter - * diameter of cross line used in this alias - * @return x coordinate of the alias - */ - private double getXCoord(Element alias, double diameter) { - double x = alias.getX() + (alias.getWidth() - diameter) / 2; - return x; - } + } - /** - * Computes diameter of cross line for the degraded alias. - * - * @param alias - * object alias to to which we are looking for diameter. - * @return diameter of the cross line - */ - private double getDiameter(Element alias) { - double diameter = Math.min(alias.getWidth(), alias.getHeight()) - 2 * DEGRADED_MARGIN; - if (diameter < 0) { - diameter = 0; - } - return diameter; - } + @Override + public PathIterator getBoundPathIterator(Species alias) { + throw new NotImplementedException("This class doesn't have bound"); + } - @Override - public Point2D getAnchorPointCoordinates(Species alias, double angle) { - if (alias.getWidth() == 0 && alias.getHeight() == 0) { - return alias.getCenter(); - } - double diameter = getDiameter(alias); - double x = getXCoord(alias, diameter); - double y = getYCoord(alias); - Point2D result = getEllipseTransformation().getPointOnEllipseByRadian(x, y, diameter, diameter, angle); - return result; + /** + * Returns transformed y coordinate for the degraded alias. + * + * @param alias + * object alias to to which we are looking for y coordinate + * @return y coordinate of the alias + */ + private double getYCoord(Element alias) { + double y = alias.getY() + DEGRADED_MARGIN; + return y; + } - } + /** + * Returns transformed x coordinate for the degraded alias. + * + * @param alias + * object alias to to which we are looking for x coordinate + * @param diameter + * diameter of cross line used in this alias + * @return x coordinate of the alias + */ + private double getXCoord(Element alias, double diameter) { + double x = alias.getX() + (alias.getWidth() - diameter) / 2; + return x; + } - @Override - public PathIterator getBoundPathIterator(Species alias) { - throw new NotImplementedException("This class doesn't have bound"); - } + /** + * Computes diameter of cross line for the degraded alias. + * + * @param alias + * object alias to to which we are looking for diameter. + * @return diameter of the cross line + */ + private double getDiameter(Element alias) { + double diameter = Math.min(alias.getWidth(), alias.getHeight()) - 2 * DEGRADED_MARGIN; + if (diameter < 0) { + diameter = 0; + } + return diameter; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DrugCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DrugCellDesignerAliasConverter.java index 837c81674f..50ea67ccec 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DrugCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DrugCellDesignerAliasConverter.java @@ -1,10 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.RoundRectangle2D; +import java.awt.*; +import java.awt.geom.*; import java.util.ArrayList; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -20,73 +17,74 @@ import lcsb.mapviewer.model.map.species.Species; */ public class DrugCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Species> { - /** - * Default constructor. - * - * @param sbgn - * Should the converter use sbgn standard - */ - protected DrugCellDesignerAliasConverter(boolean sbgn) { - super(sbgn); - } + /** + * How big should be the arc in rectangle for drug representation. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 40; - /** - * How big should be the arc in rectangle for drug representation. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 40; + /** + * Default constructor. + * + * @param sbgn + * Should the converter use sbgn standard + */ + protected DrugCellDesignerAliasConverter(boolean sbgn) { + super(sbgn); + } - @Override - public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { - if (invalidAnchorPosition(alias, anchor)) { - return alias.getCenter(); - } - ArrayList<Point2D> list = getDrugPoints(alias); + @Override + public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { + if (invalidAnchorPosition(alias, anchor)) { + return alias.getCenter(); + } + ArrayList<Point2D> list = getDrugPoints(alias); - return getPolygonTransformation().getPointOnPolygonByAnchor(list, anchor); - } + return getPolygonTransformation().getPointOnPolygonByAnchor(list, anchor); + } - @Override - protected PathIterator getBoundPathIterator(Species alias) { - return getDrugShape(alias).getPathIterator(new AffineTransform()); - } + @Override + protected PathIterator getBoundPathIterator(Species alias) { + return getDrugShape(alias).getPathIterator(new AffineTransform()); + } - /** - * Returns shape of the Drug as a list of points. - * - * @param alias - * alias for which we are looking for a border - * @return list of points defining border of the given alias - */ - protected ArrayList<Point2D> getDrugPoints(Species alias) { - ArrayList<Point2D> list = new ArrayList<Point2D>(); + /** + * Returns shape of the Drug as a list of points. + * + * @param alias + * alias for which we are looking for a border + * @return list of points defining border of the given alias + */ + protected ArrayList<Point2D> getDrugPoints(Species alias) { + ArrayList<Point2D> list = new ArrayList<Point2D>(); - double x = alias.getX(); - double y = alias.getY(); - double width = alias.getWidth(); - double height = alias.getHeight(); + double x = alias.getX(); + double y = alias.getY(); + double width = alias.getWidth(); + double height = alias.getHeight(); - // CHECKSTYLE:OFF - list.add(new Point2D.Double(x, y + height / 2)); - list.add(new Point2D.Double(x + width / 12, y)); - list.add(new Point2D.Double(x + width / 2, y)); - list.add(new Point2D.Double(x + width * 11 / 12, y)); - list.add(new Point2D.Double(x + width, y + height / 2)); - list.add(new Point2D.Double(x + width * 11 / 12, y + height)); - list.add(new Point2D.Double(x + width / 2, y + height)); - list.add(new Point2D.Double(x + width / 12, y + height)); - // CHECKSTYLE:ON - return list; - } + // CHECKSTYLE:OFF + list.add(new Point2D.Double(x, y + height / 2)); + list.add(new Point2D.Double(x + width / 12, y)); + list.add(new Point2D.Double(x + width / 2, y)); + list.add(new Point2D.Double(x + width * 11 / 12, y)); + list.add(new Point2D.Double(x + width, y + height / 2)); + list.add(new Point2D.Double(x + width * 11 / 12, y + height)); + list.add(new Point2D.Double(x + width / 2, y + height)); + list.add(new Point2D.Double(x + width / 12, y + height)); + // CHECKSTYLE:ON + return list; + } - /** - * Returns shape of the Drug. - * - * @param alias - * alias for which we are looking for a border - * @return Shape object defining given alias - */ - private Shape getDrugShape(Element alias) { - return new RoundRectangle2D.Double(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), RECTANGLE_CORNER_ARC_SIZE, RECTANGLE_CORNER_ARC_SIZE); - } + /** + * Returns shape of the Drug. + * + * @param alias + * alias for which we are looking for a border + * @return Shape object defining given alias + */ + private Shape getDrugShape(Element alias) { + return new RoundRectangle2D.Double(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), + RECTANGLE_CORNER_ARC_SIZE, RECTANGLE_CORNER_ARC_SIZE); + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverter.java index ca1c3240d1..42f1a5d048 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverter.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -25,6 +22,11 @@ import lcsb.mapviewer.model.map.species.field.ModificationResidue; */ public class GeneCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Gene> { + /** + * How big should be the arc in rectangle for nucleic acid feature + * representation. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 5; /** * Default class logger */ @@ -33,7 +35,7 @@ public class GeneCellDesignerAliasConverter extends AbstractCellDesignerAliasCon /** * Default constructor. - * + * * @param sbgn * Should the converter use SBGN standard */ @@ -41,12 +43,6 @@ public class GeneCellDesignerAliasConverter extends AbstractCellDesignerAliasCon super(sbgn); } - /** - * How big should be the arc in rectangle for nucleic acid feature - * representation. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 5; - @Override public Point2D getPointCoordinates(Gene alias, CellDesignerAnchor anchor) { if (invalidAnchorPosition(alias, anchor)) { @@ -56,34 +52,6 @@ public class GeneCellDesignerAliasConverter extends AbstractCellDesignerAliasCon alias.getHeight(), anchor); } - /** - * Shape representation of the gene alias. - * - * @param alias - * alias for which we are looking for a Shape - * @return Shape object that represents alias - */ - private Shape getGeneShape(Element alias) { - if (!isSbgn()) { - Shape shape; - shape = new Rectangle2D.Double(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight()); - return shape; - } else { - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - double x = alias.getX(), y = alias.getY(), width = alias.getWidth(), height = alias.getHeight(); - - path.moveTo(x, y); - path.lineTo(x, y + height - RECTANGLE_CORNER_ARC_SIZE); - path.curveTo(x, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height); - path.lineTo(x + width - RECTANGLE_CORNER_ARC_SIZE, y + height); - path.curveTo(x + width, y + height, x + width, y + height - RECTANGLE_CORNER_ARC_SIZE, x + width, - y + height - RECTANGLE_CORNER_ARC_SIZE); - path.lineTo(x + width, y); - path.closePath(); - return path; - } - } - @Override public PathIterator getBoundPathIterator(Gene alias) { return getGeneShape(alias).getPathIterator(new AffineTransform()); @@ -120,4 +88,32 @@ public class GeneCellDesignerAliasConverter extends AbstractCellDesignerAliasCon return size * element.getWidth(); } + /** + * Shape representation of the gene alias. + * + * @param alias + * alias for which we are looking for a Shape + * @return Shape object that represents alias + */ + private Shape getGeneShape(Element alias) { + if (!isSbgn()) { + Shape shape; + shape = new Rectangle2D.Double(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight()); + return shape; + } else { + GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); + double x = alias.getX(), y = alias.getY(), width = alias.getWidth(), height = alias.getHeight(); + + path.moveTo(x, y); + path.lineTo(x, y + height - RECTANGLE_CORNER_ARC_SIZE); + path.curveTo(x, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height); + path.lineTo(x + width - RECTANGLE_CORNER_ARC_SIZE, y + height); + path.curveTo(x + width, y + height, x + width, y + height - RECTANGLE_CORNER_ARC_SIZE, x + width, + y + height - RECTANGLE_CORNER_ARC_SIZE); + path.lineTo(x + width, y); + path.closePath(); + return path; + } + } + } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverter.java index 50d1975f81..dc97aa6f44 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverter.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -43,9 +44,41 @@ public class IonCellDesignerAliasConverter extends AbstractCellDesignerAliasConv return getEllipseTransformation().getPointOnEllipseByAnchor(x, y, diameter, diameter, anchor); } + @Override + public Point2D getAnchorPointCoordinates(Ion alias, double angle) { + if (alias.getWidth() == 0 && alias.getHeight() == 0) { + return alias.getCenter(); + } + double diameter = getDiameter(alias); + double x = getXCoord(alias, diameter); + double y = getYCoord(alias); + Point2D result = getEllipseTransformation().getPointOnEllipseByRadian(x, y, diameter, diameter, angle); + return result; + + } + + @Override + protected PathIterator getBoundPathIterator(Ion alias) { + throw new NotImplementedException("This class doesn't have bound"); + } + + @Override + public Point2D getPointCoordinatesOnBorder(Ion ion, final double angle) { + if (ion.getWidth() == 0 && ion.getHeight() == 0) { + logger.warn("Looking for coordinates for the alias with 0 size"); + return ion.getCenter(); + } + double diameter = getDiameter(ion); + double x = getXCoord(ion, diameter); + double y = getYCoord(ion); + Point2D result = getEllipseTransformation().getPointOnEllipseByRadian(x, y, diameter, diameter, angle); + return result; + + } + /** * Returns transformed y coordinate for the ion alias. - * + * * @param alias * object alias to to which we are looking for y coordinate * @return y coordinate of the alias @@ -57,7 +90,7 @@ public class IonCellDesignerAliasConverter extends AbstractCellDesignerAliasConv /** * Returns transformed x coordinate for the ion alias. - * + * * @param alias * object alias to to which we are looking for x coordinate * @param diameter @@ -71,7 +104,7 @@ public class IonCellDesignerAliasConverter extends AbstractCellDesignerAliasConv /** * Returns diameter of the ion alias. - * + * * @param alias * object alias to to which we are looking for diameter. * @return diameter of the alias @@ -83,36 +116,4 @@ public class IonCellDesignerAliasConverter extends AbstractCellDesignerAliasConv } return diameter; } - - @Override - public Point2D getAnchorPointCoordinates(Ion alias, double angle) { - if (alias.getWidth() == 0 && alias.getHeight() == 0) { - return alias.getCenter(); - } - double diameter = getDiameter(alias); - double x = getXCoord(alias, diameter); - double y = getYCoord(alias); - Point2D result = getEllipseTransformation().getPointOnEllipseByRadian(x, y, diameter, diameter, angle); - return result; - - } - - @Override - protected PathIterator getBoundPathIterator(Ion alias) { - throw new NotImplementedException("This class doesn't have bound"); - } - - @Override - public Point2D getPointCoordinatesOnBorder(Ion ion, final double angle) { - if (ion.getWidth() == 0 && ion.getHeight() == 0) { - logger.warn("Looking for coordinates for the alias with 0 size"); - return ion.getCenter(); - } - double diameter = getDiameter(ion); - double x = getXCoord(ion, diameter); - double y = getYCoord(ion); - Point2D result = getEllipseTransformation().getPointOnEllipseByRadian(x, y, diameter, diameter, angle); - return result; - - } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/PhenotypeCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/PhenotypeCellDesignerAliasConverter.java index c09fbbb901..861323e2c5 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/PhenotypeCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/PhenotypeCellDesignerAliasConverter.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; import java.util.ArrayList; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -19,76 +16,76 @@ import lcsb.mapviewer.model.map.species.Species; */ public class PhenotypeCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Species> { - /** - * Default constructor. - * - * @param sbgn - * Should the converter use sbgn standard - */ - protected PhenotypeCellDesignerAliasConverter(boolean sbgn) { - super(sbgn); - } + /** + * Default constructor. + * + * @param sbgn + * Should the converter use sbgn standard + */ + protected PhenotypeCellDesignerAliasConverter(boolean sbgn) { + super(sbgn); + } - @Override - public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { - if (invalidAnchorPosition(alias, anchor)) { - return alias.getCenter(); - } - return getPolygonTransformation().getPointOnPolygonByAnchor(getPointsForAlias(alias), anchor); - } + @Override + public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { + if (invalidAnchorPosition(alias, anchor)) { + return alias.getCenter(); + } + return getPolygonTransformation().getPointOnPolygonByAnchor(getPointsForAlias(alias), anchor); + } - /** - * Returns shape of the Phenotype as a list of points. - * - * @param alias - * alias for which we are looking for a border - * @return list of points defining border of the given alias - */ - private ArrayList<Point2D> getPointsForAlias(Element alias) { - ArrayList<Point2D> list = new ArrayList<Point2D>(); + @Override + public PathIterator getBoundPathIterator(Species alias) { + return getPhenotypePath(alias).getPathIterator(new AffineTransform()); + } - double x = alias.getX(); - double y = alias.getY(); - double width = alias.getWidth(); - double height = alias.getHeight(); + /** + * Returns shape of the Phenotype as a list of points. + * + * @param alias + * alias for which we are looking for a border + * @return list of points defining border of the given alias + */ + private ArrayList<Point2D> getPointsForAlias(Element alias) { + ArrayList<Point2D> list = new ArrayList<Point2D>(); - // CHECKSTYLE:OFF - list.add(new Point2D.Double(x, y + height / 2)); - list.add(new Point2D.Double(x + width / 6, y)); - list.add(new Point2D.Double(x + width / 2, y)); - list.add(new Point2D.Double(x + width * 5 / 6, y)); - list.add(new Point2D.Double(x + width, y + height / 2)); - list.add(new Point2D.Double(x + width * 5 / 6, y + height)); - list.add(new Point2D.Double(x + width / 2, y + height)); - list.add(new Point2D.Double(x + width / 6, y + height)); - // CHECKSTYLE:ON - return list; - } + double x = alias.getX(); + double y = alias.getY(); + double width = alias.getWidth(); + double height = alias.getHeight(); - @Override - public PathIterator getBoundPathIterator(Species alias) { - return getPhenotypePath(alias).getPathIterator(new AffineTransform()); - } + // CHECKSTYLE:OFF + list.add(new Point2D.Double(x, y + height / 2)); + list.add(new Point2D.Double(x + width / 6, y)); + list.add(new Point2D.Double(x + width / 2, y)); + list.add(new Point2D.Double(x + width * 5 / 6, y)); + list.add(new Point2D.Double(x + width, y + height / 2)); + list.add(new Point2D.Double(x + width * 5 / 6, y + height)); + list.add(new Point2D.Double(x + width / 2, y + height)); + list.add(new Point2D.Double(x + width / 6, y + height)); + // CHECKSTYLE:ON + return list; + } - /** - * Returns shape of the Phenotype as a GeneralPath object. - * - * @param alias - * alias for which we are looking for a border - * @return GeneralPath object defining border of the given alias - */ - private GeneralPath getPhenotypePath(Element alias) { - // CHECKSTYLE:OFF - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 6); - path.moveTo(alias.getX() + alias.getWidth() / 6, alias.getY()); - path.lineTo(alias.getX() + alias.getWidth() * 5 / 6, alias.getY()); - path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight() / 2); - path.lineTo(alias.getX() + alias.getWidth() * 5 / 6, alias.getY() + alias.getHeight()); - path.lineTo(alias.getX() + alias.getWidth() / 6, alias.getY() + alias.getHeight()); - path.lineTo(alias.getX(), alias.getY() + alias.getHeight() / 2); - // CHECKSTYLE:ON - path.closePath(); - return path; - } + /** + * Returns shape of the Phenotype as a GeneralPath object. + * + * @param alias + * alias for which we are looking for a border + * @return GeneralPath object defining border of the given alias + */ + private GeneralPath getPhenotypePath(Element alias) { + // CHECKSTYLE:OFF + GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD, 6); + path.moveTo(alias.getX() + alias.getWidth() / 6, alias.getY()); + path.lineTo(alias.getX() + alias.getWidth() * 5 / 6, alias.getY()); + path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight() / 2); + path.lineTo(alias.getX() + alias.getWidth() * 5 / 6, alias.getY() + alias.getHeight()); + path.lineTo(alias.getX() + alias.getWidth() / 6, alias.getY() + alias.getHeight()); + path.lineTo(alias.getX(), alias.getY() + alias.getHeight() / 2); + // CHECKSTYLE:ON + path.closePath(); + return path; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverter.java index 858ca69689..fb8886282b 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverter.java @@ -1,23 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.RoundRectangle2D; +import java.awt.*; +import java.awt.geom.*; import java.util.ArrayList; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.TruncatedProtein; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.modelutils.map.ElementUtils; /** @@ -29,203 +21,207 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class ProteinCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Protein> { - /** - * Default constructor. - * - * @param sbgn - * Should the converter use sbgn standard - */ - protected ProteinCellDesignerAliasConverter(boolean sbgn) { - super(sbgn); - } - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(ProteinCellDesignerAliasConverter.class); - - /** - * How big should be the arc in rectangle for generic protein representation. - */ - private static final int GENERIC_PROTEIN_RECTANGLE_CORNER_ARC_SIZE = 10; - - /** - * Helps in providing human readable identifiers of elements for logging. - */ - private ElementUtils eu = new ElementUtils(); - - @Override - public Point2D getPointCoordinates(Protein alias, CellDesignerAnchor anchor) { - Point2D result = null; - if (invalidAnchorPosition(alias, anchor)) { - result = alias.getCenter(); - } else { - int homodir = alias.getHomodimer(); - - alias.setWidth(alias.getWidth() - AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); - alias.setHeight(alias.getHeight() - AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); - - if (alias instanceof GenericProtein) { - result = getRectangleTransformation().getPointOnRectangleByAnchor(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), anchor); - } else if (alias instanceof ReceptorProtein) { - ArrayList<Point2D> points = getReceptorPoints(alias); - result = getPolygonTransformation().getPointOnPolygonByAnchor(points, anchor); - } else if (alias instanceof IonChannelProtein) { - result = getRectangleTransformation().getPointOnRectangleByAnchor(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), anchor); - } else if (alias instanceof TruncatedProtein) { - ArrayList<Point2D> points = getTruncatedPoints(alias); - result = getPolygonTransformation().getPointOnPolygonByAnchor(points, anchor); - } else { - throw new NotImplementedException(eu.getElementTag(alias) + "Unknown type: " + alias.getClass()); - } - - alias.setWidth(alias.getWidth() + AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); - alias.setHeight(alias.getHeight() + AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); - } - return result; - } - - @Override - public PathIterator getBoundPathIterator(Protein alias) { - if (alias instanceof GenericProtein) { - return getGenericShape(alias).getPathIterator(new AffineTransform()); - } else if (alias instanceof ReceptorProtein) { - return getReceptorShape(alias).getPathIterator(new AffineTransform()); - } else if (alias instanceof IonChannelProtein) { - return getGenericShape(alias).getPathIterator(new AffineTransform()); - } else if (alias instanceof TruncatedProtein) { - return getTruncatedShape(alias).getPathIterator(new AffineTransform()); - } else { - throw new NotImplementedException(eu.getElementTag(alias) + "Not implemented protein converter for type: " + alias.getClass()); - } - } - - /** - * Returns shape of generic protein. - * - * @param alias - * alias for which we are looking for a border - * @return Shape object defining given alias - */ - private Shape getGenericShape(Element alias) { - return new RoundRectangle2D.Double( - alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), GENERIC_PROTEIN_RECTANGLE_CORNER_ARC_SIZE, GENERIC_PROTEIN_RECTANGLE_CORNER_ARC_SIZE); - } - - /** - * Returns shape of the Truncated protein as a list of points. - * - * @param alias - * alias for which we are looking for a border - * @return list of points defining border of the given alias - */ - private ArrayList<Point2D> getTruncatedPoints(Element alias) { - double x = alias.getX(); - double y = alias.getY(); - double width = alias.getWidth(); - double height = alias.getHeight(); - ArrayList<Point2D> points = new ArrayList<Point2D>(); - // CHECKSTYLE:OFF - points.add(new Point2D.Double(x, y + height / 2)); - points.add(new Point2D.Double(x, y + height / 4)); - points.add(new Point2D.Double(x, y)); - points.add(new Point2D.Double(x + width / 4, y)); - points.add(new Point2D.Double(x + width / 2, y)); - points.add(new Point2D.Double(x + width * 3 / 4, y)); - points.add(new Point2D.Double(x + width, y)); - points.add(new Point2D.Double(x + width, y + height * 3 / 10)); - points.add(new Point2D.Double(x + width, y + height * 3 / 5)); - points.add(new Point2D.Double(x + width * 4 / 5, y + height * 2 / 5)); - points.add(new Point2D.Double(x + width * 4 / 5, y + height * 7 / 10)); - points.add(new Point2D.Double(x + width * 4 / 5, y + height)); - points.add(new Point2D.Double(x + width / 2, y + height)); - points.add(new Point2D.Double(x + width / 4, y + height)); - points.add(new Point2D.Double(x, y + height)); - points.add(new Point2D.Double(x, y + height * 3 / 4)); - - // CHECKSTYLE:ON - - return points; - } - - /** - * Returns shape of receptor protein. - * - * @param alias - * alias for which we are looking for a border - * @return Shape object defining given alias - */ - protected Shape getReceptorShape(Element alias) { - Shape shape; - GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - ArrayList<Point2D> points = getReceptorPoints(alias); - path.moveTo(points.get(0).getX(), points.get(0).getY()); - for (int i = 1; i < points.size(); i++) { - path.lineTo(points.get(i).getX(), points.get(i).getY()); - } - path.closePath(); - shape = path; - return shape; - } - - /** - * Returns shape of truncated protein. - * - * @param alias - * alias for which we are looking for a border - * @return Shape object defining given alias - */ - protected Shape getTruncatedShape(Element alias) { - Shape shape; - GeneralPath path = new GeneralPath(); - - // CHECKSTYLE:OFF - path.moveTo(alias.getX() + 10, alias.getY()); - path.lineTo(alias.getX() + alias.getWidth(), alias.getY()); - path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight() * 3 / 5); - path.lineTo(alias.getX() + alias.getWidth() * 4 / 5, alias.getY() + alias.getHeight() * 2 / 5); - path.lineTo(alias.getX() + alias.getWidth() * 4 / 5, alias.getY() + alias.getHeight()); - path.lineTo(alias.getX() + 10, alias.getY() + alias.getHeight()); - path.curveTo( - alias.getX() + 5, alias.getY() + alias.getHeight() - 2, alias.getX() + 2, alias.getY() + alias.getHeight() - 5, alias.getX(), - alias.getY() + alias.getHeight() - 10); - path.lineTo(alias.getX(), alias.getY() + 10); - path.curveTo(alias.getX() + 2, alias.getY() + 5, alias.getX() + 5, alias.getY() + 2, alias.getX() + 10, alias.getY()); - - // CHECKSTYLE:ON - - path.closePath(); - shape = path; - return shape; - } - - /** - * Returns shape of receptor protein as a list of points. - * - * @param alias - * alias for which we are looking for a border - * @return list of points defining border of the given alias - */ - private ArrayList<Point2D> getReceptorPoints(Element alias) { - double x = alias.getX(); - double y = alias.getY(); - double width = alias.getWidth(); - double height = alias.getHeight(); - ArrayList<Point2D> points = new ArrayList<Point2D>(); - - // CHECKSTYLE:OFF - points.add(new Point2D.Double(x, y + height * 2 / 5)); - points.add(new Point2D.Double(x, y)); - points.add(new Point2D.Double(x + width / 2, y + height / 5)); - points.add(new Point2D.Double(x + width, y)); - points.add(new Point2D.Double(x + width, y + height * 2 / 5)); - points.add(new Point2D.Double(x + width, y + height * 4 / 5)); - points.add(new Point2D.Double(x + width / 2, y + height)); - points.add(new Point2D.Double(x, y + height * 4 / 5)); - // CHECKSTYLE:ON - - return points; - } + /** + * How big should be the arc in rectangle for generic protein representation. + */ + private static final int GENERIC_PROTEIN_RECTANGLE_CORNER_ARC_SIZE = 10; + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(ProteinCellDesignerAliasConverter.class); + /** + * Helps in providing human readable identifiers of elements for logging. + */ + private ElementUtils eu = new ElementUtils(); + + /** + * Default constructor. + * + * @param sbgn + * Should the converter use sbgn standard + */ + protected ProteinCellDesignerAliasConverter(boolean sbgn) { + super(sbgn); + } + + @Override + public Point2D getPointCoordinates(Protein alias, CellDesignerAnchor anchor) { + Point2D result = null; + if (invalidAnchorPosition(alias, anchor)) { + result = alias.getCenter(); + } else { + int homodir = alias.getHomodimer(); + + alias.setWidth(alias.getWidth() - AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); + alias.setHeight(alias.getHeight() - AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); + + if (alias instanceof GenericProtein) { + result = getRectangleTransformation().getPointOnRectangleByAnchor(alias.getX(), alias.getY(), alias.getWidth(), + alias.getHeight(), anchor); + } else if (alias instanceof ReceptorProtein) { + ArrayList<Point2D> points = getReceptorPoints(alias); + result = getPolygonTransformation().getPointOnPolygonByAnchor(points, anchor); + } else if (alias instanceof IonChannelProtein) { + result = getRectangleTransformation().getPointOnRectangleByAnchor(alias.getX(), alias.getY(), alias.getWidth(), + alias.getHeight(), anchor); + } else if (alias instanceof TruncatedProtein) { + ArrayList<Point2D> points = getTruncatedPoints(alias); + result = getPolygonTransformation().getPointOnPolygonByAnchor(points, anchor); + } else { + throw new NotImplementedException(eu.getElementTag(alias) + "Unknown type: " + alias.getClass()); + } + + alias.setWidth(alias.getWidth() + AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); + alias.setHeight(alias.getHeight() + AbstractCellDesignerAliasConverter.HOMODIMER_OFFSET * (homodir - 1)); + } + return result; + } + + @Override + public PathIterator getBoundPathIterator(Protein alias) { + if (alias instanceof GenericProtein) { + return getGenericShape(alias).getPathIterator(new AffineTransform()); + } else if (alias instanceof ReceptorProtein) { + return getReceptorShape(alias).getPathIterator(new AffineTransform()); + } else if (alias instanceof IonChannelProtein) { + return getGenericShape(alias).getPathIterator(new AffineTransform()); + } else if (alias instanceof TruncatedProtein) { + return getTruncatedShape(alias).getPathIterator(new AffineTransform()); + } else { + throw new NotImplementedException( + eu.getElementTag(alias) + "Not implemented protein converter for type: " + alias.getClass()); + } + } + + /** + * Returns shape of generic protein. + * + * @param alias + * alias for which we are looking for a border + * @return Shape object defining given alias + */ + private Shape getGenericShape(Element alias) { + return new RoundRectangle2D.Double( + alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight(), GENERIC_PROTEIN_RECTANGLE_CORNER_ARC_SIZE, + GENERIC_PROTEIN_RECTANGLE_CORNER_ARC_SIZE); + } + + /** + * Returns shape of the Truncated protein as a list of points. + * + * @param alias + * alias for which we are looking for a border + * @return list of points defining border of the given alias + */ + private ArrayList<Point2D> getTruncatedPoints(Element alias) { + double x = alias.getX(); + double y = alias.getY(); + double width = alias.getWidth(); + double height = alias.getHeight(); + ArrayList<Point2D> points = new ArrayList<Point2D>(); + // CHECKSTYLE:OFF + points.add(new Point2D.Double(x, y + height / 2)); + points.add(new Point2D.Double(x, y + height / 4)); + points.add(new Point2D.Double(x, y)); + points.add(new Point2D.Double(x + width / 4, y)); + points.add(new Point2D.Double(x + width / 2, y)); + points.add(new Point2D.Double(x + width * 3 / 4, y)); + points.add(new Point2D.Double(x + width, y)); + points.add(new Point2D.Double(x + width, y + height * 3 / 10)); + points.add(new Point2D.Double(x + width, y + height * 3 / 5)); + points.add(new Point2D.Double(x + width * 4 / 5, y + height * 2 / 5)); + points.add(new Point2D.Double(x + width * 4 / 5, y + height * 7 / 10)); + points.add(new Point2D.Double(x + width * 4 / 5, y + height)); + points.add(new Point2D.Double(x + width / 2, y + height)); + points.add(new Point2D.Double(x + width / 4, y + height)); + points.add(new Point2D.Double(x, y + height)); + points.add(new Point2D.Double(x, y + height * 3 / 4)); + + // CHECKSTYLE:ON + + return points; + } + + /** + * Returns shape of receptor protein. + * + * @param alias + * alias for which we are looking for a border + * @return Shape object defining given alias + */ + protected Shape getReceptorShape(Element alias) { + Shape shape; + GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD); + ArrayList<Point2D> points = getReceptorPoints(alias); + path.moveTo(points.get(0).getX(), points.get(0).getY()); + for (int i = 1; i < points.size(); i++) { + path.lineTo(points.get(i).getX(), points.get(i).getY()); + } + path.closePath(); + shape = path; + return shape; + } + + /** + * Returns shape of truncated protein. + * + * @param alias + * alias for which we are looking for a border + * @return Shape object defining given alias + */ + protected Shape getTruncatedShape(Element alias) { + Shape shape; + GeneralPath path = new GeneralPath(); + + // CHECKSTYLE:OFF + path.moveTo(alias.getX() + 10, alias.getY()); + path.lineTo(alias.getX() + alias.getWidth(), alias.getY()); + path.lineTo(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight() * 3 / 5); + path.lineTo(alias.getX() + alias.getWidth() * 4 / 5, alias.getY() + alias.getHeight() * 2 / 5); + path.lineTo(alias.getX() + alias.getWidth() * 4 / 5, alias.getY() + alias.getHeight()); + path.lineTo(alias.getX() + 10, alias.getY() + alias.getHeight()); + path.curveTo( + alias.getX() + 5, alias.getY() + alias.getHeight() - 2, alias.getX() + 2, alias.getY() + alias.getHeight() - 5, + alias.getX(), + alias.getY() + alias.getHeight() - 10); + path.lineTo(alias.getX(), alias.getY() + 10); + path.curveTo(alias.getX() + 2, alias.getY() + 5, alias.getX() + 5, alias.getY() + 2, alias.getX() + 10, + alias.getY()); + + // CHECKSTYLE:ON + + path.closePath(); + shape = path; + return shape; + } + + /** + * Returns shape of receptor protein as a list of points. + * + * @param alias + * alias for which we are looking for a border + * @return list of points defining border of the given alias + */ + private ArrayList<Point2D> getReceptorPoints(Element alias) { + double x = alias.getX(); + double y = alias.getY(); + double width = alias.getWidth(); + double height = alias.getHeight(); + ArrayList<Point2D> points = new ArrayList<Point2D>(); + + // CHECKSTYLE:OFF + points.add(new Point2D.Double(x, y + height * 2 / 5)); + points.add(new Point2D.Double(x, y)); + points.add(new Point2D.Double(x + width / 2, y + height / 5)); + points.add(new Point2D.Double(x + width, y)); + points.add(new Point2D.Double(x + width, y + height * 2 / 5)); + points.add(new Point2D.Double(x + width, y + height * 4 / 5)); + points.add(new Point2D.Double(x + width / 2, y + height)); + points.add(new Point2D.Double(x, y + height * 4 / 5)); + // CHECKSTYLE:ON + + return points; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverter.java index bd221e7175..3c412c80da 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverter.java @@ -8,16 +8,15 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; * */ public final class ReactionCellDesignerConverter { - /** - * What is the size of rectangle that is drawn in center point of the - * reaction. - */ - public static final double RECT_SIZE = 10; + /** + * What is the size of rectangle that is drawn in center point of the reaction. + */ + public static final double RECT_SIZE = 10; - /** - * Default constructor that prevents instantiation. - */ - protected ReactionCellDesignerConverter() { + /** + * Default constructor that prevents instantiation. + */ + protected ReactionCellDesignerConverter() { - } + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverter.java index 6223bf05ed..590880394c 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverter.java @@ -1,12 +1,10 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; +import java.awt.geom.*; import java.util.ArrayList; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -24,6 +22,11 @@ import lcsb.mapviewer.model.map.species.field.ModificationResidue; */ public class RnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConverter<Species> { + /** + * How big should be the arc in rectangle for nucleic acid feature + * representation. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 5; /** * Default class logger */ @@ -32,7 +35,7 @@ public class RnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConv /** * Default constructor. - * + * * @param sbgn * Should the converter use sbgn standard */ @@ -40,12 +43,6 @@ public class RnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConv super(sbgn); } - /** - * How big should be the arc in rectangle for nucleic acid feature - * representation. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 5; - @Override public Point2D getPointCoordinates(Species alias, CellDesignerAnchor anchor) { if (invalidAnchorPosition(alias, anchor)) { @@ -64,9 +61,37 @@ public class RnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConv return getRnaPath(alias).getPathIterator(new AffineTransform()); } + @Override + public Double getCellDesignerPositionByCoordinates(ModificationResidue mr) { + return (mr.getPosition().getX() - mr.getSpecies().getX() - mr.getSpecies().getWidth() / 4.0) + / (mr.getSpecies().getWidth() * 3.0 / 4.0); + } + + @Override + public Point2D getCoordinatesByPosition(Element element, Double pos, Double modificationWidth) { + double x = element.getX() + element.getWidth() / 4.0 + element.getWidth() * 3.0 / 4.0 * pos; + x = Math.max(element.getX() + modificationWidth / 2, x); + x = Math.min(element.getX() + element.getWidth() - modificationWidth / 2, x); + + return new Point2D.Double(x, element.getY()); + } + + @Override + public Double getCellDesignerSize(ModificationResidue mr) { + if (mr instanceof AbstractRegionModification) { + return ((AbstractRegionModification) mr).getWidth() / (mr.getSpecies().getWidth() * 3.0 / 4.0); + } + throw new NotImplementedException("Not implemented for: " + this.getClass() + ", " + mr.getClass()); + } + + @Override + public Double getWidthBySize(Element element, Double size) { + return size * (element.getWidth() * 3.0 / 4.0); + } + /** * Returns shape of the Rna as a list of points. - * + * * @param alias * alias for which we are looking for a border * @return list of points defining border of the given alias @@ -92,7 +117,7 @@ public class RnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConv /** * Returns shape of the Rna as a GeneralPath object. - * + * * @param alias * alias for which we are looking for a border * @return GeneralPath object defining border of the given alias @@ -124,32 +149,4 @@ public class RnaCellDesignerAliasConverter extends AbstractCellDesignerAliasConv return path; } - @Override - public Double getCellDesignerPositionByCoordinates(ModificationResidue mr) { - return (mr.getPosition().getX() - mr.getSpecies().getX() - mr.getSpecies().getWidth() / 4.0) - / (mr.getSpecies().getWidth() * 3.0 / 4.0); - } - - @Override - public Point2D getCoordinatesByPosition(Element element, Double pos, Double modificationWidth) { - double x = element.getX() + element.getWidth() / 4.0 + element.getWidth() * 3.0 / 4.0 * pos; - x = Math.max(element.getX() + modificationWidth / 2, x); - x = Math.min(element.getX() + element.getWidth() - modificationWidth / 2, x); - - return new Point2D.Double(x, element.getY()); - } - - @Override - public Double getCellDesignerSize(ModificationResidue mr) { - if (mr instanceof AbstractRegionModification) { - return ((AbstractRegionModification) mr).getWidth() / (mr.getSpecies().getWidth() * 3.0 / 4.0); - } - throw new NotImplementedException("Not implemented for: " + this.getClass() + ", " + mr.getClass()); - } - - @Override - public Double getWidthBySize(Element element, Double size) { - return size * (element.getWidth() * 3.0 / 4.0); - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverter.java index 979e7516ca..0d5eef9b9b 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverter.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverter.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverter.java index 8dd5e721e7..a3dd0508fd 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverter.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverter.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; @@ -40,11 +41,6 @@ public class UnknownCellDesignerAliasConverter extends AbstractCellDesignerAlias alias.getHeight(), anchor); } - @Override - public PathIterator getBoundPathIterator(Unknown alias) { - throw new NotImplementedException("This class doesn't provide boundPath"); - } - @Override public Point2D getAnchorPointCoordinates(Unknown alias, double angle) { if (alias.getWidth() == 0 && alias.getHeight() == 0) { @@ -57,6 +53,11 @@ public class UnknownCellDesignerAliasConverter extends AbstractCellDesignerAlias } + @Override + public PathIterator getBoundPathIterator(Unknown alias) { + throw new NotImplementedException("This class doesn't provide boundPath"); + } + @Override public Point2D getPointCoordinatesOnBorder(Unknown unknown, final double angle) { if (unknown.getWidth() == 0 && unknown.getHeight() == 0) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformation.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformation.java index 374f3c09f8..84d822932b 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformation.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformation.java @@ -2,9 +2,10 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; import java.awt.geom.Point2D; -import lcsb.mapviewer.common.geometry.EllipseTransformation; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.*; +import lcsb.mapviewer.common.geometry.EllipseTransformation; /** * This class contains basic operators on ellipse used by CellDesigner @@ -14,35 +15,36 @@ import org.apache.logging.log4j.*; * */ public class CellDesignerEllipseTransformation extends EllipseTransformation { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CellDesignerEllipseTransformation.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CellDesignerEllipseTransformation.class.getName()); - /** - * Method returns a cross point between ellipse and a line (from center point - * to the anchor point). - * - * @param x - * x coordinate of the ellipse - * @param y - * y coordinate of the ellipse - * @param width - * width of the ellipse - * @param height - * height of the ellipse - * @param anchor - * anchor on ellipse where we look for the point - * @return coordinates on the ellipse described by the anchor point - */ - public Point2D getPointOnEllipseByAnchor(double x, double y, double width, double height, CellDesignerAnchor anchor) { + /** + * Method returns a cross point between ellipse and a line (from center point to + * the anchor point). + * + * @param x + * x coordinate of the ellipse + * @param y + * y coordinate of the ellipse + * @param width + * width of the ellipse + * @param height + * height of the ellipse + * @param anchor + * anchor on ellipse where we look for the point + * @return coordinates on the ellipse described by the anchor point + */ + public Point2D getPointOnEllipseByAnchor(double x, double y, double width, double height, CellDesignerAnchor anchor) { - if (anchor == null || anchor.getAngle() == null) { - return new Point2D.Double(x + width / 2, y + height / 2); - } else { - double angle = anchor.getAngle(); - return new Point2D.Double(x + width / 2 + Math.cos(angle) * width / 2, y + height / 2 + Math.sin(angle) * height / 2); - } - } + if (anchor == null || anchor.getAngle() == null) { + return new Point2D.Double(x + width / 2, y + height / 2); + } else { + double angle = anchor.getAngle(); + return new Point2D.Double(x + width / 2 + Math.cos(angle) * width / 2, + y + height / 2 + Math.sin(angle) * height / 2); + } + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformation.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformation.java index 3092a74500..9df531f3da 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformation.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformation.java @@ -2,9 +2,10 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; import java.awt.geom.Point2D; -import lcsb.mapviewer.common.geometry.PointTransformation; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.*; +import lcsb.mapviewer.common.geometry.PointTransformation; /** * Class for basic point transformations. @@ -13,78 +14,80 @@ import org.apache.logging.log4j.*; * */ public class CellDesignerPointTransformation extends PointTransformation { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CellDesignerPointTransformation.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CellDesignerPointTransformation.class.getName()); - /** - * This method transform coordinates of pointP in CellDesginer format (base: - * pointA, pointB, pointC) into normal x,y coordinates. - * - * In CellDesigner some points are in different base consisted from three - * points. In this base vector between pointA and pointC is 1 unit on X axis - * (in normal world); and vector between pointB and pointC is 1 unit on Y - * axis. - * - * @param pointA - * central point of CellDesigner base - * @param pointB - * first point of CellDesigner base - * @param pointC - * second point of CellDesigner base - * @param pointP - * point to be transformed into normal coordinates - * @return standard x,y coordinate - */ - public Point2D getCoordinatesInNormalBase(final Point2D pointA, final Point2D pointB, final Point2D pointC, final Point2D pointP) { - double dx1 = pointA.getX() - pointC.getX(); - double dy1 = pointA.getY() - pointC.getY(); + /** + * This method transform coordinates of pointP in CellDesginer format (base: + * pointA, pointB, pointC) into normal x,y coordinates. + * + * In CellDesigner some points are in different base consisted from three + * points. In this base vector between pointA and pointC is 1 unit on X axis (in + * normal world); and vector between pointB and pointC is 1 unit on Y axis. + * + * @param pointA + * central point of CellDesigner base + * @param pointB + * first point of CellDesigner base + * @param pointC + * second point of CellDesigner base + * @param pointP + * point to be transformed into normal coordinates + * @return standard x,y coordinate + */ + public Point2D getCoordinatesInNormalBase(final Point2D pointA, final Point2D pointB, final Point2D pointC, + final Point2D pointP) { + double dx1 = pointA.getX() - pointC.getX(); + double dy1 = pointA.getY() - pointC.getY(); - double dx2 = pointB.getX() - pointC.getX(); - double dy2 = pointB.getY() - pointC.getY(); + double dx2 = pointB.getX() - pointC.getX(); + double dy2 = pointB.getY() - pointC.getY(); - double x = pointC.getX() + dx1 * pointP.getX() + dx2 * pointP.getY(); - double y = pointC.getY() + dy1 * pointP.getX() + dy2 * pointP.getY(); + double x = pointC.getX() + dx1 * pointP.getX() + dx2 * pointP.getY(); + double y = pointC.getY() + dy1 * pointP.getX() + dy2 * pointP.getY(); - Point2D pointO = new Point2D.Double(x, y); + Point2D pointO = new Point2D.Double(x, y); - return pointO; - } + return pointO; + } - /** - * This method transform coordinates of pointP in x,y coordinates into - * celldesginer format (base: pointA, pointB, pointC) - * - * In CellDesigner some points are in different base consisted from three - * points. In this base vector between pointA and pointC is 1 unit on X axis - * (in normal world); and vector between pointB and pointC is 1 unit on Y - * axis. - * - * @param pointA - * central point of CellDesigner base - * @param pointB - * first point of CellDesigner base - * @param pointC - * second point of CellDesigner base - * @param pointO - * point to be transformed - * @return point in CellDesigner base - */ - public Point2D getCoordinatesInCellDesignerBase(final Point2D pointA, final Point2D pointB, final Point2D pointC, final Point2D pointO) { - double dx1 = pointA.getX() - pointC.getX(); - double dy1 = pointA.getY() - pointC.getY(); + /** + * This method transform coordinates of pointP in x,y coordinates into + * celldesginer format (base: pointA, pointB, pointC) + * + * In CellDesigner some points are in different base consisted from three + * points. In this base vector between pointA and pointC is 1 unit on X axis (in + * normal world); and vector between pointB and pointC is 1 unit on Y axis. + * + * @param pointA + * central point of CellDesigner base + * @param pointB + * first point of CellDesigner base + * @param pointC + * second point of CellDesigner base + * @param pointO + * point to be transformed + * @return point in CellDesigner base + */ + public Point2D getCoordinatesInCellDesignerBase(final Point2D pointA, final Point2D pointB, final Point2D pointC, + final Point2D pointO) { + double dx1 = pointA.getX() - pointC.getX(); + double dy1 = pointA.getY() - pointC.getY(); - double dx2 = pointB.getX() - pointC.getX(); - double dy2 = pointB.getY() - pointC.getY(); + double dx2 = pointB.getX() - pointC.getX(); + double dy2 = pointB.getY() - pointC.getY(); - double y = (dy1 * (pointO.getX() - pointC.getX()) + dx1 * (pointC.getY() - pointO.getY())) / (dx2 * dy1 - dx1 * dy2); - double x = (dy2 * (pointC.getX() - pointO.getX()) + dx2 * (pointO.getY() - pointC.getY())) / (dx2 * dy1 - dx1 * dy2); + double y = (dy1 * (pointO.getX() - pointC.getX()) + dx1 * (pointC.getY() - pointO.getY())) + / (dx2 * dy1 - dx1 * dy2); + double x = (dy2 * (pointC.getX() - pointO.getX()) + dx2 * (pointO.getY() - pointC.getY())) + / (dx2 * dy1 - dx1 * dy2); - Point2D pointP = new Point2D.Double(x, y); + Point2D pointP = new Point2D.Double(x, y); - return pointP; - } + return pointP; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformation.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformation.java index 8bee6c829d..4252bc66ea 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformation.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPolygonTransformation.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; import java.awt.geom.Point2D; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -14,97 +15,100 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; * */ public class CellDesignerPolygonTransformation { - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CellDesignerPolygonTransformation.class.getName()); - /** - * Returns a middle point between two points (using Euclidean distance). - * - * @param pointA - * first coordinate - * @param pointB - * second coordinate - * @return central point between pointA and pointB - */ - private Point2D getMidPoint(Point2D pointA, Point2D pointB) { - return new Point2D.Double((pointA.getX() + pointB.getX()) / 2, (pointA.getY() + pointB.getY()) / 2); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CellDesignerPolygonTransformation.class.getName()); - /** - * Returns a point on polygon for the anchor given as a parameter. - * - * @param points - * list of points which describes polygon. By default polygon can - * contain only 8 or 16 points (all CellDesigner elements can be - * drawn as such coordinates). - * @param anchor - * direction in which we look for coordinates - * @return coordinates on the polygon described by the anchor point - */ - public Point2D getPointOnPolygonByAnchor(List<Point2D> points, CellDesignerAnchor anchor) { - if (points.size() == CellDesignerAnchor.DIFFERENT_ANCHORS / 2) { - return getPointOn8NodesPolygonByAnchor(points, anchor); - } else if (points.size() == CellDesignerAnchor.DIFFERENT_ANCHORS) { - return getPointOn16NodesPolygonByAnchor(points, anchor); - } else { - throw new InvalidArgumentException("Invalid number of points: " + points.size()); - } - } + /** + * Returns a middle point between two points (using Euclidean distance). + * + * @param pointA + * first coordinate + * @param pointB + * second coordinate + * @return central point between pointA and pointB + */ + private Point2D getMidPoint(Point2D pointA, Point2D pointB) { + return new Point2D.Double((pointA.getX() + pointB.getX()) / 2, (pointA.getY() + pointB.getY()) / 2); + } - /** - * Creates a copy of a point given as a parameter. - * - * @param point - * object to copy - * @return copy of the point parameter - */ - private Point2D copyPoint(Point2D point) { - return new Point2D.Double(point.getX(), point.getY()); - } + /** + * Returns a point on polygon for the anchor given as a parameter. + * + * @param points + * list of points which describes polygon. By default polygon can + * contain only 8 or 16 points (all CellDesigner elements can be drawn + * as such coordinates). + * @param anchor + * direction in which we look for coordinates + * @return coordinates on the polygon described by the anchor point + */ + public Point2D getPointOnPolygonByAnchor(List<Point2D> points, CellDesignerAnchor anchor) { + if (points.size() == CellDesignerAnchor.DIFFERENT_ANCHORS / 2) { + return getPointOn8NodesPolygonByAnchor(points, anchor); + } else if (points.size() == CellDesignerAnchor.DIFFERENT_ANCHORS) { + return getPointOn16NodesPolygonByAnchor(points, anchor); + } else { + throw new InvalidArgumentException("Invalid number of points: " + points.size()); + } + } - /** - * This method returns a point on the border defined by the list of 8 points - * for a given anchor. - * - * @param points - * list of 8 points that define a polygon - * @param anchor - * direction in which we are looking for a point - * @return point on the border - */ - private Point2D getPointOn8NodesPolygonByAnchor(List<Point2D> points, CellDesignerAnchor anchor) { - if (anchor == null || anchor.getAngle() == null) { - throw new InvalidArgumentException("Invalid anchor: " + anchor); - } else { - int position = (anchor.ordinal() + CellDesignerAnchor.DIFFERENT_ANCHORS / 2) % CellDesignerAnchor.DIFFERENT_ANCHORS; - if (position % 2 == 0) { - return copyPoint(points.get(position / 2)); - } else { - return getMidPoint(points.get(position / 2), points.get((position / 2 + 1) % (CellDesignerAnchor.DIFFERENT_ANCHORS / 2))); - } - } - } + /** + * Creates a copy of a point given as a parameter. + * + * @param point + * object to copy + * @return copy of the point parameter + */ + private Point2D copyPoint(Point2D point) { + return new Point2D.Double(point.getX(), point.getY()); + } - /** - * This method returns a point on the border defined by the list of 16 points - * for a given anchor. - * - * @param points - * list of 16 points that define a polygon - * @param anchor - * direction in which we are looking for a point - * @return point on the border - */ - private Point2D getPointOn16NodesPolygonByAnchor(List<Point2D> points, CellDesignerAnchor anchor) { - if (anchor == null || anchor.getAngle() == null) { - throw new InvalidArgumentException("Invalid anchor: " + anchor); - } else { - int position = (anchor.ordinal() + CellDesignerAnchor.DIFFERENT_ANCHORS / 2) % CellDesignerAnchor.DIFFERENT_ANCHORS; - return copyPoint(points.get(position)); - } - } + /** + * This method returns a point on the border defined by the list of 8 points for + * a given anchor. + * + * @param points + * list of 8 points that define a polygon + * @param anchor + * direction in which we are looking for a point + * @return point on the border + */ + private Point2D getPointOn8NodesPolygonByAnchor(List<Point2D> points, CellDesignerAnchor anchor) { + if (anchor == null || anchor.getAngle() == null) { + throw new InvalidArgumentException("Invalid anchor: " + anchor); + } else { + int position = (anchor.ordinal() + CellDesignerAnchor.DIFFERENT_ANCHORS / 2) + % CellDesignerAnchor.DIFFERENT_ANCHORS; + if (position % 2 == 0) { + return copyPoint(points.get(position / 2)); + } else { + return getMidPoint(points.get(position / 2), + points.get((position / 2 + 1) % (CellDesignerAnchor.DIFFERENT_ANCHORS / 2))); + } + } + } + + /** + * This method returns a point on the border defined by the list of 16 points + * for a given anchor. + * + * @param points + * list of 16 points that define a polygon + * @param anchor + * direction in which we are looking for a point + * @return point on the border + */ + private Point2D getPointOn16NodesPolygonByAnchor(List<Point2D> points, CellDesignerAnchor anchor) { + if (anchor == null || anchor.getAngle() == null) { + throw new InvalidArgumentException("Invalid anchor: " + anchor); + } else { + int position = (anchor.ordinal() + CellDesignerAnchor.DIFFERENT_ANCHORS / 2) + % CellDesignerAnchor.DIFFERENT_ANCHORS; + return copyPoint(points.get(position)); + } + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformation.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformation.java index bd8b5a3b48..05cee016fc 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformation.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformation.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; import java.awt.geom.Point2D; import java.util.ArrayList; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Class with basic operations on rectangles. @@ -13,46 +14,46 @@ import org.apache.logging.log4j.*; */ public class CellDesignerRectangleTransformation { - /** - * Object used for transformation on the polygons. - */ - private CellDesignerPolygonTransformation polygonTransformation = new CellDesignerPolygonTransformation(); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CellDesignerRectangleTransformation.class.getName()); + /** + * Object used for transformation on the polygons. + */ + private CellDesignerPolygonTransformation polygonTransformation = new CellDesignerPolygonTransformation(); - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CellDesignerRectangleTransformation.class.getName()); - - /** - * Returns a point on a rectangle for anchor. - * - * @param x - * x coordinate of the rectangle - * @param y - * y coordinate of the rectangle - * @param width - * width of the rectangle - * @param height - * height of the rectangle - * @param anchor - * point where we are looking for the point - * @return coordinates on the rectangle in direction described by anchor - */ - public Point2D getPointOnRectangleByAnchor(double x, double y, double width, double height, CellDesignerAnchor anchor) { - if (anchor == null || anchor.getAngle() == null) { - return new Point2D.Double(x + width / 2, y + height / 2); - } - ArrayList<Point2D> list = new ArrayList<Point2D>(); - list.add(new Point2D.Double(x, y + height / 2)); - list.add(new Point2D.Double(x, y)); - list.add(new Point2D.Double(x + width / 2, y)); - list.add(new Point2D.Double(x + width, y)); - list.add(new Point2D.Double(x + width, y + height / 2)); - list.add(new Point2D.Double(x + width, y + height)); - list.add(new Point2D.Double(x + width / 2, y + height)); - list.add(new Point2D.Double(x, y + height)); - return polygonTransformation.getPointOnPolygonByAnchor(list, anchor); - } + /** + * Returns a point on a rectangle for anchor. + * + * @param x + * x coordinate of the rectangle + * @param y + * y coordinate of the rectangle + * @param width + * width of the rectangle + * @param height + * height of the rectangle + * @param anchor + * point where we are looking for the point + * @return coordinates on the rectangle in direction described by anchor + */ + public Point2D getPointOnRectangleByAnchor(double x, double y, double width, double height, + CellDesignerAnchor anchor) { + if (anchor == null || anchor.getAngle() == null) { + return new Point2D.Double(x + width / 2, y + height / 2); + } + ArrayList<Point2D> list = new ArrayList<Point2D>(); + list.add(new Point2D.Double(x, y + height / 2)); + list.add(new Point2D.Double(x, y)); + list.add(new Point2D.Double(x + width / 2, y)); + list.add(new Point2D.Double(x + width, y)); + list.add(new Point2D.Double(x + width, y + height / 2)); + list.add(new Point2D.Double(x + width, y + height)); + list.add(new Point2D.Double(x + width / 2, y + height)); + list.add(new Point2D.Double(x, y + height)); + return polygonTransformation.getPointOnPolygonByAnchor(list, anchor); + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/package-info.java index b164954ded..bf898d1af1 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/package-info.java @@ -3,4 +3,3 @@ * into more intuitive structures. */ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/package-info.java index 7ac605eb0d..14b5292d68 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/geometry/package-info.java @@ -3,4 +3,3 @@ * objects into normal x,y coordinates in our model. */ package lcsb.mapviewer.converter.model.celldesigner.geometry; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/package-info.java index 89e84c422f..4a5fe50d25 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/package-info.java @@ -5,4 +5,3 @@ * CellDesignerXmlParser} to see how it works. */ package lcsb.mapviewer.converter.model.celldesigner; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java index 8629a24939..ef8a4522d8 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.parameter; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterXmlParser.java index 18cbbca16b..507e157ba6 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterXmlParser.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.parameter; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; @@ -41,7 +42,7 @@ public class ParameterXmlParser { result.append("units=\"" + sbmlFunction.getUnits().getUnitId() + "\" "); } result.append("/>"); - + return result.toString(); } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParser.java index 13c5b6cb0c..d3447cbb08 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParser.java @@ -1,10 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; @@ -12,9 +11,7 @@ import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.parameter.ParameterCollectionXmlParser; import lcsb.mapviewer.model.map.InconsistentModelException; -import lcsb.mapviewer.model.map.kinetics.SbmlArgument; -import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParser.java index 7920cc77f9..667adf9184 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParser.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; 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/reaction/ReactionFromXml.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionFromXml.java index 8f26b3efad..8fdfaeaf59 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 @@ -1,14 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -16,51 +9,20 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; 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.common.exception.*; import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; 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; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerPointTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.PolylineDataFactory; -import lcsb.mapviewer.converter.model.celldesigner.structure.fields.ConnectScheme; -import lcsb.mapviewer.converter.model.celldesigner.structure.fields.EditPoints; -import lcsb.mapviewer.converter.model.celldesigner.structure.fields.LineProperties; -import lcsb.mapviewer.converter.model.celldesigner.types.ModifierType; -import lcsb.mapviewer.converter.model.celldesigner.types.ModifierTypeUtils; -import lcsb.mapviewer.converter.model.celldesigner.types.OperatorType; -import lcsb.mapviewer.converter.model.celldesigner.types.OperatorTypeUtils; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.*; +import lcsb.mapviewer.converter.model.celldesigner.structure.fields.*; +import lcsb.mapviewer.converter.model.celldesigner.types.*; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -import lcsb.mapviewer.model.map.reaction.DissociationOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NandOperator; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.OrOperator; -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.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.TruncationOperator; -import lcsb.mapviewer.model.map.reaction.UnknownOperator; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.SimpleReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; -import lcsb.mapviewer.model.map.reaction.type.TwoProductReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TwoReactantReactionInterface; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -82,70 +44,58 @@ 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; - + CellDesignerElementCollection elements; /** * Stores information about {@link CellDesignerAnchor} for a node. */ private 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<>(); - /** * Stores information to which point on the central rectangle modifier should be * connected. */ private 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<>(); - /** * Stores information about list of points that create line describing modifier. */ private 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<>(); - /** * Identifies central line segment in {@link TwoProductReactionInterface} and * {@link TwoReactantReactionInterface} reactions. */ private Map<ReactionNode, Integer> indexByComplexReaction = new HashMap<>(); - /** * Default class logger. */ @SuppressWarnings("unused") private Logger logger = LogManager.getLogger(ReactionXmlParser.class.getName()); - /** * Xml parser used for processing notes into structured data. */ private RestAnnotationParser rap = new RestAnnotationParser(); - /** * Helper object used for manipulation on the point coordinates in CellDesigner * format. */ private CellDesignerPointTransformation pointTransformation = new CellDesignerPointTransformation(); - /** * Should SBGN standard be used. */ private boolean sbgn; - CellDesignerElementCollection elements; - /** * Default constructor. * diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineData.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineData.java index aeb24d7470..d94b022ec7 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineData.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineData.java @@ -6,32 +6,7 @@ import java.util.Map; import lcsb.mapviewer.model.graphics.ArrowType; import lcsb.mapviewer.model.graphics.LineType; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.type.CatalysisReaction; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.InhibitionReaction; -import lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction; -import lcsb.mapviewer.model.map.reaction.type.ModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.PhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranslationReaction; -import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.reaction.type.TriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownCatalysisReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownInhibitionReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; +import lcsb.mapviewer.model.map.reaction.type.*; /** * This class represent graphical information about lines/arrows that are @@ -187,33 +162,39 @@ public enum ReactionLineData { */ UNKNOWN_TRANSITION(UnknownTransitionReaction.class, "UNKNOWN_TRANSITION"); + /** + * Map used for reverse lookup between {@link Reaction} types and + * {@link ReactionLineData}. + */ + private static Map<Class<? extends Reaction>, ReactionLineData> map = null; + /** + * Map used for reverse lookup between {@link #cellDesignerString} types and + * {@link ReactionLineData}. + */ + private static Map<String, ReactionLineData> cellDesignerMap = null; /** * {@link Reaction} class for which the data is stored. */ private Class<? extends Reaction> reactionClass; - /** * Type of arrow that should be used by products. */ private ArrowType productArrowType; - /** * Line types that should be used by the reaction. */ private LineType lineType; - /** * How much product line should be trimmed at the end. */ private double productLineTrim; - /** * String used by CellDesigner to represent reaction. */ private String cellDesignerString; /** - * + * * @param clazz * {@link #reactionClass} * @param cellDesignerString @@ -225,7 +206,7 @@ public enum ReactionLineData { } /** - * + * * @param clazz * {@link #reactionClass} * @param cellDesignerString @@ -238,7 +219,7 @@ public enum ReactionLineData { } /** - * + * * @param clazz * {@link #reactionClass} * @param cellDesignerString @@ -254,7 +235,7 @@ public enum ReactionLineData { } /** - * + * * @param clazz * {@link #reactionClass} * @param cellDesignerString @@ -275,6 +256,64 @@ public enum ReactionLineData { this.cellDesignerString = cellDesignerString; } + /** + * Method that finds {@link ReactionLineData} or given {@link Reaction} type. + * + * @param clazz + * type for which {@link ReactionLineData} will be returned + * @return {@link ReactionLineData} or given {@link Reaction} type + */ + public static ReactionLineData getByReactionType(Class<? extends Reaction> clazz) { + if (map == null) { + map = new HashMap<Class<? extends Reaction>, ReactionLineData>(); + for (ReactionLineData rld : values()) { + map.put(rld.getReactionClass(), rld); + } + } + return map.get(clazz); + } + + /** + * Returns {@link ReactionLineData} identified by CellDEsigner string that + * identifies this Reaction type. + * + * @param type + * {@link #cellDesignerString} + * @return {@link ReactionLineData} identified by CellDEsigner string that + * identifies this Reaction type + */ + public static ReactionLineData getByCellDesignerString(String type) { + if (cellDesignerMap == null) { + cellDesignerMap = new HashMap<String, ReactionLineData>(); + for (ReactionLineData rld : values()) { + cellDesignerMap.put(rld.getCellDesignerString(), rld); + } + } + return cellDesignerMap.get(type); + } + + /** + * Returns {@link ReactionLineData} that can be applied for lines with given + * line type and arrow type. If there are more then one possibility, one of them + * will be returned (nothing is guaranteed). + * + * @param lineType + * type of the line for which are looking for {@link ReactionLineData} + * @param productArrowType + * type of the arrow for which are looking for {@link ReactionLineData} + * @return {@link ReactionLineData} that can be applied for lines with given + * line type and arrow type. If there are more then one possibility, one + * of them will be returned (nothing is guaranteed) + */ + public static ReactionLineData getByLineType(LineType lineType, ArrowType productArrowType) { + for (ReactionLineData rld : values()) { + if (rld.getLineType().equals(lineType) && rld.getProductArrowType().equals(productArrowType)) { + return rld; + } + } + return null; + } + /** * @return the reactionClass * @see #reactionClass @@ -307,35 +346,6 @@ public enum ReactionLineData { return productLineTrim; } - /** - * Map used for reverse lookup between {@link Reaction} types and - * {@link ReactionLineData}. - */ - private static Map<Class<? extends Reaction>, ReactionLineData> map = null; - - /** - * Map used for reverse lookup between {@link #cellDesignerString} types and - * {@link ReactionLineData}. - */ - private static Map<String, ReactionLineData> cellDesignerMap = null; - - /** - * Method that finds {@link ReactionLineData} or given {@link Reaction} type. - * - * @param clazz - * type for which {@link ReactionLineData} will be returned - * @return {@link ReactionLineData} or given {@link Reaction} type - */ - public static ReactionLineData getByReactionType(Class<? extends Reaction> clazz) { - if (map == null) { - map = new HashMap<Class<? extends Reaction>, ReactionLineData>(); - for (ReactionLineData rld : values()) { - map.put(rld.getReactionClass(), rld); - } - } - return map.get(clazz); - } - /** * @return the cellDesignerString * @see #cellDesignerString @@ -344,29 +354,10 @@ public enum ReactionLineData { return cellDesignerString; } - /** - * Returns {@link ReactionLineData} identified by CellDEsigner string that - * identifies this Reaction type. - * - * @param type - * {@link #cellDesignerString} - * @return {@link ReactionLineData} identified by CellDEsigner string that - * identifies this Reaction type - */ - public static ReactionLineData getByCellDesignerString(String type) { - if (cellDesignerMap == null) { - cellDesignerMap = new HashMap<String, ReactionLineData>(); - for (ReactionLineData rld : values()) { - cellDesignerMap.put(rld.getCellDesignerString(), rld); - } - } - return cellDesignerMap.get(type); - } - /** * Creates instance of {@link Reaction} represented by this enum and copies the * data from result parameter. - * + * * @param result * original data * @return instance of {@link Reaction} represented by this enum and copies the @@ -381,26 +372,4 @@ public enum ReactionLineData { } } - /** - * Returns {@link ReactionLineData} that can be applied for lines with given - * line type and arrow type. If there are more then one possibility, one of them - * will be returned (nothing is guaranteed). - * - * @param lineType - * type of the line for which are looking for {@link ReactionLineData} - * @param productArrowType - * type of the arrow for which are looking for {@link ReactionLineData} - * @return {@link ReactionLineData} that can be applied for lines with given - * line type and arrow type. If there are more then one possibility, one - * of them will be returned (nothing is guaranteed) - */ - public static ReactionLineData getByLineType(LineType lineType, ArrowType productArrowType) { - for (ReactionLineData rld : values()) { - if (rld.getLineType().equals(lineType) && rld.getProductArrowType().equals(productArrowType)) { - return rld; - } - } - return null; - } - } 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 f374f0fe2c..fe18a84c30 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,12 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; 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.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -20,30 +15,13 @@ import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; 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; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerPointTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.PolylineDataFactory; +import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.*; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; -import lcsb.mapviewer.converter.model.celldesigner.types.ModifierType; -import lcsb.mapviewer.converter.model.celldesigner.types.ModifierTypeUtils; -import lcsb.mapviewer.converter.model.celldesigner.types.OperatorType; -import lcsb.mapviewer.converter.model.celldesigner.types.OperatorTypeUtils; +import lcsb.mapviewer.converter.model.celldesigner.types.*; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.InconsistentModelException; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -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.reaction.type.ReducedNotation; -import lcsb.mapviewer.model.map.reaction.type.SimpleReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TwoProductReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TwoReactantReactionInterface; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -531,7 +509,8 @@ public class ReactionToXml { if (!(operator instanceof AndOperator || operator instanceof AssociationOperator || !operator.isReactantOperator())) { return "BOOLEAN_LOGIC_GATE"; - } else if (operator instanceof AndOperator && operator.isReactantOperator() && reaction instanceof ReducedNotation) { + } else if (operator instanceof AndOperator && operator.isReactantOperator() + && reaction instanceof ReducedNotation) { // check the geometry - we might need to use BOOLEAN_LOGIC_GATE if the joining // point is not colinear with first reactant line and operator line AbstractNode firstReactant = operator.getInputs().get(0); @@ -703,7 +682,7 @@ public class ReactionToXml { sb.append(getAnchorXml(alias, reactant.getLine().getBeginPoint())); - sb.append(getConnectSchemeXmlStringForLines(new PolylineData[] {reactant.getLine()})); + sb.append(getConnectSchemeXmlStringForLines(new PolylineData[] { reactant.getLine() })); sb.append(getEditPointsXmlStringForLine(new PolylineData[] { reactant.getLine() }, 0)); sb.append("<celldesigner:line "); sb.append("width=\"" + reactant.getLine().getWidth() + "\" "); @@ -998,16 +977,16 @@ public class ReactionToXml { } int centerPosition = reactant.getLine().getPoints().size() - 1; PolylineData productLine = getLineBeforeTrimming(product); - + PolylineData testLine = new PolylineData(); - testLine.addPoint(reactant.getLine().getPoints().get(reactant.getLine().getPoints().size()-2)); - testLine.addPoint(reactant.getLine().getPoints().get(reactant.getLine().getPoints().size()-1)); + testLine.addPoint(reactant.getLine().getPoints().get(reactant.getLine().getPoints().size() - 2)); + testLine.addPoint(reactant.getLine().getPoints().get(reactant.getLine().getPoints().size() - 1)); testLine.addPoint(productLine.getPoints().get(0)); testLine.addPoint(productLine.getPoints().get(1)); testLine = PolylineDataFactory.removeCollinearPoints(testLine); - if (testLine.getPoints().size()>2) { - points.add(reactant.getLine().getPoints().get(reactant.getLine().getPoints().size()-1)); - centerPosition ++; + if (testLine.getPoints().size() > 2) { + points.add(reactant.getLine().getPoints().get(reactant.getLine().getPoints().size() - 1)); + centerPosition++; points.add(productLine.getPoints().get(0)); } for (int i = 1; i < productLine.getPoints().size(); i++) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionXmlParser.java index 36ce6ae460..8b99762b00 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionXmlParser.java @@ -19,57 +19,57 @@ import lcsb.mapviewer.model.map.reaction.Reaction; */ public class ReactionXmlParser { - /** - * Class that allows to export data into CellDesigner xml node. - */ - private ReactionToXml reactionToXml; + /** + * Class that allows to export data into CellDesigner xml node. + */ + private ReactionToXml reactionToXml; - /** - * Class that allows to import data from CellDesigner xml node. - */ - private ReactionFromXml reactionFromXml; + /** + * Class that allows to import data from CellDesigner xml node. + */ + private ReactionFromXml reactionFromXml; - /** - * Default constructor. Model is required because some nodes require access to - * other parts of the model. - * - * @param sbgn - * Should SBGN standard be used - * @param elements - * collection of {@link CellDesignerElement cell designer elements} - * parsed from xml - */ - public ReactionXmlParser(CellDesignerElementCollection elements, boolean sbgn) { - reactionToXml = new ReactionToXml(elements, sbgn); - reactionFromXml = new ReactionFromXml(elements, sbgn); - } + /** + * Default constructor. Model is required because some nodes require access to + * other parts of the model. + * + * @param sbgn + * Should SBGN standard be used + * @param elements + * collection of {@link CellDesignerElement cell designer elements} + * parsed from xml + */ + public ReactionXmlParser(CellDesignerElementCollection elements, boolean sbgn) { + reactionToXml = new ReactionToXml(elements, sbgn); + reactionFromXml = new ReactionFromXml(elements, sbgn); + } - /** - * Returns {@link Reaction} object from CellDesigner xml node. - * - * @param node - * xml node - * @param model - * model where the reaction is placed - * @return reaction from xml node - * @throws ReactionParserException - * thrown when the xml is invalid - * @throws InvalidXmlSchemaException - * thrown when node is invalid xml - */ - public Reaction getReaction(Node node, Model model) throws ReactionParserException, InvalidXmlSchemaException { - return reactionFromXml.getReaction(node, model); - } + /** + * Returns {@link Reaction} object from CellDesigner xml node. + * + * @param node + * xml node + * @param model + * model where the reaction is placed + * @return reaction from xml node + * @throws ReactionParserException + * thrown when the xml is invalid + * @throws InvalidXmlSchemaException + * thrown when node is invalid xml + */ + public Reaction getReaction(Node node, Model model) throws ReactionParserException, InvalidXmlSchemaException { + return reactionFromXml.getReaction(node, model); + } - /** - * Transform reaction into CellDesigner xml representation. - * - * @param reaction - * reaction to transform - * @return xml representation of reaction - * @throws ConverterException - */ - public String toXml(Reaction reaction) throws InconsistentModelException { - return reactionToXml.toXml(reaction); - } + /** + * Transform reaction into CellDesigner xml representation. + * + * @param reaction + * reaction to transform + * @return xml representation of reaction + * @throws ConverterException + */ + public String toXml(Reaction reaction) throws InconsistentModelException { + return reactionToXml.toXml(reaction); + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassException.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassException.java index 160c69da42..934aaea362 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassException.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassException.java @@ -9,46 +9,46 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; */ public class UnknownModifierClassException extends ReactionParserException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Type of reaction that was a reason for this exception. - */ - private String modificationType; + /** + * Type of reaction that was a reason for this exception. + */ + private String modificationType; - /** - * Default constructor. - * - * @param message - * message thrown - * @param type - * {@link #modificationType} - * @param reactionId - * {@link #reactionId} - */ - public UnknownModifierClassException(String message, String type, String reactionId) { - super(message, reactionId); - this.modificationType = type; - } + /** + * Default constructor. + * + * @param message + * message thrown + * @param type + * {@link #modificationType} + * @param reactionId + * {@link #reactionId} + */ + public UnknownModifierClassException(String message, String type, String reactionId) { + super(message, reactionId); + this.modificationType = type; + } - /** - * @return the modificationType - * @see #modificationType - */ - public String getModificationType() { - return modificationType; - } + /** + * @return the modificationType + * @see #modificationType + */ + public String getModificationType() { + return modificationType; + } - /** - * @param modificationType - * the modificationType to set - * @see #modificationType - */ - public void setModificationType(String modificationType) { - this.modificationType = modificationType; - } + /** + * @param modificationType + * the modificationType to set + * @see #modificationType + */ + public void setModificationType(String modificationType) { + this.modificationType = modificationType; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/package-info.java index 3a0bc37998..bb86585488 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/reaction/package-info.java @@ -3,4 +3,3 @@ * {@link lcsb.mapviewer.db.model.map.reaction.Reaction Reaction}. */ package lcsb.mapviewer.converter.model.celldesigner.reaction; - 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 4b4c18b2ff..57088e7a92 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 @@ -3,10 +3,9 @@ package lcsb.mapviewer.converter.model.celldesigner.species; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.XmlParser; @@ -48,21 +47,6 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, */ private RestAnnotationParser rap = new RestAnnotationParser(); - /** - * Method that parses CellDesigner xml node and translate it into object. - * 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 - * @throws CompartmentParserException - */ - public abstract Pair<String, T> parseXmlElement(Node node) throws InvalidXmlSchemaException, CellDesignerParserException; - /** * Default constructor. */ @@ -124,6 +108,23 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, encodedStrings.add(new Pair<String, String>("_omega_", "ω")); } + /** + * Method that parses CellDesigner xml node and translate it into object. + * 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 + * @throws CompartmentParserException + */ + public abstract Pair<String, T> parseXmlElement(Node node) + throws InvalidXmlSchemaException, CellDesignerParserException; + /** * Parses CellDEsigner xml node that is given as a plain text into element. * Returns a {@link Pair} containing CellDesigner identifier in @@ -131,13 +132,15 @@ public abstract class AbstractElementXmlParser<T extends CellDesignerElement<?>, * * @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()}. + * @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 - * @throws CellDesignerParserException + * @throws CellDesignerParserException */ - public Pair<String, T> parseXmlElement(String xmlString) throws InvalidXmlSchemaException, CellDesignerParserException { + public Pair<String, T> parseXmlElement(String xmlString) + throws InvalidXmlSchemaException, CellDesignerParserException { Document doc = XmlParser.getXmlDocumentFromString(xmlString); NodeList root = doc.getChildNodes(); return parseXmlElement(root.item(0)); diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java index 45005aeaed..3365b858a8 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParser.java @@ -1,11 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.Pair; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java index 1a3fbbfc96..913c6a0ec4 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/GeneXmlParser.java @@ -1,11 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.Pair; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; @@ -85,9 +86,38 @@ public class GeneXmlParser extends AbstractElementXmlParser<CellDesignerGene, Ge return new Pair<String, CellDesignerGene>(identifier, gene); } + @Override + public String toXml(Gene gene) { + String attributes = ""; + String result = ""; + attributes += " id=\"g_" + elements.getElementId(gene) + "\""; + if (!gene.getName().equals("")) { + attributes += " name=\"" + XmlParser.escapeXml(encodeName(gene.getName())) + "\""; + } + result += "<celldesigner:gene" + attributes + ">"; + result += "<celldesigner:notes>"; + result += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title/></head><body>"; + RestAnnotationParser rap = new RestAnnotationParser(); + result += rap.createAnnotationString(gene); + result += gene.getNotes(); + result += "</body></html>"; + result += "</celldesigner:notes>"; + + if (gene.getModificationResidues().size() > 0) { + result += "<celldesigner:listOfRegions>\n"; + for (ModificationResidue mr : gene.getModificationResidues()) { + result += modificationResidueXmlParser.toXml(mr); + } + result += "</celldesigner:listOfRegions>\n"; + } + + result += "</celldesigner:gene>"; + return result; + } + /** * Parse modification for a gene. - * + * * @param residueNode * source xml node * @return object representing modification @@ -118,33 +148,4 @@ public class GeneXmlParser extends AbstractElementXmlParser<CellDesignerGene, Ge return residue; } - @Override - public String toXml(Gene gene) { - String attributes = ""; - String result = ""; - attributes += " id=\"g_" + elements.getElementId(gene) + "\""; - if (!gene.getName().equals("")) { - attributes += " name=\"" + XmlParser.escapeXml(encodeName(gene.getName())) + "\""; - } - result += "<celldesigner:gene" + attributes + ">"; - result += "<celldesigner:notes>"; - result += "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title/></head><body>"; - RestAnnotationParser rap = new RestAnnotationParser(); - result += rap.createAnnotationString(gene); - result += gene.getNotes(); - result += "</body></html>"; - result += "</celldesigner:notes>"; - - if (gene.getModificationResidues().size() > 0) { - result += "<celldesigner:listOfRegions>\n"; - for (ModificationResidue mr : gene.getModificationResidues()) { - result += modificationResidueXmlParser.toXml(mr); - } - result += "</celldesigner:listOfRegions>\n"; - } - - result += "</celldesigner:gene>"; - return result; - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesData.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesData.java index 26770e3b4a..0c97522c1b 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesData.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesData.java @@ -1,25 +1,13 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerAntisenseRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerDegraded; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerDrug; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerIon; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerPhenotype; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSimpleMolecule; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerUnknown; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; /** * This class contains information about all species in model that are relevant @@ -30,185 +18,185 @@ import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerUnknown */ public class InternalModelSpeciesData { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(InternalModelSpeciesData.class); - - /** - * Collection of proteins. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerProtein<?>> proteins; - - /** - * Collection of genes. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerGene> genes; - - /** - * Collection of genes. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerRna> rnas; - - /** - * Collection of antisense rnas. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerAntisenseRna> antisenseRnas; - - /** - * Collection of phenotypes. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerPhenotype> phenotypes; - - /** - * Collection of ions. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerIon> ions; - - /** - * Collection of simple molecules. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerSimpleMolecule> simpleMolecules; - - /** - * Collection of drugs. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerDrug> drugs; - - /** - * Collection of unknowns. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerUnknown> unknowns; - - /** - * Collection of degraded elements. Used only by the CellDesigner parser. - */ - private SpeciesCollection<CellDesignerDegraded> degradeds; - - /** - * Collection of complexes. - */ - private List<CellDesignerComplexSpecies> complexes = new ArrayList<>(); - - /** - * Default constructor. - */ - public InternalModelSpeciesData() { - proteins = new SpeciesCollection<>(); - genes = new SpeciesCollection<>(); - rnas = new SpeciesCollection<>(); - antisenseRnas = new SpeciesCollection<>(); - phenotypes = new SpeciesCollection<>(); - ions = new SpeciesCollection<>(); - simpleMolecules = new SpeciesCollection<>(); - drugs = new SpeciesCollection<>(); - unknowns = new SpeciesCollection<>(); - degradeds = new SpeciesCollection<>(); - } - - /** - * - * @return {@link #proteins} - */ - public Collection<CellDesignerProtein<?>> getProteins() { - return proteins.getAll(); - } - - /** - * - * @return {@link #genes} - */ - public Collection<CellDesignerGene> getGenes() { - return genes.getAll(); - } - - /** - * - * @return {@link #rnas} - */ - public Collection<CellDesignerRna> getRnas() { - return rnas.getAll(); - } - - /** - * - * @return {@link #antisenseRnas} - */ - public Collection<CellDesignerAntisenseRna> getAntisenseRnas() { - return antisenseRnas.getAll(); - } - - /** - * Updates information about species in the dataset. - * - * @param collection - * set of species to be updated, first element in pair defines - * celldesigner identifier, second is the species - */ - public void updateSpecies(Collection<Pair<String, ? extends CellDesignerSpecies<?>>> collection) { - for (Pair<String, ? extends CellDesignerSpecies<?>> species : collection) { - updateSpecies(species.getRight(), species.getLeft()); - } - } - - /** - * Updates information about species in the dataset (identified by - * celldesigner specific identifier). - * - * @param sp - * species to be updated - * @param identifier - * celldesigner identifier - */ - public void updateSpecies(CellDesignerSpecies<?> sp, String identifier) { - if (sp instanceof CellDesignerGene) { - genes.updateSpeciesByLocalId((CellDesignerGene) sp, identifier); - } else if (sp instanceof CellDesignerProtein) { - proteins.updateSpeciesByLocalId((CellDesignerProtein<?>) sp, identifier); - } else if (sp instanceof CellDesignerRna) { - rnas.updateSpeciesByLocalId((CellDesignerRna) sp, identifier); - } else if (sp instanceof CellDesignerAntisenseRna) { - antisenseRnas.updateSpeciesByLocalId((CellDesignerAntisenseRna) sp, identifier); - } else if (sp instanceof CellDesignerDegraded) { - degradeds.updateSpeciesByLocalId((CellDesignerDegraded) sp, identifier); - } else if (sp instanceof CellDesignerUnknown) { - unknowns.updateSpeciesByLocalId((CellDesignerUnknown) sp, identifier); - } else if (sp instanceof CellDesignerDrug) { - drugs.updateSpeciesByLocalId((CellDesignerDrug) sp, identifier); - } else if (sp instanceof CellDesignerSimpleMolecule) { - simpleMolecules.updateSpeciesByLocalId((CellDesignerSimpleMolecule) sp, identifier); - } else if (sp instanceof CellDesignerIon) { - ions.updateSpeciesByLocalId((CellDesignerIon) sp, identifier); - } else if (sp instanceof CellDesignerPhenotype) { - phenotypes.updateSpeciesByLocalId((CellDesignerPhenotype) sp, identifier); - } else if (sp instanceof CellDesignerComplexSpecies) { - complexes.add((CellDesignerComplexSpecies) sp); - } else { - throw new InvalidArgumentException("Unknown species type: " + sp.getClass().getName()); - } - } - - /** - * Returns list of all species in dataset. - * - * @return list of all species in dataset - */ - public Collection<CellDesignerSpecies<?>> getAll() { - List<CellDesignerSpecies<?>> result = new ArrayList<>(); - - result.addAll(genes.getAll()); - result.addAll(rnas.getAll()); - result.addAll(antisenseRnas.getAll()); - result.addAll(phenotypes.getAll()); - result.addAll(ions.getAll()); - result.addAll(simpleMolecules.getAll()); - result.addAll(drugs.getAll()); - result.addAll(unknowns.getAll()); - result.addAll(degradeds.getAll()); - result.addAll(proteins.getAll()); - result.addAll(complexes); - - return result; - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(InternalModelSpeciesData.class); + + /** + * Collection of proteins. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerProtein<?>> proteins; + + /** + * Collection of genes. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerGene> genes; + + /** + * Collection of genes. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerRna> rnas; + + /** + * Collection of antisense rnas. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerAntisenseRna> antisenseRnas; + + /** + * Collection of phenotypes. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerPhenotype> phenotypes; + + /** + * Collection of ions. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerIon> ions; + + /** + * Collection of simple molecules. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerSimpleMolecule> simpleMolecules; + + /** + * Collection of drugs. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerDrug> drugs; + + /** + * Collection of unknowns. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerUnknown> unknowns; + + /** + * Collection of degraded elements. Used only by the CellDesigner parser. + */ + private SpeciesCollection<CellDesignerDegraded> degradeds; + + /** + * Collection of complexes. + */ + private List<CellDesignerComplexSpecies> complexes = new ArrayList<>(); + + /** + * Default constructor. + */ + public InternalModelSpeciesData() { + proteins = new SpeciesCollection<>(); + genes = new SpeciesCollection<>(); + rnas = new SpeciesCollection<>(); + antisenseRnas = new SpeciesCollection<>(); + phenotypes = new SpeciesCollection<>(); + ions = new SpeciesCollection<>(); + simpleMolecules = new SpeciesCollection<>(); + drugs = new SpeciesCollection<>(); + unknowns = new SpeciesCollection<>(); + degradeds = new SpeciesCollection<>(); + } + + /** + * + * @return {@link #proteins} + */ + public Collection<CellDesignerProtein<?>> getProteins() { + return proteins.getAll(); + } + + /** + * + * @return {@link #genes} + */ + public Collection<CellDesignerGene> getGenes() { + return genes.getAll(); + } + + /** + * + * @return {@link #rnas} + */ + public Collection<CellDesignerRna> getRnas() { + return rnas.getAll(); + } + + /** + * + * @return {@link #antisenseRnas} + */ + public Collection<CellDesignerAntisenseRna> getAntisenseRnas() { + return antisenseRnas.getAll(); + } + + /** + * Updates information about species in the dataset. + * + * @param collection + * set of species to be updated, first element in pair defines + * celldesigner identifier, second is the species + */ + public void updateSpecies(Collection<Pair<String, ? extends CellDesignerSpecies<?>>> collection) { + for (Pair<String, ? extends CellDesignerSpecies<?>> species : collection) { + updateSpecies(species.getRight(), species.getLeft()); + } + } + + /** + * Updates information about species in the dataset (identified by celldesigner + * specific identifier). + * + * @param sp + * species to be updated + * @param identifier + * celldesigner identifier + */ + public void updateSpecies(CellDesignerSpecies<?> sp, String identifier) { + if (sp instanceof CellDesignerGene) { + genes.updateSpeciesByLocalId((CellDesignerGene) sp, identifier); + } else if (sp instanceof CellDesignerProtein) { + proteins.updateSpeciesByLocalId((CellDesignerProtein<?>) sp, identifier); + } else if (sp instanceof CellDesignerRna) { + rnas.updateSpeciesByLocalId((CellDesignerRna) sp, identifier); + } else if (sp instanceof CellDesignerAntisenseRna) { + antisenseRnas.updateSpeciesByLocalId((CellDesignerAntisenseRna) sp, identifier); + } else if (sp instanceof CellDesignerDegraded) { + degradeds.updateSpeciesByLocalId((CellDesignerDegraded) sp, identifier); + } else if (sp instanceof CellDesignerUnknown) { + unknowns.updateSpeciesByLocalId((CellDesignerUnknown) sp, identifier); + } else if (sp instanceof CellDesignerDrug) { + drugs.updateSpeciesByLocalId((CellDesignerDrug) sp, identifier); + } else if (sp instanceof CellDesignerSimpleMolecule) { + simpleMolecules.updateSpeciesByLocalId((CellDesignerSimpleMolecule) sp, identifier); + } else if (sp instanceof CellDesignerIon) { + ions.updateSpeciesByLocalId((CellDesignerIon) sp, identifier); + } else if (sp instanceof CellDesignerPhenotype) { + phenotypes.updateSpeciesByLocalId((CellDesignerPhenotype) sp, identifier); + } else if (sp instanceof CellDesignerComplexSpecies) { + complexes.add((CellDesignerComplexSpecies) sp); + } else { + throw new InvalidArgumentException("Unknown species type: " + sp.getClass().getName()); + } + } + + /** + * Returns list of all species in dataset. + * + * @return list of all species in dataset + */ + public Collection<CellDesignerSpecies<?>> getAll() { + List<CellDesignerSpecies<?>> result = new ArrayList<>(); + + result.addAll(genes.getAll()); + result.addAll(rnas.getAll()); + result.addAll(antisenseRnas.getAll()); + result.addAll(phenotypes.getAll()); + result.addAll(ions.getAll()); + result.addAll(simpleMolecules.getAll()); + result.addAll(drugs.getAll()); + result.addAll(unknowns.getAll()); + result.addAll(degradeds.getAll()); + result.addAll(proteins.getAll()); + result.addAll(complexes); + + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParser.java index 36be726939..c2322a5dbb 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParser.java @@ -9,18 +9,8 @@ import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection import lcsb.mapviewer.converter.model.celldesigner.geometry.CellDesignerAliasConverter; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.ModificationType; -import lcsb.mapviewer.model.map.species.AntisenseRna; -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.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; public class ModificationResidueXmlParser { @@ -92,7 +82,8 @@ public class ModificationResidueXmlParser { * because we have to merge elements when exporting to CellDesigner and this * might introduce inconsistent identifiers. * - * @param region {@link ModificationResidue} for which we want to find out identifier + * @param region + * {@link ModificationResidue} for which we want to find out identifier * @return identifier that can be used in CellDesigner */ private String computeModificationResidueId(ModificationResidue region) { diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMapping.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMapping.java index 67dc601b64..8463544ddc 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMapping.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMapping.java @@ -1,18 +1,11 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGenericProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerIonChannelProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerReceptorProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerTruncatedProtein; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.TruncatedProtein; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; +import lcsb.mapviewer.model.map.species.*; /** * This enum contains information about mapping between CellDesigner xml nodes @@ -23,133 +16,131 @@ import lcsb.mapviewer.model.map.species.TruncatedProtein; */ public enum ProteinMapping { - /** - * {@link GenericProtein}. - */ - GENERIC_PROTEIN(GenericProtein.class, CellDesignerGenericProtein.class, "GENERIC"), - - /** - * {@link IonChannelProtein}. - */ - ION_CHANNEL_PROTEIN(IonChannelProtein.class, CellDesignerIonChannelProtein.class, "ION_CHANNEL"), - - /** - * {@link ReceptorProtein}. - */ - RECEPTOR_PROTEIN(ReceptorProtein.class, CellDesignerReceptorProtein.class, "RECEPTOR"), - - /** - * {@link TruncatedProtein}. - */ - TRUNCATED_PROTEIN(TruncatedProtein.class, CellDesignerTruncatedProtein.class, "TRUNCATED"); - - /** - * CellDesigner xml node type. - */ - private String cellDesignerString; - - /** - * Model class that should be used to represent cell designer node. - */ - private Class<? extends Protein> clazz; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(ProteinMapping.class); - - /** - * {@link CellDesignerProtein Celldesigner structure} used to represent the - * node. - */ - private Class<? extends CellDesignerProtein<?>> cellDesignerClazz; - - /** - * Default constructor. - * - * @param cellDesignerClazz - * {@link #clazz} - * @param modelClazz - * {@link #clazz class} in model corresponding to celldesigner object - * @param cellDesignerString - * {@link #cellDesignerString} - */ - ProteinMapping(Class<? extends Protein> modelClazz, Class<? extends CellDesignerProtein<?>> cellDesignerClazz, String cellDesignerString) { - this.cellDesignerString = cellDesignerString; - this.clazz = modelClazz; - this.cellDesignerClazz = cellDesignerClazz; - } - - /** - * @return the cellDesignerName - * @see #cellDesignerString - */ - public String getCellDesignerString() { - return cellDesignerString; - } - - /** - * @return the clazz - * @see #clazz - */ - public Class<? extends Protein> getClazz() { - return clazz; - } - - /** - * Returns celldesigner class type that represents xml node. - * - * @return celldesigner class type that represents xml node - */ - public Class<? extends CellDesignerProtein<?>> getCellDesignerClazz() { - return cellDesignerClazz; - } - - /** - * Returns {@link ProteinMapping} for given CellDesigner xml node name. - * - * @param string - * CellDesigner xml node name - * @return {@link ProteinMapping} for given CellDesigner xml node name - */ - public static ProteinMapping getMappingByString(String string) { - for (ProteinMapping mapping : ProteinMapping.values()) { - if (mapping.getCellDesignerString().equals(string)) { - return mapping; - } - } - return null; - } - - /** - * Returns {@link ProteinMapping} for given {@link CellDesignerProtein} class. - * - * @param searchClazz - * {@link CellDesignerProtein} class - * @return {@link ProteinMapping} for given {@link CellDesignerProtein} class - */ - public static ProteinMapping getMappingByClass(Class<? extends Protein> searchClazz) { - for (ProteinMapping mapping : ProteinMapping.values()) { - if (mapping.getClazz().isAssignableFrom(searchClazz)) { - return mapping; - } - } - return null; - } - - /** - * Creates instance of {@link CellDesignerProtein} specific for this - * {@link ProteinMapping}. - * - * @return new instance of {@link CellDesignerProtein} specific for this - * {@link ProteinMapping}. - */ - public CellDesignerProtein<?> createProtein() { - try { - return cellDesignerClazz.getConstructor().newInstance(); - } catch (Exception e) { - throw new InvalidStateException(e); - } - } + /** + * {@link GenericProtein}. + */ + GENERIC_PROTEIN(GenericProtein.class, CellDesignerGenericProtein.class, "GENERIC"), + + /** + * {@link IonChannelProtein}. + */ + ION_CHANNEL_PROTEIN(IonChannelProtein.class, CellDesignerIonChannelProtein.class, "ION_CHANNEL"), + + /** + * {@link ReceptorProtein}. + */ + RECEPTOR_PROTEIN(ReceptorProtein.class, CellDesignerReceptorProtein.class, "RECEPTOR"), + + /** + * {@link TruncatedProtein}. + */ + TRUNCATED_PROTEIN(TruncatedProtein.class, CellDesignerTruncatedProtein.class, "TRUNCATED"); + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(ProteinMapping.class); + /** + * CellDesigner xml node type. + */ + private String cellDesignerString; + /** + * Model class that should be used to represent cell designer node. + */ + private Class<? extends Protein> clazz; + /** + * {@link CellDesignerProtein Celldesigner structure} used to represent the + * node. + */ + private Class<? extends CellDesignerProtein<?>> cellDesignerClazz; + + /** + * Default constructor. + * + * @param cellDesignerClazz + * {@link #clazz} + * @param modelClazz + * {@link #clazz class} in model corresponding to celldesigner object + * @param cellDesignerString + * {@link #cellDesignerString} + */ + ProteinMapping(Class<? extends Protein> modelClazz, Class<? extends CellDesignerProtein<?>> cellDesignerClazz, + String cellDesignerString) { + this.cellDesignerString = cellDesignerString; + this.clazz = modelClazz; + this.cellDesignerClazz = cellDesignerClazz; + } + + /** + * Returns {@link ProteinMapping} for given CellDesigner xml node name. + * + * @param string + * CellDesigner xml node name + * @return {@link ProteinMapping} for given CellDesigner xml node name + */ + public static ProteinMapping getMappingByString(String string) { + for (ProteinMapping mapping : ProteinMapping.values()) { + if (mapping.getCellDesignerString().equals(string)) { + return mapping; + } + } + return null; + } + + /** + * Returns {@link ProteinMapping} for given {@link CellDesignerProtein} class. + * + * @param searchClazz + * {@link CellDesignerProtein} class + * @return {@link ProteinMapping} for given {@link CellDesignerProtein} class + */ + public static ProteinMapping getMappingByClass(Class<? extends Protein> searchClazz) { + for (ProteinMapping mapping : ProteinMapping.values()) { + if (mapping.getClazz().isAssignableFrom(searchClazz)) { + return mapping; + } + } + return null; + } + + /** + * @return the cellDesignerName + * @see #cellDesignerString + */ + public String getCellDesignerString() { + return cellDesignerString; + } + + /** + * @return the clazz + * @see #clazz + */ + public Class<? extends Protein> getClazz() { + return clazz; + } + + /** + * Returns celldesigner class type that represents xml node. + * + * @return celldesigner class type that represents xml node + */ + public Class<? extends CellDesignerProtein<?>> getCellDesignerClazz() { + return cellDesignerClazz; + } + + /** + * Creates instance of {@link CellDesignerProtein} specific for this + * {@link ProteinMapping}. + * + * @return new instance of {@link CellDesignerProtein} specific for this + * {@link ProteinMapping}. + */ + public CellDesignerProtein<?> createProtein() { + try { + return cellDesignerClazz.getConstructor().newInstance(); + } catch (Exception e) { + throw new InvalidStateException(e); + } + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java index 4066b611b6..019ca19c7d 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParser.java @@ -3,12 +3,13 @@ package lcsb.mapviewer.converter.model.celldesigner.species; import java.util.ArrayList; import java.util.List; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.Pair; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; @@ -17,9 +18,7 @@ import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.ModificationType; import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.species.field.*; /** * Class that performs parsing of the CellDesigner xml for diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java index 3520d7bae2..afc3f7e985 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/RnaXmlParser.java @@ -1,11 +1,12 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.Pair; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; @@ -85,34 +86,6 @@ public class RnaXmlParser extends AbstractElementXmlParser<CellDesignerRna, Rna> return new Pair<String, CellDesignerRna>(identifier, rna); } - /** - * Parses CellDesigner xml node for RnaRegion. - * - * @param residueNode - * xml node to parse - * @return {@link CellDesignerModificationResidue} object created from the node - * @throws InvalidXmlSchemaException - * thrown when input xml node doesn't follow defined schema - */ - private CellDesignerModificationResidue getRnaRegion(Node residueNode) throws InvalidXmlSchemaException { - CellDesignerModificationResidue residue = new CellDesignerModificationResidue(); - residue.setIdModificationResidue(XmlParser.getNodeAttr("id", residueNode)); - residue.setSize(XmlParser.getNodeAttr("size", residueNode)); - residue.setPos(XmlParser.getNodeAttr("pos", residueNode)); - String typeString = XmlParser.getNodeAttr("type", residueNode); - if (typeString != null) { - residue.setModificationType(ModificationType.getByCellDesignerName(typeString)); - } - NodeList list = residueNode.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - Node node = list.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - throw new InvalidXmlSchemaException("Unknown element of celldesigner:region " + node.getNodeName()); - } - } - return residue; - } - @Override public String toXml(Rna rna) { String attributes = ""; @@ -142,4 +115,32 @@ public class RnaXmlParser extends AbstractElementXmlParser<CellDesignerRna, Rna> return result; } + /** + * Parses CellDesigner xml node for RnaRegion. + * + * @param residueNode + * xml node to parse + * @return {@link CellDesignerModificationResidue} object created from the node + * @throws InvalidXmlSchemaException + * thrown when input xml node doesn't follow defined schema + */ + private CellDesignerModificationResidue getRnaRegion(Node residueNode) throws InvalidXmlSchemaException { + CellDesignerModificationResidue residue = new CellDesignerModificationResidue(); + residue.setIdModificationResidue(XmlParser.getNodeAttr("id", residueNode)); + residue.setSize(XmlParser.getNodeAttr("size", residueNode)); + residue.setPos(XmlParser.getNodeAttr("pos", residueNode)); + String typeString = XmlParser.getNodeAttr("type", residueNode); + if (typeString != null) { + residue.setModificationType(ModificationType.getByCellDesignerName(typeString)); + } + NodeList list = residueNode.getChildNodes(); + for (int i = 0; i < list.getLength(); i++) { + Node node = list.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + throw new InvalidXmlSchemaException("Unknown element of celldesigner:region " + node.getNodeName()); + } + } + return residue; + } + } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollection.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollection.java index 731647113e..3326eb4223 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollection.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesCollection.java @@ -1,11 +1,9 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; @@ -25,149 +23,149 @@ import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies */ public class SpeciesCollection<C extends CellDesignerSpecies<?>> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(SpeciesCollection.class.getName()); - - /** - * List of all elements added to this collection. - */ - private ArrayList<C> allElements; - - /** - * Map of species identified by specific identifier of the species (like - * {@link lcsb.mapviewer.db.model.map.species.CellDesignerProtein#proteinId - * Protein#proteinId}. - */ - private Map<String, ArrayList<C>> speciesListByLocalId; - - /** - * Default Constructor. Initializes collection. Checks if method signature is - * proper. - * - */ - public SpeciesCollection() { - allElements = new ArrayList<C>(); - speciesListByLocalId = new HashMap<String, ArrayList<C>>(); - } - - /** - * Adds element to collection. - * - * @param localId - * celldesigner identifier - * @param element - * object to add - */ - public void add(C element, String localId) { - ArrayList<C> list = speciesListByLocalId.get(localId); - if (list == null) { - list = new ArrayList<C>(); - speciesListByLocalId.put(localId, list); - } - list.add(element); - allElements.add(element); - } - - /** - * Returns list of species identifierd by local species specific identifier. - * - * @param localId - * identifier of this species will be used to return the list - * @return list of species identifierd by local species specific identifier - */ - public ArrayList<C> getSpeciesListByLocalId(String localId) { - return speciesListByLocalId.get(localId); - } - - /** - * This method is magic :). It updates information in every element in the - * collection when the information should be propagated. And add species to - * the collection when necessary. - * - * @param sp - * data from this species should be propagated to other species - * @param identifier - * celldesigner identifier that determine which elements should be - * modified - */ - public void updateSpeciesByLocalId(C sp, String identifier) { - C result = null; - - ArrayList<C> list = getSpeciesListByLocalId(identifier); - if (list == null || list.size() == 0) { - result = sp; - add(sp, identifier); - } else { - ArrayList<C> toRemove = new ArrayList<C>(); - ArrayList<C> toAdd = new ArrayList<C>(); - for (C c : list) { - // propagate the data only when idSpecies is not set or the idSpecies is - // equlas to the one from which we updating data - if (c.getElementId().equals("") || c.getElementId().equals(sp.getElementId())) { - c.update(sp); - if (c.getClass() != sp.getClass() && c.getClass().isAssignableFrom(sp.getClass())) { - toRemove.add(c); - C newInstance = createNewInstance(sp.getClass(), c); - toAdd.add(newInstance); - result = newInstance; - } else { - result = c; - } - } else if (sp.getElementId().equals("")) { - c.update(sp); - if (c.getClass() != sp.getClass() && c.getClass().isAssignableFrom(sp.getClass())) { - toRemove.add(c); - C newInstance = createNewInstance(sp.getClass(), c); - toAdd.add(newInstance); - result = newInstance; - } else { - result = c; - } - } - } - list.removeAll(toRemove); - list.addAll(toAdd); - allElements.removeAll(toRemove); - allElements.addAll(toAdd); - - // if we haven't found any object to update then probably we have to add - // species to the collection - if (result == null) { - result = sp; - add(result, identifier); - } - } - } - - /** - * Creates a new instance of the object defined by clazz parameter and - * initialized by c parameter. - * - * @param clazz - * class of the object - * @param c - * original object and param of the constructor - * @return new instance of the object - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected C createNewInstance(Class clazz, C c) { - try { - return (C) clazz.getConstructor(CellDesignerSpecies.class).newInstance(c); - } catch (Exception e) { - throw new InvalidStateException("Problem with creating object", e); - } - } - - /** - * Returns all elements from collection. - * - * @return collection with all elements - */ - public Collection<C> getAll() { - return allElements; - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(SpeciesCollection.class.getName()); + + /** + * List of all elements added to this collection. + */ + private ArrayList<C> allElements; + + /** + * Map of species identified by specific identifier of the species (like + * {@link lcsb.mapviewer.db.model.map.species.CellDesignerProtein#proteinId + * Protein#proteinId}. + */ + private Map<String, ArrayList<C>> speciesListByLocalId; + + /** + * Default Constructor. Initializes collection. Checks if method signature is + * proper. + * + */ + public SpeciesCollection() { + allElements = new ArrayList<C>(); + speciesListByLocalId = new HashMap<String, ArrayList<C>>(); + } + + /** + * Adds element to collection. + * + * @param localId + * celldesigner identifier + * @param element + * object to add + */ + public void add(C element, String localId) { + ArrayList<C> list = speciesListByLocalId.get(localId); + if (list == null) { + list = new ArrayList<C>(); + speciesListByLocalId.put(localId, list); + } + list.add(element); + allElements.add(element); + } + + /** + * Returns list of species identifierd by local species specific identifier. + * + * @param localId + * identifier of this species will be used to return the list + * @return list of species identifierd by local species specific identifier + */ + public ArrayList<C> getSpeciesListByLocalId(String localId) { + return speciesListByLocalId.get(localId); + } + + /** + * This method is magic :). It updates information in every element in the + * collection when the information should be propagated. And add species to the + * collection when necessary. + * + * @param sp + * data from this species should be propagated to other species + * @param identifier + * celldesigner identifier that determine which elements should be + * modified + */ + public void updateSpeciesByLocalId(C sp, String identifier) { + C result = null; + + ArrayList<C> list = getSpeciesListByLocalId(identifier); + if (list == null || list.size() == 0) { + result = sp; + add(sp, identifier); + } else { + ArrayList<C> toRemove = new ArrayList<C>(); + ArrayList<C> toAdd = new ArrayList<C>(); + for (C c : list) { + // propagate the data only when idSpecies is not set or the idSpecies is + // equlas to the one from which we updating data + if (c.getElementId().equals("") || c.getElementId().equals(sp.getElementId())) { + c.update(sp); + if (c.getClass() != sp.getClass() && c.getClass().isAssignableFrom(sp.getClass())) { + toRemove.add(c); + C newInstance = createNewInstance(sp.getClass(), c); + toAdd.add(newInstance); + result = newInstance; + } else { + result = c; + } + } else if (sp.getElementId().equals("")) { + c.update(sp); + if (c.getClass() != sp.getClass() && c.getClass().isAssignableFrom(sp.getClass())) { + toRemove.add(c); + C newInstance = createNewInstance(sp.getClass(), c); + toAdd.add(newInstance); + result = newInstance; + } else { + result = c; + } + } + } + list.removeAll(toRemove); + list.addAll(toAdd); + allElements.removeAll(toRemove); + allElements.addAll(toAdd); + + // if we haven't found any object to update then probably we have to add + // species to the collection + if (result == null) { + result = sp; + add(result, identifier); + } + } + } + + /** + * Creates a new instance of the object defined by clazz parameter and + * initialized by c parameter. + * + * @param clazz + * class of the object + * @param c + * original object and param of the constructor + * @return new instance of the object + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected C createNewInstance(Class clazz, C c) { + try { + return (C) clazz.getConstructor(CellDesignerSpecies.class).newInstance(c); + } catch (Exception e) { + throw new InvalidStateException("Problem with creating object", e); + } + } + + /** + * Returns all elements from collection. + * + * @return collection with all elements + */ + public Collection<C> getAll() { + return allElements; + } } 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 fcec0ffa91..c7647412b1 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 @@ -1,10 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -18,20 +14,9 @@ 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.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; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.model.map.InconsistentModelException; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -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.model.map.species.*; /** * Class used to parse CellDesigner xml nodes containing collections of @@ -88,8 +73,9 @@ public class SpeciesCollectionXmlParser { */ private AbstractElementXmlParser<CellDesignerElement<?>, Element> helpParser = new AbstractElementXmlParser<CellDesignerElement<?>, Element>() { @Override - public String encodeName(String name) { - return super.encodeName(name); + public Pair<String, CellDesignerElement<?>> parseXmlElement(Node node) + throws InvalidXmlSchemaException { + throw new NotImplementedException(); } @Override @@ -98,9 +84,8 @@ public class SpeciesCollectionXmlParser { } @Override - public Pair<String, CellDesignerElement<?>> parseXmlElement(Node node) - throws InvalidXmlSchemaException { - throw new NotImplementedException(); + public String encodeName(String name) { + return super.encodeName(name); } }; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMapping.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMapping.java index c086811d0c..c16ecad2f3 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMapping.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMapping.java @@ -1,30 +1,8 @@ package lcsb.mapviewer.converter.model.celldesigner.species; import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerAntisenseRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerComplexSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerDegraded; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerDrug; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerIon; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerPhenotype; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSimpleMolecule; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerUnknown; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; +import lcsb.mapviewer.model.map.species.*; /** * This enum contains information about mapping between CellDesigner xml nodes @@ -121,14 +99,35 @@ public enum SpeciesMapping { } /** - * Sets new cellDesignerClazz value. - * - * @param cellDesignerClazz2 - * new cellDesignerClazz value + * Returns {@link SpeciesMapping} for given CellDesigner xml node name. + * + * @param string + * CellDesigner xml node name + * @return {@link SpeciesMapping} for given CellDesigner xml node name */ - @SuppressWarnings("unchecked") - private void setCellDesignerClazz(Class<?> cellDesignerClazz2) { - cellDesignerClazz = (Class<? extends CellDesignerSpecies<?>>) cellDesignerClazz2; + public static SpeciesMapping getMappingByString(String string) { + for (SpeciesMapping mapping : SpeciesMapping.values()) { + if (mapping.getCellDesignerString().equalsIgnoreCase(string)) { + return mapping; + } + } + return null; + } + + /** + * Returns {@link SpeciesMapping} for given {@link CellDesignerSpecies} class. + * + * @param searchClazz + * {@link CellDesignerSpecies} class + * @return {@link SpeciesMapping} for given {@link CellDesignerSpecies} class + */ + public static SpeciesMapping getMappingByModelClass(Class<? extends Element> searchClazz) { + for (SpeciesMapping mapping : SpeciesMapping.values()) { + if (mapping.getModelClazz().isAssignableFrom(searchClazz)) { + return mapping; + } + } + return null; } /** @@ -147,9 +146,20 @@ public enum SpeciesMapping { return cellDesignerClazz; } + /** + * Sets new cellDesignerClazz value. + * + * @param cellDesignerClazz2 + * new cellDesignerClazz value + */ + @SuppressWarnings("unchecked") + private void setCellDesignerClazz(Class<?> cellDesignerClazz2) { + cellDesignerClazz = (Class<? extends CellDesignerSpecies<?>>) cellDesignerClazz2; + } + /** * Returns model class that represent the species. - * + * * @return model class that represent the species */ public Class<? extends Element> getModelClazz() { @@ -159,7 +169,7 @@ public enum SpeciesMapping { /** * Creates instance of {@link CellDesignerSpecies} specific for this * {@link SpeciesMapping}. - * + * * @param result * parameter that should be passed to the constructor * @return new instance of {@link CellDesignerSpecies} specific for this @@ -172,36 +182,4 @@ public enum SpeciesMapping { throw new InvalidStateException(e); } } - - /** - * Returns {@link SpeciesMapping} for given CellDesigner xml node name. - * - * @param string - * CellDesigner xml node name - * @return {@link SpeciesMapping} for given CellDesigner xml node name - */ - public static SpeciesMapping getMappingByString(String string) { - for (SpeciesMapping mapping : SpeciesMapping.values()) { - if (mapping.getCellDesignerString().equalsIgnoreCase(string)) { - return mapping; - } - } - return null; - } - - /** - * Returns {@link SpeciesMapping} for given {@link CellDesignerSpecies} class. - * - * @param searchClazz - * {@link CellDesignerSpecies} class - * @return {@link SpeciesMapping} for given {@link CellDesignerSpecies} class - */ - public static SpeciesMapping getMappingByModelClass(Class<? extends Element> searchClazz) { - for (SpeciesMapping mapping : SpeciesMapping.values()) { - if (mapping.getModelClazz().isAssignableFrom(searchClazz)) { - return mapping; - } - } - return null; - } } 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 27cdf027f8..de2bdea00a 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 @@ -1,37 +1,24 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +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.Pair; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.XmlParser; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.annotation.XmlAnnotationParser; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; 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; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerElement; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerGene; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerProtein; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerRna; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSimpleMolecule; -import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; +import lcsb.mapviewer.converter.model.celldesigner.structure.*; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.SpeciesState; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.species.AntisenseRna; -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.model.map.species.*; import lcsb.mapviewer.model.map.species.field.ModificationState; import lcsb.mapviewer.model.map.species.field.PositionToCompartment; @@ -146,7 +133,8 @@ public class SpeciesSbmlParser extends AbstractElementXmlParser<CellDesignerSpec if (positionToCompartment != null) { PositionToCompartment position = PositionToCompartment.getByString(XmlParser.getNodeValue(positionToCompartment)); if (position == null) { - throw new InvalidXmlSchemaException("Unknown position on compartment: " + XmlParser.getNodeValue(positionToCompartment)); + throw new InvalidXmlSchemaException( + "Unknown position on compartment: " + XmlParser.getNodeValue(positionToCompartment)); } species.setPositionToCompartment(position); } @@ -170,7 +158,8 @@ public class SpeciesSbmlParser extends AbstractElementXmlParser<CellDesignerSpec species.setBoundaryCondition(XmlParser.getNodeAttr("boundaryCondition", spieciesNode)); species.setConstant(XmlParser.getNodeAttr("constant", spieciesNode)); - CellDesignerCompartment compartment = elements.getElementByElementId(XmlParser.getNodeAttr("compartment", spieciesNode)); + CellDesignerCompartment compartment = elements + .getElementByElementId(XmlParser.getNodeAttr("compartment", spieciesNode)); if (compartment != null) { species.setParent(compartment); } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/package-info.java index 6f59a20abe..5d519a76ca 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/species/package-info.java @@ -3,4 +3,3 @@ * {@link lcsb.mapviewer.db.model.map.species.CellDesignerSpecies Species}. */ package lcsb.mapviewer.converter.model.celldesigner.species; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerAntisenseRna.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerAntisenseRna.java index 942d2f895b..7b4ee8990f 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerAntisenseRna.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerAntisenseRna.java @@ -3,17 +3,15 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.AntisenseRna; import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; +import lcsb.mapviewer.model.map.species.field.*; /** * Class representing CellDesigner {@link AntisenseRna}. @@ -62,21 +60,12 @@ public class CellDesignerAntisenseRna extends CellDesignerSpecies<AntisenseRna> super(); } - @Override - public CellDesignerAntisenseRna copy() { - if (this.getClass() == CellDesignerAntisenseRna.class) { - return new CellDesignerAntisenseRna(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - /** * Add antisense rna region (part of rna sequence that has some meaning) to the * object. If the region with given id exists then the data of this region is * copied to the one that is already in the {@link CellDesignerAntisenseRna}. - * - * + * + * * @param region * region to add */ @@ -102,11 +91,44 @@ public class CellDesignerAntisenseRna extends CellDesignerSpecies<AntisenseRna> } } + @Override + public CellDesignerAntisenseRna copy() { + if (this.getClass() == CellDesignerAntisenseRna.class) { + return new CellDesignerAntisenseRna(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + @Override + public AntisenseRna createModelElement(String aliasId) { + AntisenseRna result = new AntisenseRna(aliasId); + super.setModelObjectFields(result); + return result; + } + + @Override + public void updateModelElementAfterLayoutAdded(Species species) { + AntisenseRna antisenseRna = (AntisenseRna) species; + for (CellDesignerModificationResidue region : regions) { + ModificationResidue mr = region.createModificationResidue(antisenseRna); + if (mr instanceof CodingRegion) { + antisenseRna.addCodingRegion((CodingRegion) mr); + } else if (mr instanceof ModificationSite) { + antisenseRna.addModificationSite((ModificationSite) mr); + } else if (mr instanceof ProteinBindingDomain) { + antisenseRna.addProteinBindingDomain((ProteinBindingDomain) mr); + } else { + throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); + } + } + } + /** * Method update antisense rna region from the object in params (if the object * with the same id already exists). If there is no object with given id then * new object is added to antisense rna. - * + * * @param param * - object with new data from where update should be performed */ @@ -137,28 +159,4 @@ public class CellDesignerAntisenseRna extends CellDesignerSpecies<AntisenseRna> this.regions = regions; } - @Override - public AntisenseRna createModelElement(String aliasId) { - AntisenseRna result = new AntisenseRna(aliasId); - super.setModelObjectFields(result); - return result; - } - - @Override - public void updateModelElementAfterLayoutAdded(Species species) { - AntisenseRna antisenseRna = (AntisenseRna) species; - for (CellDesignerModificationResidue region : regions) { - ModificationResidue mr = region.createModificationResidue(antisenseRna); - if (mr instanceof CodingRegion) { - antisenseRna.addCodingRegion((CodingRegion) mr); - } else if (mr instanceof ModificationSite) { - antisenseRna.addModificationSite((ModificationSite) mr); - } else if (mr instanceof ProteinBindingDomain) { - antisenseRna.addProteinBindingDomain((ProteinBindingDomain) mr); - } else { - throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); - } - } - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemical.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemical.java index 0146ba0bbd..f2cad15edd 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemical.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemical.java @@ -13,113 +13,113 @@ import lcsb.mapviewer.model.map.species.Chemical; */ public abstract class CellDesignerChemical<T extends Chemical> extends CellDesignerSpecies<T> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * <a href= - * "http://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system" - * >Smiles</a> parameter for the chemical. - */ - private String smiles; - - /** - * <a href= "http://en.wikipedia.org/wiki/International_Chemical_Identifier" > - * InChI</a> parameter for the chemical. - */ - - private String inChI; - - /** - * <a href= - * "http://en.wikipedia.org/wiki/International_Chemical_Identifier#InChIKey" > - * InChIKey</a> parameter for the chemical. - */ - - private String inChIKey; - - /** - * Creates a chemical from the species given in the parameter. - * - * @param species - * original species from which this chemical will be created - */ - public CellDesignerChemical(CellDesignerSpecies<?> species) { - super(species); - if (species instanceof CellDesignerChemical) { - CellDesignerChemical<?> chemical = (CellDesignerChemical<?>) species; - this.smiles = chemical.smiles; - this.inChI = chemical.inChI; - this.inChIKey = chemical.inChIKey; - } - } - - /** - * Default constructor. - */ - public CellDesignerChemical() { - super(); - } - - /** - * @return the smiles - * @see #smiles - */ - public String getSmiles() { - return smiles; - } - - /** - * @param smiles - * the smiles to set - * @see #smiles - */ - public void setSmiles(String smiles) { - this.smiles = smiles; - } - - /** - * @return the inChI - * @see #inChI - */ - public String getInChI() { - return inChI; - } - - /** - * @param inChI - * the inChI to set - * @see #inChI - */ - public void setInChI(String inChI) { - this.inChI = inChI; - } - - /** - * @return the inChIKey - * @see #inChIKey - */ - public String getInChIKey() { - return inChIKey; - } - - /** - * @param inChIKey - * the inChIKey to set - * @see #inChIKey - */ - public void setInChIKey(String inChIKey) { - this.inChIKey = inChIKey; - } - - @Override - protected void setModelObjectFields(T result) { - super.setModelObjectFields(result); - result.setInChI(inChI); - result.setInChIKey(inChIKey); - result.setSmiles(smiles); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * <a href= + * "http://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system" + * >Smiles</a> parameter for the chemical. + */ + private String smiles; + + /** + * <a href= "http://en.wikipedia.org/wiki/International_Chemical_Identifier" > + * InChI</a> parameter for the chemical. + */ + + private String inChI; + + /** + * <a href= + * "http://en.wikipedia.org/wiki/International_Chemical_Identifier#InChIKey" > + * InChIKey</a> parameter for the chemical. + */ + + private String inChIKey; + + /** + * Creates a chemical from the species given in the parameter. + * + * @param species + * original species from which this chemical will be created + */ + public CellDesignerChemical(CellDesignerSpecies<?> species) { + super(species); + if (species instanceof CellDesignerChemical) { + CellDesignerChemical<?> chemical = (CellDesignerChemical<?>) species; + this.smiles = chemical.smiles; + this.inChI = chemical.inChI; + this.inChIKey = chemical.inChIKey; + } + } + + /** + * Default constructor. + */ + public CellDesignerChemical() { + super(); + } + + /** + * @return the smiles + * @see #smiles + */ + public String getSmiles() { + return smiles; + } + + /** + * @param smiles + * the smiles to set + * @see #smiles + */ + public void setSmiles(String smiles) { + this.smiles = smiles; + } + + /** + * @return the inChI + * @see #inChI + */ + public String getInChI() { + return inChI; + } + + /** + * @param inChI + * the inChI to set + * @see #inChI + */ + public void setInChI(String inChI) { + this.inChI = inChI; + } + + /** + * @return the inChIKey + * @see #inChIKey + */ + public String getInChIKey() { + return inChIKey; + } + + /** + * @param inChIKey + * the inChIKey to set + * @see #inChIKey + */ + public void setInChIKey(String inChIKey) { + this.inChIKey = inChIKey; + } + + @Override + protected void setModelObjectFields(T result) { + super.setModelObjectFields(result); + result.setInChI(inChI); + result.setInChIKey(inChIKey); + result.setSmiles(smiles); + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerCompartment.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerCompartment.java index e33cb055d9..35116e044d 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerCompartment.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerCompartment.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.compartment.Compartment; @@ -84,6 +85,12 @@ public class CellDesignerCompartment extends CellDesignerElement<Compartment> return 0; } + @Override + public int hashCode() { + String result = compartmentId + "_" + getName(); + return result.hashCode(); + } + @Override public boolean equals(Object param) { if (this == param) { @@ -97,9 +104,13 @@ public class CellDesignerCompartment extends CellDesignerElement<Compartment> } @Override - public int hashCode() { - String result = compartmentId + "_" + getName(); - return result.hashCode(); + public String getElementId() { + return compartmentId; + } + + @Override + public void setElementId(String id) { + this.compartmentId = id; } @Override @@ -111,18 +122,18 @@ public class CellDesignerCompartment extends CellDesignerElement<Compartment> } @Override - public String getElementId() { - return compartmentId; - } - - @Override - public void setElementId(String id) { - this.compartmentId = id; + public Compartment createModelElement(String aliasId) { + Compartment result = new Compartment(aliasId); + super.setModelObjectFields(result); + if (elements.size() > 0) { + throw new NotImplementedException(); + } + return result; } /** * Adds element. - * + * * @param element * element to add */ @@ -132,21 +143,11 @@ public class CellDesignerCompartment extends CellDesignerElement<Compartment> } /** - * + * * @return {@link #elements} */ public Set<CellDesignerElement<?>> getElements() { return elements; } - @Override - public Compartment createModelElement(String aliasId) { - Compartment result = new Compartment(aliasId); - super.setModelObjectFields(result); - if (elements.size() > 0) { - throw new NotImplementedException(); - } - return result; - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerComplexSpecies.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerComplexSpecies.java index 0de3bc46d8..2a815be82a 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerComplexSpecies.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerComplexSpecies.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -17,154 +18,155 @@ import lcsb.mapviewer.model.map.species.Complex; */ public class CellDesignerComplexSpecies extends CellDesignerSpecies<Complex> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(CellDesignerComplexSpecies.class.getName()); - - /** - * Elements that exists in this complex. - */ - private Set<CellDesignerElement<?>> elements = new HashSet<>(); - - /** - * State of the complex species. - */ - private String structuralState = null; - - /** - * Default constructor. - */ - public CellDesignerComplexSpecies() { - super(); - } - - /** - * Constructor that initiale the complex with the data from the object passed - * as an argument. - * - * @param original - * object used for initializing data - */ - public CellDesignerComplexSpecies(CellDesignerSpecies<?> original) { - super(original); - if (original instanceof CellDesignerComplexSpecies) { - CellDesignerComplexSpecies complex = (CellDesignerComplexSpecies) original; - structuralState = complex.getStructuralState(); - for (CellDesignerElement<?> element : complex.getElements()) { - addElement(element.copy()); - } - } - } - - /** - * Constructor with species id. - * - * @param complexId - * {@link CellDesignerSpecies#idSpecies} - */ - public CellDesignerComplexSpecies(String complexId) { - super(complexId); - } - - @Override - public CellDesignerComplexSpecies copy() { - if (this.getClass() == CellDesignerComplexSpecies.class) { - return new CellDesignerComplexSpecies(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - /** - * Adds element to the complex. - * - * @param element - * object to add - */ - public void addElement(CellDesignerElement<?> element) { - if (element instanceof CellDesignerSpecies) { - for (CellDesignerElement<?> el : elements) { - if (el instanceof CellDesignerSpecies) { - if (el.getElementId().equals(element.getElementId())) { - throw new InvalidArgumentException("Cannot add two species with the same id: " + el.getElementId()); - } - } - } - } - this.elements.add(element); - } - - /** - * Returns list of all elements in the complex. Also subelements are included. - * - * @return list of all elements in the complex. - */ - public Set<CellDesignerSpecies<?>> getAllSimpleChildren() { - Set<CellDesignerSpecies<?>> result = new HashSet<>(); - for (CellDesignerElement<?> element : getElements()) { - if (element instanceof CellDesignerComplexSpecies) { - result.addAll(((CellDesignerComplexSpecies) element).getAllSimpleChildren()); - } else if (element instanceof CellDesignerSpecies) { - result.add((CellDesignerSpecies<?>) element); - } - } - return result; - } - - /** - * @return the structuralState - * @see #structuralState - */ - public String getStructuralState() { - return structuralState; - } - - /** - * @param structuralState - * the structuralState to set - * @see #structuralState - */ - public void setStructuralState(String structuralState) { - if (this.structuralState != null && !this.structuralState.equals("") && !this.structuralState.equals(structuralState)) { - logger.warn("replacing structural state, Old: " + this.structuralState + " into new: " + structuralState); - } - this.structuralState = structuralState; - } - - /** - * @return the elements - * @see #elements - */ - public Set<CellDesignerElement<?>> getElements() { - return elements; - } - - /** - * @param elements - * the elements to set - * @see #elements - */ - public void setElements(Set<CellDesignerElement<?>> elements) { - this.elements = elements; - } - - @Override - public Complex createModelElement(String aliasId) { - Complex result = new Complex(aliasId); - super.setModelObjectFields(result); - - if (elements.size() > 0) { - throw new NotImplementedException(); - } - result.setStructuralState(structuralState); - - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(CellDesignerComplexSpecies.class.getName()); + + /** + * Elements that exists in this complex. + */ + private Set<CellDesignerElement<?>> elements = new HashSet<>(); + + /** + * State of the complex species. + */ + private String structuralState = null; + + /** + * Default constructor. + */ + public CellDesignerComplexSpecies() { + super(); + } + + /** + * Constructor that initiale the complex with the data from the object passed as + * an argument. + * + * @param original + * object used for initializing data + */ + public CellDesignerComplexSpecies(CellDesignerSpecies<?> original) { + super(original); + if (original instanceof CellDesignerComplexSpecies) { + CellDesignerComplexSpecies complex = (CellDesignerComplexSpecies) original; + structuralState = complex.getStructuralState(); + for (CellDesignerElement<?> element : complex.getElements()) { + addElement(element.copy()); + } + } + } + + /** + * Constructor with species id. + * + * @param complexId + * {@link CellDesignerSpecies#idSpecies} + */ + public CellDesignerComplexSpecies(String complexId) { + super(complexId); + } + + @Override + public CellDesignerComplexSpecies copy() { + if (this.getClass() == CellDesignerComplexSpecies.class) { + return new CellDesignerComplexSpecies(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + @Override + public Complex createModelElement(String aliasId) { + Complex result = new Complex(aliasId); + super.setModelObjectFields(result); + + if (elements.size() > 0) { + throw new NotImplementedException(); + } + result.setStructuralState(structuralState); + + return result; + } + + /** + * Adds element to the complex. + * + * @param element + * object to add + */ + public void addElement(CellDesignerElement<?> element) { + if (element instanceof CellDesignerSpecies) { + for (CellDesignerElement<?> el : elements) { + if (el instanceof CellDesignerSpecies) { + if (el.getElementId().equals(element.getElementId())) { + throw new InvalidArgumentException("Cannot add two species with the same id: " + el.getElementId()); + } + } + } + } + this.elements.add(element); + } + + /** + * Returns list of all elements in the complex. Also subelements are included. + * + * @return list of all elements in the complex. + */ + public Set<CellDesignerSpecies<?>> getAllSimpleChildren() { + Set<CellDesignerSpecies<?>> result = new HashSet<>(); + for (CellDesignerElement<?> element : getElements()) { + if (element instanceof CellDesignerComplexSpecies) { + result.addAll(((CellDesignerComplexSpecies) element).getAllSimpleChildren()); + } else if (element instanceof CellDesignerSpecies) { + result.add((CellDesignerSpecies<?>) element); + } + } + return result; + } + + /** + * @return the structuralState + * @see #structuralState + */ + public String getStructuralState() { + return structuralState; + } + + /** + * @param structuralState + * the structuralState to set + * @see #structuralState + */ + public void setStructuralState(String structuralState) { + if (this.structuralState != null && !this.structuralState.equals("") + && !this.structuralState.equals(structuralState)) { + logger.warn("replacing structural state, Old: " + this.structuralState + " into new: " + structuralState); + } + this.structuralState = structuralState; + } + + /** + * @return the elements + * @see #elements + */ + public Set<CellDesignerElement<?>> getElements() { + return elements; + } + + /** + * @param elements + * the elements to set + * @see #elements + */ + public void setElements(Set<CellDesignerElement<?>> elements) { + this.elements = elements; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDegraded.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDegraded.java index 1bde95f6c9..ee9c982679 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDegraded.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDegraded.java @@ -11,41 +11,41 @@ import lcsb.mapviewer.model.map.species.Degraded; */ public class CellDesignerDegraded extends CellDesignerSpecies<Degraded> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor that copies the data from species given in the argument. - * - * @param species - * parent species from which we want to copy data - */ - public CellDesignerDegraded(CellDesignerSpecies<?> species) { - super(species); - } - - /** - * Default constructor. - */ - public CellDesignerDegraded() { - } - - @Override - public CellDesignerDegraded copy() { - if (this.getClass() == CellDesignerDegraded.class) { - return new CellDesignerDegraded(super.copy()); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - @Override - public Degraded createModelElement(String aliasId) { - Degraded result = new Degraded(aliasId); - super.setModelObjectFields(result); - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor that copies the data from species given in the argument. + * + * @param species + * parent species from which we want to copy data + */ + public CellDesignerDegraded(CellDesignerSpecies<?> species) { + super(species); + } + + /** + * Default constructor. + */ + public CellDesignerDegraded() { + } + + @Override + public CellDesignerDegraded copy() { + if (this.getClass() == CellDesignerDegraded.class) { + return new CellDesignerDegraded(super.copy()); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + @Override + public Degraded createModelElement(String aliasId) { + Degraded result = new Degraded(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDrug.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDrug.java index 290938153d..d51e63aa64 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDrug.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerDrug.java @@ -11,41 +11,41 @@ import lcsb.mapviewer.model.map.species.Drug; */ public class CellDesignerDrug extends CellDesignerSpecies<Drug> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor that copies the data from species given in the argument. - * - * @param species - * parent species from which we want to copy data - */ - public CellDesignerDrug(CellDesignerSpecies<?> species) { - super(species); - } - - /** - * Default constructor. - */ - public CellDesignerDrug() { - } - - @Override - public CellDesignerDrug copy() { - if (this.getClass() == CellDesignerDrug.class) { - return new CellDesignerDrug(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - @Override - public Drug createModelElement(String aliasId) { - Drug result = new Drug(aliasId); - super.setModelObjectFields(result); - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor that copies the data from species given in the argument. + * + * @param species + * parent species from which we want to copy data + */ + public CellDesignerDrug(CellDesignerSpecies<?> species) { + super(species); + } + + /** + * Default constructor. + */ + public CellDesignerDrug() { + } + + @Override + public CellDesignerDrug copy() { + if (this.getClass() == CellDesignerDrug.class) { + return new CellDesignerDrug(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + @Override + public Drug createModelElement(String aliasId) { + Drug result = new Drug(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerElement.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerElement.java index 2174a5c872..eaa0c94a79 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerElement.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerElement.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; @@ -146,9 +143,17 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ */ public abstract String getElementId(); + /** + * Sets element identifier. + * + * @param elementId + * element identifier + */ + public abstract void setElementId(String elementId); + /** * Adds {@link MiriamData} to the element. - * + * * @param md * object to be added */ @@ -162,21 +167,6 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ } - /** - * Sets notes about the object. - * - * @param notes - * new notes - */ - public void setNotes(String notes) { - if (notes != null) { - if (notes.contains("</html>")) { - throw new InvalidArgumentException("Notes cannot contain html tags..."); - } - } - this.notes = notes; - } - /** * Makes a copy of the element. * @@ -211,9 +201,24 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ return notes; } + /** + * Sets notes about the object. + * + * @param notes + * new notes + */ + public void setNotes(String notes) { + if (notes != null) { + if (notes.contains("</html>")) { + throw new InvalidArgumentException("Notes cannot contain html tags..."); + } + } + this.notes = notes; + } + /** * Returns the symbol of the element. - * + * * @return the symbol of the element */ public String getSymbol() { @@ -222,7 +227,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Sets symbol of the element. - * + * * @param symbol * new symbol */ @@ -249,9 +254,9 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Returns the name of the object. - * + * * @return name of the object - * + * */ public String getName() { return name; @@ -268,7 +273,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Get list of synonyms. - * + * * @return list of synonyms */ public List<String> getSynonyms() { @@ -277,7 +282,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Sets list of synonyms to the element. - * + * * @param synonyms * new list */ @@ -338,7 +343,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Returns list of {@link MiriamData annotations} for the object. - * + * * @return list of {@link MiriamData annotations} for the object */ public Set<MiriamData> getMiriamData() { @@ -347,7 +352,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Returns the abbreviation. - * + * * @return the abbreviation */ public String getAbbreviation() { @@ -356,7 +361,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Sets abbreviation. - * + * * @param abbreviation * new abbreviation */ @@ -366,7 +371,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Returns the formula. - * + * * @return the formula */ public String getFormula() { @@ -375,7 +380,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Sets formula. - * + * * @param formula * new formula */ @@ -385,7 +390,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Adds synonym. - * + * * @param synonym * synonym to add */ @@ -395,7 +400,7 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ /** * Adds former symbol. - * + * * @param formerSymbol * former symbol to add */ @@ -403,14 +408,6 @@ public abstract class CellDesignerElement<T extends Element> implements Serializ this.formerSymbols.add(formerSymbol); } - /** - * Sets element identifier. - * - * @param elementId - * element identifier - */ - public abstract void setElementId(String elementId); - /** * Creates model object from this CellDesigner structure. * diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGene.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGene.java index 8981dc8488..1b98b75310 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGene.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGene.java @@ -3,18 +3,15 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.Gene; import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.field.*; /** * Class representing CellDesigner {@link Gene}. @@ -23,17 +20,15 @@ import lcsb.mapviewer.model.map.species.field.TranscriptionSite; * */ public class CellDesignerGene extends CellDesignerSpecies<Gene> { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(CellDesignerGene.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * List of modifications for the Gene. */ @@ -55,6 +50,22 @@ public class CellDesignerGene extends CellDesignerSpecies<Gene> { } } + /** + * Default constructor. + */ + public CellDesignerGene() { + super(); + } + + @Override + public CellDesignerGene copy() { + if (this.getClass() == CellDesignerGene.class) { + return new CellDesignerGene(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + @Override public void update(CellDesignerSpecies<?> species) { super.update(species); @@ -67,25 +78,35 @@ public class CellDesignerGene extends CellDesignerSpecies<Gene> { } } - /** - * Default constructor. - */ - public CellDesignerGene() { - super(); + @Override + public Gene createModelElement(String aliasId) { + Gene result = new Gene(aliasId); + super.setModelObjectFields(result); + return result; } @Override - public CellDesignerGene copy() { - if (this.getClass() == CellDesignerGene.class) { - return new CellDesignerGene(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + public void updateModelElementAfterLayoutAdded(Species species) { + Gene gene = (Gene) species; + for (CellDesignerModificationResidue region : modificationResidues) { + ModificationResidue mr = region.createModificationResidue(gene); + if (mr instanceof CodingRegion) { + gene.addCodingRegion((CodingRegion) mr); + } else if (mr instanceof ModificationSite) { + gene.addModificationSite((ModificationSite) mr); + } else if (mr instanceof RegulatoryRegion) { + gene.addRegulatoryRegion((RegulatoryRegion) mr); + } else if (mr instanceof TranscriptionSite) { + gene.addTranscriptionSite((TranscriptionSite) mr); + } else { + throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); + } } } /** * Adds modification to the gene. - * + * * @param modificationResidue * modification to add */ @@ -117,30 +138,4 @@ public class CellDesignerGene extends CellDesignerSpecies<Gene> { public void setModificationResidues(List<CellDesignerModificationResidue> modificationResidues) { this.modificationResidues = modificationResidues; } - - @Override - public Gene createModelElement(String aliasId) { - Gene result = new Gene(aliasId); - super.setModelObjectFields(result); - return result; - } - - @Override - public void updateModelElementAfterLayoutAdded(Species species) { - Gene gene = (Gene) species; - for (CellDesignerModificationResidue region : modificationResidues) { - ModificationResidue mr = region.createModificationResidue(gene); - if (mr instanceof CodingRegion) { - gene.addCodingRegion((CodingRegion) mr); - } else if (mr instanceof ModificationSite) { - gene.addModificationSite((ModificationSite) mr); - } else if (mr instanceof RegulatoryRegion) { - gene.addRegulatoryRegion((RegulatoryRegion) mr); - } else if (mr instanceof TranscriptionSite) { - gene.addTranscriptionSite((TranscriptionSite) mr); - } else { - throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); - } - } - } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGenericProtein.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGenericProtein.java index 52b1d1c780..dcc83900fa 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGenericProtein.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerGenericProtein.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.GenericProtein; @@ -13,17 +14,16 @@ import lcsb.mapviewer.model.map.species.GenericProtein; */ public class CellDesignerGenericProtein extends CellDesignerProtein<GenericProtein> { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private transient Logger logger = LogManager.getLogger(CellDesignerGenericProtein.class); - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Default constructor. */ diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerIonChannelProtein.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerIonChannelProtein.java index bd9cc31b09..d824925d92 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerIonChannelProtein.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerIonChannelProtein.java @@ -11,42 +11,42 @@ import lcsb.mapviewer.model.map.species.IonChannelProtein; */ public class CellDesignerIonChannelProtein extends CellDesignerProtein<IonChannelProtein> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public CellDesignerIonChannelProtein() { - super(); - } - - /** - * Constructor that creates a copy of species. - * - * @param species - * original species - */ - public CellDesignerIonChannelProtein(CellDesignerSpecies<?> species) { - super(species); - } - - @Override - public CellDesignerIonChannelProtein copy() { - if (this.getClass().equals(CellDesignerIonChannelProtein.class)) { - return new CellDesignerIonChannelProtein(this); - } else { - throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); - } - } - - @Override - public IonChannelProtein createModelElement(String aliasId) { - IonChannelProtein result = new IonChannelProtein(aliasId); - super.setModelObjectFields(result); - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public CellDesignerIonChannelProtein() { + super(); + } + + /** + * Constructor that creates a copy of species. + * + * @param species + * original species + */ + public CellDesignerIonChannelProtein(CellDesignerSpecies<?> species) { + super(species); + } + + @Override + public CellDesignerIonChannelProtein copy() { + if (this.getClass().equals(CellDesignerIonChannelProtein.class)) { + return new CellDesignerIonChannelProtein(this); + } else { + throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); + } + } + + @Override + public IonChannelProtein createModelElement(String aliasId) { + IonChannelProtein result = new IonChannelProtein(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerPhenotype.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerPhenotype.java index 6611cc4c50..cc81c685f3 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerPhenotype.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerPhenotype.java @@ -11,42 +11,41 @@ import lcsb.mapviewer.model.map.species.Phenotype; */ public class CellDesignerPhenotype extends CellDesignerSpecies<Phenotype> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor that initializes phenotype with the data passed in the - * argument. - * - * @param species - * original species used for data initialization - */ - public CellDesignerPhenotype(CellDesignerSpecies<?> species) { - super(species); - } - - /** - * Default constructor. - */ - public CellDesignerPhenotype() { - } - - @Override - public CellDesignerPhenotype copy() { - if (this.getClass() == CellDesignerPhenotype.class) { - return new CellDesignerPhenotype(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - @Override - public Phenotype createModelElement(String aliasId) { - Phenotype result = new Phenotype(aliasId); - super.setModelObjectFields(result); - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Constructor that initializes phenotype with the data passed in the argument. + * + * @param species + * original species used for data initialization + */ + public CellDesignerPhenotype(CellDesignerSpecies<?> species) { + super(species); + } + + /** + * Default constructor. + */ + public CellDesignerPhenotype() { + } + + @Override + public CellDesignerPhenotype copy() { + if (this.getClass() == CellDesignerPhenotype.class) { + return new CellDesignerPhenotype(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + @Override + public Phenotype createModelElement(String aliasId) { + Phenotype result = new Phenotype(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerProtein.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerProtein.java index 70ca0ed345..70e447b371 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerProtein.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerProtein.java @@ -3,16 +3,15 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.Protein; import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.species.field.*; /** * Class representing CellDesigner {@link Protein} object. @@ -62,6 +61,22 @@ public class CellDesignerProtein<T extends Protein> extends CellDesignerSpecies< } } + /** + * Default constructor. + */ + public CellDesignerProtein() { + super(); + } + + @Override + public CellDesignerProtein<T> copy() { + if (this.getClass().equals(CellDesignerProtein.class)) { + return new CellDesignerProtein<T>(this); + } else { + throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); + } + } + @Override public void update(CellDesignerSpecies<?> species) { super.update(species); @@ -76,25 +91,30 @@ public class CellDesignerProtein<T extends Protein> extends CellDesignerSpecies< } } - /** - * Default constructor. - */ - public CellDesignerProtein() { - super(); + @Override + protected void setModelObjectFields(T result) { + super.setModelObjectFields(result); + result.setStructuralState(structuralState); } @Override - public CellDesignerProtein<T> copy() { - if (this.getClass().equals(CellDesignerProtein.class)) { - return new CellDesignerProtein<T>(this); - } else { - throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); + public void updateModelElementAfterLayoutAdded(Species species) { + Protein protein = (Protein) species; + for (CellDesignerModificationResidue region : modificationResidues) { + ModificationResidue mr = region.createModificationResidue(protein); + if (mr instanceof Residue) { + protein.addResidue((Residue) mr); + } else if (mr instanceof BindingRegion) { + protein.addBindingRegion((BindingRegion) mr); + } else { + throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); + } } } /** * Adds modification to the protein. - * + * * @param modificationResidue * modification to add */ @@ -147,25 +167,4 @@ public class CellDesignerProtein<T extends Protein> extends CellDesignerSpecies< this.modificationResidues = modificationResidues; } - @Override - protected void setModelObjectFields(T result) { - super.setModelObjectFields(result); - result.setStructuralState(structuralState); - } - - @Override - public void updateModelElementAfterLayoutAdded(Species species) { - Protein protein= (Protein) species; - for (CellDesignerModificationResidue region : modificationResidues) { - ModificationResidue mr = region.createModificationResidue(protein); - if (mr instanceof Residue) { - protein.addResidue((Residue) mr); - } else if (mr instanceof BindingRegion) { - protein.addBindingRegion((BindingRegion) mr); - } else { - throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); - } - } - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerReceptorProtein.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerReceptorProtein.java index 6779848bf1..c7720c90dd 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerReceptorProtein.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerReceptorProtein.java @@ -11,42 +11,42 @@ import lcsb.mapviewer.model.map.species.ReceptorProtein; */ public class CellDesignerReceptorProtein extends CellDesignerProtein<ReceptorProtein> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public CellDesignerReceptorProtein() { - super(); - } - - /** - * Constructor that creates a copy of species. - * - * @param species - * original species - */ - public CellDesignerReceptorProtein(CellDesignerSpecies<?> species) { - super(species); - } - - @Override - public CellDesignerReceptorProtein copy() { - if (this.getClass().equals(CellDesignerReceptorProtein.class)) { - return new CellDesignerReceptorProtein(this); - } else { - throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); - } - } - - @Override - public ReceptorProtein createModelElement(String aliasId) { - ReceptorProtein result = new ReceptorProtein(aliasId); - super.setModelObjectFields(result); - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public CellDesignerReceptorProtein() { + super(); + } + + /** + * Constructor that creates a copy of species. + * + * @param species + * original species + */ + public CellDesignerReceptorProtein(CellDesignerSpecies<?> species) { + super(species); + } + + @Override + public CellDesignerReceptorProtein copy() { + if (this.getClass().equals(CellDesignerReceptorProtein.class)) { + return new CellDesignerReceptorProtein(this); + } else { + throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); + } + } + + @Override + public ReceptorProtein createModelElement(String aliasId) { + ReceptorProtein result = new ReceptorProtein(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerRna.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerRna.java index 42ae597ea7..94063368e0 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerRna.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerRna.java @@ -3,17 +3,15 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.CellDesignerModificationResidue; import lcsb.mapviewer.model.map.species.Rna; import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; +import lcsb.mapviewer.model.map.species.field.*; /** * Class representing CellDesigner {@link Rna}. @@ -83,9 +81,33 @@ public class CellDesignerRna extends CellDesignerSpecies<Rna> { } } + @Override + public Rna createModelElement(String aliasId) { + Rna result = new Rna(aliasId); + super.setModelObjectFields(result); + return result; + } + + @Override + public void updateModelElementAfterLayoutAdded(Species species) { + Rna rna = (Rna) species; + for (CellDesignerModificationResidue region : regions) { + ModificationResidue mr = region.createModificationResidue(rna); + if (mr instanceof CodingRegion) { + rna.addCodingRegion((CodingRegion) mr); + } else if (mr instanceof ModificationSite) { + rna.addModificationSite((ModificationSite) mr); + } else if (mr instanceof ProteinBindingDomain) { + rna.addProteinBindingDomain((ProteinBindingDomain) mr); + } else { + throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); + } + } + } + /** * Updates region in the rna. If region doesn't exist then it is added. - * + * * @param param * region that with the data to update */ @@ -102,7 +124,7 @@ public class CellDesignerRna extends CellDesignerSpecies<Rna> { /** * Adds region. If the region with given id exists then the data of this region * is copied to the one that is already in the {@link CellDesignerRna}. - * + * * @param rnaRegion * region to add */ @@ -136,28 +158,4 @@ public class CellDesignerRna extends CellDesignerSpecies<Rna> { this.regions = regions; } - @Override - public Rna createModelElement(String aliasId) { - Rna result = new Rna(aliasId); - super.setModelObjectFields(result); - return result; - } - - @Override - public void updateModelElementAfterLayoutAdded(Species species) { - Rna rna = (Rna) species; - for (CellDesignerModificationResidue region : regions) { - ModificationResidue mr = region.createModificationResidue(rna); - if (mr instanceof CodingRegion) { - rna.addCodingRegion((CodingRegion) mr); - } else if (mr instanceof ModificationSite) { - rna.addModificationSite((ModificationSite) mr); - } else if (mr instanceof ProteinBindingDomain) { - rna.addProteinBindingDomain((ProteinBindingDomain) mr); - } else { - throw new InvalidArgumentException("Cannot add modification residue to element: " + mr.getClass()); - } - } - } - } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSimpleMolecule.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSimpleMolecule.java index 04e722dfe6..03497615f2 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSimpleMolecule.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSimpleMolecule.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.SimpleMolecule; @@ -13,47 +14,47 @@ import lcsb.mapviewer.model.map.species.SimpleMolecule; */ public class CellDesignerSimpleMolecule extends CellDesignerChemical<SimpleMolecule> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CellDesignerSimpleMolecule.class.getName()); - - /** - * Constructor that initializes molecule with the data passed in the argument. - * - * @param species - * original species used for data initialization - */ - public CellDesignerSimpleMolecule(CellDesignerSpecies<?> species) { - super(species); - } - - /** - * Default constructor. - */ - public CellDesignerSimpleMolecule() { - } - - @Override - public CellDesignerSimpleMolecule copy() { - if (this.getClass() == CellDesignerSimpleMolecule.class) { - return new CellDesignerSimpleMolecule(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - @Override - public SimpleMolecule createModelElement(String aliasId) { - SimpleMolecule result = new SimpleMolecule(aliasId); - super.setModelObjectFields(result); - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CellDesignerSimpleMolecule.class.getName()); + + /** + * Constructor that initializes molecule with the data passed in the argument. + * + * @param species + * original species used for data initialization + */ + public CellDesignerSimpleMolecule(CellDesignerSpecies<?> species) { + super(species); + } + + /** + * Default constructor. + */ + public CellDesignerSimpleMolecule() { + } + + @Override + public CellDesignerSimpleMolecule copy() { + if (this.getClass() == CellDesignerSimpleMolecule.class) { + return new CellDesignerSimpleMolecule(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + @Override + public SimpleMolecule createModelElement(String aliasId) { + SimpleMolecule result = new SimpleMolecule(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSpecies.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSpecies.java index 4835b7a64f..2f162057b6 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSpecies.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerSpecies.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -75,20 +76,9 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< private Boolean constant; - /** - * Set hypothetical flag from text input. - * - * @param text - * string with true/false value that determines hypothetical state. - * @see #hypothetical - */ - public void setHypothetical(String text) { - hypothetical = text.equals("true"); - } - /** * Constructor that copies the data from species given in the argument. - * + * * @param species * parent species from which we want to copy data */ @@ -117,7 +107,7 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< /** * Default constructor with species identifier as a parameter. - * + * * @param id * species identifier */ @@ -127,23 +117,9 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< this.setName(id); } - @Override - public CellDesignerSpecies<T> copy() { - CellDesignerSpecies<T> result = new CellDesignerSpecies<T>(this); - - result.idSpecies = idSpecies; - result.setNotes(getNotes()); - result.setHypothetical(hypothetical); - // correct this - - result.setParent(getParent()); - - return result; - } - /** * Updates species with the value from the species given in the parameter. - * + * * @param species * object from which we are updating information */ @@ -244,80 +220,9 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< } } - /** - * Sets initial amount from text. - * - * @param text - * initial amount in string format - * @see #initialAmount - */ - - public void setInitialAmount(String text) { - if (text != null && !text.trim().equals("")) { - try { - initialAmount = Double.parseDouble(text); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid species amount: " + text, e); - } - } else { - initialAmount = null; - } - - } - - /** - * Sets charge from text. - * - * @param text - * charge in string format - * @see #charge - */ - public void setCharge(String text) { - if (text != null && !text.trim().equals("")) { - try { - charge = Integer.parseInt(text); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid species charge: " + text, e); - } - } else { - charge = null; - } - - } - - /** - * Sets OnlySubstanceUnits amount from text. - * - * @param text - * OnlySubstanceUnits in string format - * @see #onlySubstanceUnits - */ - public void setOnlySubstanceUnits(String text) { - onlySubstanceUnits = textToBoolean(text, "Invalid species value for only substance unit boolean: " + text); - } - - /** - * Sets initial concentration amount from text. - * - * @param text - * initial concentration in string format - * @see #initialConcentration - */ - public void setInitialConcentration(String text) { - if (text != null && !text.trim().equals("")) { - try { - initialConcentration = Double.parseDouble(text); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid species initial concentration: " + text, e); - } - } else { - initialConcentration = null; - } - } - /** * Is species hypothetical or not. - * + * * @return <code>true</code> if species is hypothetical, <code>false</code> * otherwise */ @@ -345,6 +250,49 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< } } + @Override + public CellDesignerSpecies<T> copy() { + CellDesignerSpecies<T> result = new CellDesignerSpecies<T>(this); + + result.idSpecies = idSpecies; + result.setNotes(getNotes()); + result.setHypothetical(hypothetical); + // correct this + + result.setParent(getParent()); + + return result; + } + + @Override + public T createModelElement(String aliasId) { + throw new NotImplementedException("" + this.getClass()); + } + + @Override + protected void setModelObjectFields(T result) { + super.setModelObjectFields(result); + result.setInitialAmount(initialAmount); + result.setCharge(charge); + result.setInitialConcentration(initialConcentration); + if (result.getInitialAmount() == null && result.getInitialConcentration() == null) { + result.setInitialConcentration(0.0); + } + if (onlySubstanceUnits != null) { + result.setOnlySubstanceUnits(onlySubstanceUnits); + } + if (constant != null) { + result.setConstant(constant); + } + if (boundaryCondition != null) { + result.setBoundaryCondition(boundaryCondition); + } + result.setSubstanceUnits(substanceUnits); + result.setHomodimer(homodimer); + result.setPositionToCompartment(positionToCompartment); + result.setHypothetical(hypothetical); + } + /** * @return the initialAmount * @see #initialAmount @@ -353,6 +301,27 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< return initialAmount; } + /** + * Sets initial amount from text. + * + * @param text + * initial amount in string format + * @see #initialAmount + */ + + public void setInitialAmount(String text) { + if (text != null && !text.trim().equals("")) { + try { + initialAmount = Double.parseDouble(text); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid species amount: " + text, e); + } + } else { + initialAmount = null; + } + + } + /** * @param initialAmount * the initialAmount to set @@ -370,6 +339,26 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< return charge; } + /** + * Sets charge from text. + * + * @param text + * charge in string format + * @see #charge + */ + public void setCharge(String text) { + if (text != null && !text.trim().equals("")) { + try { + charge = Integer.parseInt(text); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid species charge: " + text, e); + } + } else { + charge = null; + } + + } + /** * @param charge * the charge to set @@ -387,6 +376,17 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< return onlySubstanceUnits; } + /** + * Sets OnlySubstanceUnits amount from text. + * + * @param text + * OnlySubstanceUnits in string format + * @see #onlySubstanceUnits + */ + public void setOnlySubstanceUnits(String text) { + onlySubstanceUnits = textToBoolean(text, "Invalid species value for only substance unit boolean: " + text); + } + /** * @param onlySubstanceUnits * the onlySubstanceUnits to set @@ -404,6 +404,25 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< return initialConcentration; } + /** + * Sets initial concentration amount from text. + * + * @param text + * initial concentration in string format + * @see #initialConcentration + */ + public void setInitialConcentration(String text) { + if (text != null && !text.trim().equals("")) { + try { + initialConcentration = Double.parseDouble(text); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid species initial concentration: " + text, e); + } + } else { + initialConcentration = null; + } + } + /** * @param initialConcentration * the initialConcentration to set @@ -421,6 +440,17 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< return hypothetical; } + /** + * Set hypothetical flag from text input. + * + * @param text + * string with true/false value that determines hypothetical state. + * @see #hypothetical + */ + public void setHypothetical(String text) { + hypothetical = text.equals("true"); + } + /** * @param hypothetical * the hypothetical to set @@ -472,35 +502,6 @@ public class CellDesignerSpecies<T extends Species> extends CellDesignerElement< this.homodimer = homodimer; } - @Override - public T createModelElement(String aliasId) { - throw new NotImplementedException("" + this.getClass()); - } - - @Override - protected void setModelObjectFields(T result) { - super.setModelObjectFields(result); - result.setInitialAmount(initialAmount); - result.setCharge(charge); - result.setInitialConcentration(initialConcentration); - if (result.getInitialAmount()==null && result.getInitialConcentration()==null) { - result.setInitialConcentration(0.0); - } - if (onlySubstanceUnits != null) { - result.setOnlySubstanceUnits(onlySubstanceUnits); - } - if (constant != null) { - result.setConstant(constant); - } - if (boundaryCondition != null) { - result.setBoundaryCondition(boundaryCondition); - } - result.setSubstanceUnits(substanceUnits); - result.setHomodimer(homodimer); - result.setPositionToCompartment(positionToCompartment); - result.setHypothetical(hypothetical); - } - public void setSubstanceUnits(SbmlUnitType substanceUnits) { this.substanceUnits = substanceUnits; } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerTruncatedProtein.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerTruncatedProtein.java index aec05429b1..22dae6e805 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerTruncatedProtein.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerTruncatedProtein.java @@ -11,43 +11,43 @@ import lcsb.mapviewer.model.map.species.TruncatedProtein; */ public class CellDesignerTruncatedProtein extends CellDesignerProtein<TruncatedProtein> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public CellDesignerTruncatedProtein() { - super(); - } - - /** - * Constructor that creates a copy of species. - * - * @param species - * original species - */ - public CellDesignerTruncatedProtein(CellDesignerSpecies<?> species) { - super(species); - } - - @Override - public CellDesignerTruncatedProtein copy() { - if (this.getClass().equals(CellDesignerTruncatedProtein.class)) { - return new CellDesignerTruncatedProtein(this); - } else { - throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); - } - } - - @Override - public TruncatedProtein createModelElement(String aliasId) { - TruncatedProtein result = new TruncatedProtein(aliasId); - super.setModelObjectFields(result); - - return result; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public CellDesignerTruncatedProtein() { + super(); + } + + /** + * Constructor that creates a copy of species. + * + * @param species + * original species + */ + public CellDesignerTruncatedProtein(CellDesignerSpecies<?> species) { + super(species); + } + + @Override + public CellDesignerTruncatedProtein copy() { + if (this.getClass().equals(CellDesignerTruncatedProtein.class)) { + return new CellDesignerTruncatedProtein(this); + } else { + throw new NotImplementedException("Copy method for " + this.getClass() + " class not implemented"); + } + } + + @Override + public TruncatedProtein createModelElement(String aliasId) { + TruncatedProtein result = new TruncatedProtein(aliasId); + super.setModelObjectFields(result); + + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerUnknown.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerUnknown.java index c6d0326199..2047fb2147 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerUnknown.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerUnknown.java @@ -10,41 +10,41 @@ import lcsb.mapviewer.model.map.species.Unknown; * */ public class CellDesignerUnknown extends CellDesignerSpecies<Unknown> { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor that initializes unknown with the data passed in the argument. - * - * @param species - * original species used for data initialization - */ - public CellDesignerUnknown(CellDesignerSpecies<?> species) { - super(species); - } + /** + * Constructor that initializes unknown with the data passed in the argument. + * + * @param species + * original species used for data initialization + */ + public CellDesignerUnknown(CellDesignerSpecies<?> species) { + super(species); + } - /** - * Default constructor. - */ - public CellDesignerUnknown() { - } + /** + * Default constructor. + */ + public CellDesignerUnknown() { + } - @Override - public CellDesignerUnknown copy() { - if (this.getClass() == CellDesignerUnknown.class) { - return new CellDesignerUnknown(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public CellDesignerUnknown copy() { + if (this.getClass() == CellDesignerUnknown.class) { + return new CellDesignerUnknown(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } - @Override - public Unknown createModelElement(String aliasId) { - Unknown result = new Unknown(aliasId); - super.setModelObjectFields(result); - return result; - } + @Override + public Unknown createModelElement(String aliasId) { + Unknown result = new Unknown(aliasId); + super.setModelObjectFields(result); + return result; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidue.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidue.java index b131818c5f..afcd75d2bf 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidue.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidue.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; import java.io.Serializable; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -10,15 +11,7 @@ import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.geometry.CellDesignerAliasConverter; import lcsb.mapviewer.converter.model.celldesigner.structure.CellDesignerSpecies; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.field.*; /** * This class represent modification residue in a Species. @@ -222,43 +215,6 @@ public class CellDesignerModificationResidue implements Serializable { } } - /** - * Sets {@link #angle} . - * - * @param text - * angle in text format - */ - public void setAngle(String text) { - try { - if (text != null && !text.equals("")) { - angle = Double.parseDouble(text); - } else { - angle = null; - } - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid angle: " + text, e); - } - - } - - /** - * Sets {@link #size}. - * - * @param text - * size in text format. - */ - public void setSize(String text) { - try { - if (text != null && !text.equals("")) { - size = Double.parseDouble(text); - } else { - size = null; - } - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid size: " + text, e); - } - } - /** * @return the id * @see #idModificationResidue @@ -335,6 +291,25 @@ public class CellDesignerModificationResidue implements Serializable { return angle; } + /** + * Sets {@link #angle} . + * + * @param text + * angle in text format + */ + public void setAngle(String text) { + try { + if (text != null && !text.equals("")) { + angle = Double.parseDouble(text); + } else { + angle = null; + } + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid angle: " + text, e); + } + + } + /** * @param angle * the angle to set @@ -352,6 +327,24 @@ public class CellDesignerModificationResidue implements Serializable { return size; } + /** + * Sets {@link #size}. + * + * @param text + * size in text format. + */ + public void setSize(String text) { + try { + if (text != null && !text.equals("")) { + size = Double.parseDouble(text); + } else { + size = null; + } + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid size: " + text, e); + } + } + /** * @param size * the size to set @@ -506,9 +499,17 @@ public class CellDesignerModificationResidue implements Serializable { this.modificationType = modificationType; } + /** + * @return the pos + * @see #pos + */ + public Double getPos() { + return pos; + } + /** * Sets position from the string. - * + * * @param text * position to parse and set * @see #pos @@ -521,14 +522,6 @@ public class CellDesignerModificationResidue implements Serializable { } } - /** - * @return the pos - * @see #pos - */ - public Double getPos() { - return pos; - } - /** * @param pos * the pos to set diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ConnectScheme.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ConnectScheme.java index dcdab0a36f..21bb054225 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ConnectScheme.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ConnectScheme.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * CellDEsigner structure used for storing some line information. @@ -13,100 +14,100 @@ import org.apache.logging.log4j.*; */ public class ConnectScheme { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(ConnectScheme.class.getName()); - - /** - * Not used in our model... No ide what it means. - */ - private String connectPolicy; - - /** - * Defines where the central point is placed. - */ - private Integer connectIndex; - - /** - * Not used in our model... No ide what it means. - */ - private Map<String, String> lineDirections; - - /** - * Default constructor. - */ - public ConnectScheme() { - connectPolicy = ""; - connectIndex = null; - lineDirections = new HashMap<String, String>(); - } - - /** - * - * @param directions - * the directions to set - * @see #directions - */ - public void setLineDirections(Map<String, String> directions) { - lineDirections = directions; - } - - /** - * - * @param text - * the connectIndex to set in String format - * @see #connectIndex - */ - public void setConnectIndex(String text) { - if (text == null || "".equals(text)) { - connectIndex = null; - } else { - setConnectIndex(Integer.parseInt(text)); - } - - } - - /** - * @return the connectPolicy - * @see #connectPolicy - */ - public String getConnectPolicy() { - return connectPolicy; - } - - /** - * @param connectPolicy - * the connectPolicy to set - * @see #connectPolicy - */ - public void setConnectPolicy(String connectPolicy) { - this.connectPolicy = connectPolicy; - } - - /** - * @return the connectIndex - * @see #connectIndex - */ - public Integer getConnectIndex() { - return connectIndex; - } - - /** - * @param connectIndex - * the connectIndex to set - * @see #connectIndex - */ - public void setConnectIndex(Integer connectIndex) { - this.connectIndex = connectIndex; - } - - /** - * @return the lineDirections - * @see #lineDirections - */ - public Map<String, String> getLineDirections() { - return lineDirections; - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(ConnectScheme.class.getName()); + + /** + * Not used in our model... No ide what it means. + */ + private String connectPolicy; + + /** + * Defines where the central point is placed. + */ + private Integer connectIndex; + + /** + * Not used in our model... No ide what it means. + */ + private Map<String, String> lineDirections; + + /** + * Default constructor. + */ + public ConnectScheme() { + connectPolicy = ""; + connectIndex = null; + lineDirections = new HashMap<String, String>(); + } + + /** + * @return the connectPolicy + * @see #connectPolicy + */ + public String getConnectPolicy() { + return connectPolicy; + } + + /** + * @param connectPolicy + * the connectPolicy to set + * @see #connectPolicy + */ + public void setConnectPolicy(String connectPolicy) { + this.connectPolicy = connectPolicy; + } + + /** + * @return the connectIndex + * @see #connectIndex + */ + public Integer getConnectIndex() { + return connectIndex; + } + + /** + * + * @param text + * the connectIndex to set in String format + * @see #connectIndex + */ + public void setConnectIndex(String text) { + if (text == null || "".equals(text)) { + connectIndex = null; + } else { + setConnectIndex(Integer.parseInt(text)); + } + + } + + /** + * @param connectIndex + * the connectIndex to set + * @see #connectIndex + */ + public void setConnectIndex(Integer connectIndex) { + this.connectIndex = connectIndex; + } + + /** + * @return the lineDirections + * @see #lineDirections + */ + public Map<String, String> getLineDirections() { + return lineDirections; + } + + /** + * + * @param directions + * the directions to set + * @see #directions + */ + public void setLineDirections(Map<String, String> directions) { + lineDirections = directions; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/LineProperties.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/LineProperties.java index f60dc0441d..dd45ccc521 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/LineProperties.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/LineProperties.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; -import java.awt.Color; +import java.awt.*; import lcsb.mapviewer.model.graphics.PolylineData; diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ModificationType.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ModificationType.java index db5a5e258b..ac4058e4ae 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ModificationType.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/ModificationType.java @@ -18,10 +18,6 @@ public enum ModificationType { this.cellDesignerName = cellDesignerName; } - public String getCellDesignerName() { - return cellDesignerName; - } - public static ModificationType getByCellDesignerName(String name) { for (ModificationType type : ModificationType.values()) { if (type.getCellDesignerName() != null && type.getCellDesignerName().equals(name)) { @@ -30,4 +26,8 @@ public enum ModificationType { } throw new InvalidArgumentException("Unknown CellDesigner name: " + name); } + + public String getCellDesignerName() { + return cellDesignerName; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SingleLine.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SingleLine.java index 26dfe344ca..60c0db6f6f 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SingleLine.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SingleLine.java @@ -8,26 +8,26 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; */ public class SingleLine { - /** - * Width of the line. - */ - private Double width; + /** + * Width of the line. + */ + private Double width; - /** - * @return the width - * @see #width - */ - public Double getWidth() { - return width; - } + /** + * @return the width + * @see #width + */ + public Double getWidth() { + return width; + } - /** - * @param width - * the width to set - * @see #width - */ - public void setWidth(Double width) { - this.width = width; - } + /** + * @param width + * the width to set + * @see #width + */ + public void setWidth(Double width) { + this.width = width; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SpeciesState.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SpeciesState.java index 1c20b73fad..dbd505bdc0 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SpeciesState.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/SpeciesState.java @@ -3,15 +3,11 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -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.model.map.species.*; import lcsb.mapviewer.model.map.species.field.ModificationResidue; /** @@ -43,22 +39,6 @@ public class SpeciesState { */ private List<CellDesignerModificationResidue> modifications = new ArrayList<>(); - /** - * Adds modification to the state. - * - * @param modificationResidue - * modification to add - */ - public void addModificationResidue(CellDesignerModificationResidue modificationResidue) { - for (CellDesignerModificationResidue modification : modifications) { - if (modification.getIdModificationResidue().equals(modificationResidue.getIdModificationResidue())) { - modification.update(modificationResidue); - return; - } - } - modifications.add(modificationResidue); - } - /** * Default constructor. */ @@ -67,7 +47,7 @@ public class SpeciesState { /** * Creates species state description from species element. - * + * * @param species * object for which description is created */ @@ -104,16 +84,19 @@ public class SpeciesState { } /** - * - * @param homodimer - * new {@link #homodimer} value to set (in string format) + * Adds modification to the state. + * + * @param modificationResidue + * modification to add */ - public void setHomodimer(String homodimer) { - try { - this.homodimer = Integer.parseInt(homodimer); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid homodir value: " + homodimer); + public void addModificationResidue(CellDesignerModificationResidue modificationResidue) { + for (CellDesignerModificationResidue modification : modifications) { + if (modification.getIdModificationResidue().equals(modificationResidue.getIdModificationResidue())) { + modification.update(modificationResidue); + return; + } } + modifications.add(modificationResidue); } /** @@ -124,6 +107,19 @@ public class SpeciesState { return homodimer; } + /** + * + * @param homodimer + * new {@link #homodimer} value to set (in string format) + */ + public void setHomodimer(String homodimer) { + try { + this.homodimer = Integer.parseInt(homodimer); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid homodir value: " + homodimer); + } + } + /** * @param homodimer * the homodimer to set diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/View.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/View.java index dd0a00f02f..176e8aa21f 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/View.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/View.java @@ -1,7 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; -import java.awt.Color; -import java.awt.Dimension; +import java.awt.*; import java.awt.geom.Point2D; /** @@ -11,84 +10,84 @@ import java.awt.geom.Point2D; * */ public class View { - - /** - * No idea what this parameter describes. - */ - private Point2D innerPosition; - - /** - * Size of the element. - */ - private Dimension boxSize; - - /** - * Width of the line. - */ - private SingleLine singleLine; - - /** - * Color of the element. - */ - private Color color; - /** - * @return the innerPosition - */ - public Point2D getInnerPosition() { - return innerPosition; - } + /** + * No idea what this parameter describes. + */ + private Point2D innerPosition; - /** - * @param innerPosition - * the innerPosition to set - */ - public void setInnerPosition(Point2D innerPosition) { - this.innerPosition = innerPosition; - } + /** + * Size of the element. + */ + private Dimension boxSize; - /** - * @return the boxSize - */ - public Dimension getBoxSize() { - return boxSize; - } + /** + * Width of the line. + */ + private SingleLine singleLine; - /** - * @param boxSize - * the boxSize to set - */ - public void setBoxSize(Dimension boxSize) { - this.boxSize = boxSize; - } + /** + * Color of the element. + */ + private Color color; - /** - * @return the singleLine - */ - public SingleLine getSingleLine() { - return singleLine; - } + /** + * @return the innerPosition + */ + public Point2D getInnerPosition() { + return innerPosition; + } - /** - * @param singleLine - * the singleLine to set - */ - public void setSingleLine(SingleLine singleLine) { - this.singleLine = singleLine; - } + /** + * @param innerPosition + * the innerPosition to set + */ + public void setInnerPosition(Point2D innerPosition) { + this.innerPosition = innerPosition; + } - /** - * @return the color - */ - public Color getColor() { - return color; - } + /** + * @return the boxSize + */ + public Dimension getBoxSize() { + return boxSize; + } - /** - * @param color - * the color to set - */ - public void setColor(Color color) { - this.color = color; - } + /** + * @param boxSize + * the boxSize to set + */ + public void setBoxSize(Dimension boxSize) { + this.boxSize = boxSize; + } + + /** + * @return the singleLine + */ + public SingleLine getSingleLine() { + return singleLine; + } + + /** + * @param singleLine + * the singleLine to set + */ + public void setSingleLine(SingleLine singleLine) { + this.singleLine = singleLine; + } + + /** + * @return the color + */ + public Color getColor() { + return color; + } + + /** + * @param color + * the color to set + */ + public void setColor(Color color) { + this.color = color; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierType.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierType.java index 3a907fea11..db7e340685 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierType.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierType.java @@ -1,16 +1,8 @@ package lcsb.mapviewer.converter.model.celldesigner.types; import lcsb.mapviewer.converter.model.celldesigner.geometry.ReactionCellDesignerConverter; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.modifier.Trigger; -import lcsb.mapviewer.model.map.modifier.UnknownCatalysis; -import lcsb.mapviewer.model.map.modifier.UnknownInhibition; +import lcsb.mapviewer.model.graphics.*; +import lcsb.mapviewer.model.map.modifier.*; import lcsb.mapviewer.model.map.reaction.Modifier; /** @@ -21,182 +13,184 @@ import lcsb.mapviewer.model.map.reaction.Modifier; * */ public enum ModifierType { - - /** - * Catalysis. - */ - CATALYSIS("CATALYSIS", Catalysis.class, ArrowType.CIRCLE, 8.0), - - /** - * Inhibition. - */ - INHIBITION("INHIBITION", Inhibition.class, ArrowType.CROSSBAR, 8.0, ReactionCellDesignerConverter.RECT_SIZE / 2 - 1), - - /** - * Unknown catalysis. - */ - UNKNOWN_CATALYSIS("UNKNOWN_CATALYSIS", UnknownCatalysis.class, ArrowType.CIRCLE, 8.0, 0.0, LineType.DASHED), - - /** - * Unknown inhibition. - */ - UNKNOWN_INHIBITION("UNKNOWN_INHIBITION", UnknownInhibition.class, ArrowType.CROSSBAR, 8.0, ReactionCellDesignerConverter.RECT_SIZE / 2 - 1, LineType.DASHED), - - /** - * Physical stimulation. - */ - PHYSICAL_STIMULATION("PHYSICAL_STIMULATION", PhysicalStimulation.class, ArrowType.BLANK), - - /** - * Modulation. - */ - MODULATION_STRING("MODULATION", Modulation.class, ArrowType.DIAMOND), - - /** - * Trigger. - */ - TRIGGER_STRING("TRIGGER", Trigger.class, ArrowType.BLANK_CROSSBAR); - - /** - * CellDesigner string describing this type. - */ - private String stringName; - /** - * Which class should be used for this type. - */ - private Class<? extends Modifier> clazz; - /** - * How the arrow head of the line should look like. - */ - private ArrowTypeData atd = new ArrowTypeData(); - /** - * How much should be the arrow line trimmed. - */ - private double trimLength = 0; - /** - * What line type should be used for this modifier. - */ - private LineType lineType = LineType.SOLID; - - /** - * Constructor used to create and initialize this enum. - * - * @param string - * {@link #stringName} - * @param clazz - * {@link #clazz} - * @param at - * type of the arrow - */ - ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at) { - this(string, clazz, at, null, null, null); - } - - /** - * Constructor used to create and initialize this enum. - * - * @param string - * {@link #stringName} - * @param clazz - * {@link #clazz} - * @param at - * type of the arrow - * @param arrowLength - * length of the arrow - */ - ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at, Double arrowLength) { - this(string, clazz, at, arrowLength, null, null); - } - - /** - * Constructor used to create and initialize this enum. - * - * @param string - * {@link #stringName} - * @param clazz - * {@link #clazz} - * @param at - * type of the arrow - * @param arrowLength - * length of the arrow - * @param trimLength - * {@link #trimLength} - */ - ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at, Double arrowLength, Double trimLength) { - this(string, clazz, at, arrowLength, trimLength, null); - } - - /** - * Constructor used to create and initialize this enum. - * - * @param string - * {@link #stringName} - * @param clazz - * {@link #clazz} - * @param at - * type of the arrow - * @param arrowLength - * length of the arrow - * @param trimLength - * {@link #trimLength} - * @param lt - * {@link #lineType} - */ - ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at, Double arrowLength, Double trimLength, LineType lt) { - stringName = string; - this.clazz = clazz; - if (at != null) { - atd.setArrowType(at); - } - if (arrowLength != null) { - atd.setLen(arrowLength); - } - if (trimLength != null) { - this.trimLength = trimLength; - } - if (lt != null) { - lineType = lt; - } - - } - - /** - * - * @return {@link #stringName} - */ - public String getStringName() { - return stringName; - } - - /** - * - * @return {@link #clazz} - */ - public Class<? extends Modifier> getClazz() { - return clazz; - } - - /** - * - * @return {@link #atd} - */ - public ArrowTypeData getAtd() { - return atd; - } - - /** - * - * @return {@link #trimLength} - */ - public double getTrimLength() { - return trimLength; - } - - /** - * - * @return {@link #lineType} - */ - public LineType getLineType() { - return lineType; - } + + /** + * Catalysis. + */ + CATALYSIS("CATALYSIS", Catalysis.class, ArrowType.CIRCLE, 8.0), + + /** + * Inhibition. + */ + INHIBITION("INHIBITION", Inhibition.class, ArrowType.CROSSBAR, 8.0, ReactionCellDesignerConverter.RECT_SIZE / 2 - 1), + + /** + * Unknown catalysis. + */ + UNKNOWN_CATALYSIS("UNKNOWN_CATALYSIS", UnknownCatalysis.class, ArrowType.CIRCLE, 8.0, 0.0, LineType.DASHED), + + /** + * Unknown inhibition. + */ + UNKNOWN_INHIBITION("UNKNOWN_INHIBITION", UnknownInhibition.class, ArrowType.CROSSBAR, 8.0, + ReactionCellDesignerConverter.RECT_SIZE / 2 - 1, LineType.DASHED), + + /** + * Physical stimulation. + */ + PHYSICAL_STIMULATION("PHYSICAL_STIMULATION", PhysicalStimulation.class, ArrowType.BLANK), + + /** + * Modulation. + */ + MODULATION_STRING("MODULATION", Modulation.class, ArrowType.DIAMOND), + + /** + * Trigger. + */ + TRIGGER_STRING("TRIGGER", Trigger.class, ArrowType.BLANK_CROSSBAR); + + /** + * CellDesigner string describing this type. + */ + private String stringName; + /** + * Which class should be used for this type. + */ + private Class<? extends Modifier> clazz; + /** + * How the arrow head of the line should look like. + */ + private ArrowTypeData atd = new ArrowTypeData(); + /** + * How much should be the arrow line trimmed. + */ + private double trimLength = 0; + /** + * What line type should be used for this modifier. + */ + private LineType lineType = LineType.SOLID; + + /** + * Constructor used to create and initialize this enum. + * + * @param string + * {@link #stringName} + * @param clazz + * {@link #clazz} + * @param at + * type of the arrow + */ + ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at) { + this(string, clazz, at, null, null, null); + } + + /** + * Constructor used to create and initialize this enum. + * + * @param string + * {@link #stringName} + * @param clazz + * {@link #clazz} + * @param at + * type of the arrow + * @param arrowLength + * length of the arrow + */ + ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at, Double arrowLength) { + this(string, clazz, at, arrowLength, null, null); + } + + /** + * Constructor used to create and initialize this enum. + * + * @param string + * {@link #stringName} + * @param clazz + * {@link #clazz} + * @param at + * type of the arrow + * @param arrowLength + * length of the arrow + * @param trimLength + * {@link #trimLength} + */ + ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at, Double arrowLength, Double trimLength) { + this(string, clazz, at, arrowLength, trimLength, null); + } + + /** + * Constructor used to create and initialize this enum. + * + * @param string + * {@link #stringName} + * @param clazz + * {@link #clazz} + * @param at + * type of the arrow + * @param arrowLength + * length of the arrow + * @param trimLength + * {@link #trimLength} + * @param lt + * {@link #lineType} + */ + ModifierType(String string, Class<? extends Modifier> clazz, ArrowType at, Double arrowLength, Double trimLength, + LineType lt) { + stringName = string; + this.clazz = clazz; + if (at != null) { + atd.setArrowType(at); + } + if (arrowLength != null) { + atd.setLen(arrowLength); + } + if (trimLength != null) { + this.trimLength = trimLength; + } + if (lt != null) { + lineType = lt; + } + + } + + /** + * + * @return {@link #stringName} + */ + public String getStringName() { + return stringName; + } + + /** + * + * @return {@link #clazz} + */ + public Class<? extends Modifier> getClazz() { + return clazz; + } + + /** + * + * @return {@link #atd} + */ + public ArrowTypeData getAtd() { + return atd; + } + + /** + * + * @return {@link #trimLength} + */ + public double getTrimLength() { + return trimLength; + } + + /** + * + * @return {@link #lineType} + */ + public LineType getLineType() { + return lineType; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtils.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtils.java index 4e6d2650ea..d2bd4390d2 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtils.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtils.java @@ -3,17 +3,15 @@ package lcsb.mapviewer.converter.model.celldesigner.types; import java.awt.geom.Line2D; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +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.common.geometry.PointTransformation; import lcsb.mapviewer.converter.model.celldesigner.geometry.ReactionCellDesignerConverter; import lcsb.mapviewer.model.graphics.PolylineData; -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.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -26,281 +24,282 @@ import lcsb.mapviewer.model.map.species.Species; */ public class ModifierTypeUtils { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(ModifierTypeUtils.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(ModifierTypeUtils.class); - /** - * Returns {@link ModifierType} that reference to the clazz. - * - * @param clazz - * class type for which result is returned - * @return {@link ModifierType} that reference to the clazz - */ - public ModifierType getModifierTypeForClazz(Class<? extends Modifier> clazz) { - for (ModifierType modType : ModifierType.values()) { - if (clazz.equals(modType.getClazz())) { - return modType; - } - } - return null; - } + /** + * Returns {@link ModifierType} that reference to the clazz. + * + * @param clazz + * class type for which result is returned + * @return {@link ModifierType} that reference to the clazz + */ + public ModifierType getModifierTypeForClazz(Class<? extends Modifier> clazz) { + for (ModifierType modType : ModifierType.values()) { + if (clazz.equals(modType.getClazz())) { + return modType; + } + } + return null; + } - /** - * Returns {@link ModifierType} that reference to the CellDesigner string - * 'type'. - * - * @param type - * CellDesigner string defining modifier type - * @return {@link ModifierType} that reference to the CellDesigner 'type' - */ - public ModifierType getModifierTypeForStringType(String type) { - for (ModifierType modType : ModifierType.values()) { - if (type.equalsIgnoreCase(modType.getStringName())) { - return modType; - } - } - return null; - } + /** + * Returns {@link ModifierType} that reference to the CellDesigner string + * 'type'. + * + * @param type + * CellDesigner string defining modifier type + * @return {@link ModifierType} that reference to the CellDesigner 'type' + */ + public ModifierType getModifierTypeForStringType(String type) { + for (ModifierType modType : ModifierType.values()) { + if (type.equalsIgnoreCase(modType.getStringName())) { + return modType; + } + } + return null; + } - /** - * Creates {@link Modifier} for the CellDesigner type. - * - * @param type - * CellDesigner type of the modifier - * @param alias - * alias to which modifier point to - * @return {@link Modifier} for the CellDesigner type - */ - public Modifier createModifierForStringType(String type, Species alias) { - ModifierType modType = getModifierTypeForStringType(type); - if (modType == null) { - throw new InvalidArgumentException("Unknown modifier type: " + type); - } - try { - Modifier mod = modType.getClazz().getConstructor(Element.class).newInstance(alias); - return mod; - } catch (Exception e) { - throw new InvalidStateException("Problem with instantiation of Modifier class: " + type); - } - } + /** + * Creates {@link Modifier} for the CellDesigner type. + * + * @param type + * CellDesigner type of the modifier + * @param alias + * alias to which modifier point to + * @return {@link Modifier} for the CellDesigner type + */ + public Modifier createModifierForStringType(String type, Species alias) { + ModifierType modType = getModifierTypeForStringType(type); + if (modType == null) { + throw new InvalidArgumentException("Unknown modifier type: " + type); + } + try { + Modifier mod = modType.getClazz().getConstructor(Element.class).newInstance(alias); + return mod; + } catch (Exception e) { + throw new InvalidStateException("Problem with instantiation of Modifier class: " + type); + } + } - /** - * Returns CellDesigner string used for modifier creation. - * - * @param modifier - * modifier for which CellDesigner string is looked for - * @return CellDesigner string used for modifier creation - */ - public String getStringTypeByModifier(Modifier modifier) { - ModifierType modifierType = getModifierTypeForClazz(modifier.getClass()); - if (modifierType != null) { - return modifierType.getStringName(); - } - return null; - } + /** + * Returns CellDesigner string used for modifier creation. + * + * @param modifier + * modifier for which CellDesigner string is looked for + * @return CellDesigner string used for modifier creation + */ + public String getStringTypeByModifier(Modifier modifier) { + ModifierType modifierType = getModifierTypeForClazz(modifier.getClass()); + if (modifierType != null) { + return modifierType.getStringName(); + } + return null; + } - /** - * Returns string that identfies TargetLine index for the modifier. TargetLine - * index is a CellDesigner String that identifies to which point on the - * rectangle in the center line modifier line is connected. - * - * @param modifier - * modifier for target line - * @return string that identfies TargetLine index for the modifier - */ - public String getTargetLineIndexByModifier(Modifier modifier) { - ModifierType modType = getModifierTypeForClazz(modifier.getClass()); - if (modType == null) { - throw new InvalidArgumentException("Unknown modifier class: " + modifier.getClass()); - } + /** + * Returns string that identfies TargetLine index for the modifier. TargetLine + * index is a CellDesigner String that identifies to which point on the + * rectangle in the center line modifier line is connected. + * + * @param modifier + * modifier for target line + * @return string that identfies TargetLine index for the modifier + */ + public String getTargetLineIndexByModifier(Modifier modifier) { + ModifierType modType = getModifierTypeForClazz(modifier.getClass()); + if (modType == null) { + throw new InvalidArgumentException("Unknown modifier class: " + modifier.getClass()); + } - Reaction reaction = modifier.getReaction(); - PolylineData line = modifier.getLine(); + Reaction reaction = modifier.getReaction(); + PolylineData line = modifier.getLine(); - String result = getTragteLineIndex(modType, reaction, line); - return result; - } + String result = getTragteLineIndex(modType, reaction, line); + return result; + } - /** - * Returns string that identfies TargetLine index for the modifier operator. - * TargetLine index is a CellDesigner String that identifies to which point on - * the rectangle in the center line modifier line is connected. - * - * @param modifier - * modifier operator for target line - * @return string that identfies TargetLine index for the modifier - */ - public String getTargetLineIndexByModifier(NodeOperator modifier) { - if (!(modifier.getInputs().get(0) instanceof Modifier)) { - throw new InvalidArgumentException("Invalid NodeOperator"); - } else { - ModifierType modType = getModifierTypeForClazz(((Modifier) modifier.getInputs().get(0)).getClass()); + /** + * Returns string that identfies TargetLine index for the modifier operator. + * TargetLine index is a CellDesigner String that identifies to which point on + * the rectangle in the center line modifier line is connected. + * + * @param modifier + * modifier operator for target line + * @return string that identfies TargetLine index for the modifier + */ + public String getTargetLineIndexByModifier(NodeOperator modifier) { + if (!(modifier.getInputs().get(0) instanceof Modifier)) { + throw new InvalidArgumentException("Invalid NodeOperator"); + } else { + ModifierType modType = getModifierTypeForClazz(((Modifier) modifier.getInputs().get(0)).getClass()); - if (modType == null) { - throw new InvalidArgumentException("Unknown modifier class: " + modifier.getClass()); - } + if (modType == null) { + throw new InvalidArgumentException("Unknown modifier class: " + modifier.getClass()); + } - Reaction reaction = modifier.getReaction(); - PolylineData line = modifier.getLine(); + Reaction reaction = modifier.getReaction(); + PolylineData line = modifier.getLine(); - String result = getTragteLineIndex(modType, reaction, line); - return result; - } - } + String result = getTragteLineIndex(modType, reaction, line); + return result; + } + } - /** - * Returns string that identfies TargetLine index for the modifier line - * connected to reaction (target line index is explained here: - * {@link #getTargetLineIndexByModifier(Modifier)}). - * - * - * @param modType - * type of modifier for the line - * @param reaction - * reaction on which target line index is looked for - * @param originalLine - * line that connects modifier to the reaction - * @return string that identifies TargetLine index for modifier line - */ - private String getTragteLineIndex(ModifierType modType, Reaction reaction, PolylineData originalLine) { - PolylineData line = new PolylineData(originalLine); - line.trimEnd(-modType.getTrimLength()); + /** + * Returns string that identfies TargetLine index for the modifier line + * connected to reaction (target line index is explained here: + * {@link #getTargetLineIndexByModifier(Modifier)}). + * + * + * @param modType + * type of modifier for the line + * @param reaction + * reaction on which target line index is looked for + * @param originalLine + * line that connects modifier to the reaction + * @return string that identifies TargetLine index for modifier line + */ + private String getTragteLineIndex(ModifierType modType, Reaction reaction, PolylineData originalLine) { + PolylineData line = new PolylineData(originalLine); + line.trimEnd(-modType.getTrimLength()); - String[] possibleValues = new String[] { "0,2", "0,3", "0,4", "0,5", "0,6", "0,7" }; - Point2D closestPoint = new Point2D.Double(Double.MAX_VALUE, Double.MAX_VALUE); - Point2D checkedPoint = line.getEndPoint(); - String result = "0,0"; - for (String string : possibleValues) { - Point2D point = getAnchorPointOnReactionRect(reaction, string); - if (point.distance(checkedPoint) < closestPoint.distance(checkedPoint)) { - closestPoint = point; - result = string; - } - } - return result; - } + String[] possibleValues = new String[] { "0,2", "0,3", "0,4", "0,5", "0,6", "0,7" }; + Point2D closestPoint = new Point2D.Double(Double.MAX_VALUE, Double.MAX_VALUE); + Point2D checkedPoint = line.getEndPoint(); + String result = "0,0"; + for (String string : possibleValues) { + Point2D point = getAnchorPointOnReactionRect(reaction, string); + if (point.distance(checkedPoint) < closestPoint.distance(checkedPoint)) { + closestPoint = point; + result = string; + } + } + return result; + } - /** - * This method get anchor point on the reaction line (the center point of this - * line is given as a parameter). The anchor point depends on the line and - * lineConnectionType associated with the modification. - * - * @param reaction - * reaction on which we are looking for a point - * @param lineConnectionType - * point of connection to the reaction center rectangle - * @return coordinates of point on the center rectangle - */ - public Point2D getAnchorPointOnReactionRect(Reaction reaction, String lineConnectionType) { - int countLines = reaction.getLine().getPoints().size()-1; - Line2D centerLine = reaction.getLine().getLines().get(countLines/2); - double dx = centerLine.getX2() - centerLine.getX1(); - double dy = centerLine.getY2() - centerLine.getY1(); - double angle = Math.atan2(dy, dx); - Point2D mid = new Point2D.Double((centerLine.getX1() + centerLine.getX2()) / 2, (centerLine.getY1() + centerLine.getY2()) / 2); + /** + * This method get anchor point on the reaction line (the center point of this + * line is given as a parameter). The anchor point depends on the line and + * lineConnectionType associated with the modification. + * + * @param reaction + * reaction on which we are looking for a point + * @param lineConnectionType + * point of connection to the reaction center rectangle + * @return coordinates of point on the center rectangle + */ + public Point2D getAnchorPointOnReactionRect(Reaction reaction, String lineConnectionType) { + int countLines = reaction.getLine().getPoints().size() - 1; + Line2D centerLine = reaction.getLine().getLines().get(countLines / 2); + double dx = centerLine.getX2() - centerLine.getX1(); + double dy = centerLine.getY2() - centerLine.getY1(); + double angle = Math.atan2(dy, dx); + Point2D mid = new Point2D.Double((centerLine.getX1() + centerLine.getX2()) / 2, + (centerLine.getY1() + centerLine.getY2()) / 2); - String id = lineConnectionType; - String[] spr = id.split(","); - double x = mid.getX(); - double y = mid.getY(); - if (spr.length > 1) { - id = spr[1]; - if (id.equals("2")) { - y -= ReactionCellDesignerConverter.RECT_SIZE / 2; - } else if (id.equals("3")) { - y += ReactionCellDesignerConverter.RECT_SIZE / 2; - } else if (id.equals("4")) { - y -= ReactionCellDesignerConverter.RECT_SIZE / 2; - x -= ReactionCellDesignerConverter.RECT_SIZE / 2; - } else if (id.equals("5")) { - y -= ReactionCellDesignerConverter.RECT_SIZE / 2; - x += ReactionCellDesignerConverter.RECT_SIZE / 2; - } else if (id.equals("6")) { - y += ReactionCellDesignerConverter.RECT_SIZE / 2; - x -= ReactionCellDesignerConverter.RECT_SIZE / 2; - } else if (id.equals("7")) { - y += ReactionCellDesignerConverter.RECT_SIZE / 2; - x += ReactionCellDesignerConverter.RECT_SIZE / 2; - } else if (id.equals("0")) { - // this is only workaround... - y += ReactionCellDesignerConverter.RECT_SIZE / 2; - } else { - throw new InvalidArgumentException("Unknown targetLineIndex: " + id); - } + String id = lineConnectionType; + String[] spr = id.split(","); + double x = mid.getX(); + double y = mid.getY(); + if (spr.length > 1) { + id = spr[1]; + if (id.equals("2")) { + y -= ReactionCellDesignerConverter.RECT_SIZE / 2; + } else if (id.equals("3")) { + y += ReactionCellDesignerConverter.RECT_SIZE / 2; + } else if (id.equals("4")) { + y -= ReactionCellDesignerConverter.RECT_SIZE / 2; + x -= ReactionCellDesignerConverter.RECT_SIZE / 2; + } else if (id.equals("5")) { + y -= ReactionCellDesignerConverter.RECT_SIZE / 2; + x += ReactionCellDesignerConverter.RECT_SIZE / 2; + } else if (id.equals("6")) { + y += ReactionCellDesignerConverter.RECT_SIZE / 2; + x -= ReactionCellDesignerConverter.RECT_SIZE / 2; + } else if (id.equals("7")) { + y += ReactionCellDesignerConverter.RECT_SIZE / 2; + x += ReactionCellDesignerConverter.RECT_SIZE / 2; + } else if (id.equals("0")) { + // this is only workaround... + y += ReactionCellDesignerConverter.RECT_SIZE / 2; + } else { + throw new InvalidArgumentException("Unknown targetLineIndex: " + id); + } - } else { - throw new InvalidArgumentException("Invalid targetLineIndex: " + id); - } - Point2D p = new Point2D.Double(x, y); - PointTransformation pointTransformation = new PointTransformation(); - p = pointTransformation.rotatePoint(p, angle, mid); - return p; - } + } else { + throw new InvalidArgumentException("Invalid targetLineIndex: " + id); + } + Point2D p = new Point2D.Double(x, y); + PointTransformation pointTransformation = new PointTransformation(); + p = pointTransformation.rotatePoint(p, angle, mid); + return p; + } - /** - * Update line parameters to make it look like a proper modifier. - * - * @param modifier - * modifier for which line will be modified - */ - public void updateLineEndPoint(Modifier modifier) { - ModifierType modType = getModifierTypeForClazz(modifier.getClass()); - if (modType == null) { - throw new InvalidArgumentException("Unknown modifier class: " + modifier.getClass()); - } - PolylineData line = modifier.getLine(); - updateLineByType(modType, line); - } + /** + * Update line parameters to make it look like a proper modifier. + * + * @param modifier + * modifier for which line will be modified + */ + public void updateLineEndPoint(Modifier modifier) { + ModifierType modType = getModifierTypeForClazz(modifier.getClass()); + if (modType == null) { + throw new InvalidArgumentException("Unknown modifier class: " + modifier.getClass()); + } + PolylineData line = modifier.getLine(); + updateLineByType(modType, line); + } - /** - * Updates line parameters of modifier operator to make it look like a proper - * modifier. - * - * @param operator - * modifier operator for which line will be modified - */ - @SuppressWarnings("unchecked") - public void updateLineEndPoint(NodeOperator operator) { - Class<? extends AbstractNode> clazz = operator.getInputs().get(1).getClass(); - if (Modifier.class.isAssignableFrom(clazz)) { - ModifierType modType = getModifierTypeForClazz((Class<? extends Modifier>) clazz); - if (modType == null) { - throw new InvalidArgumentException("Unknown modifier class: " + clazz); - } - PolylineData line = operator.getLine(); - updateLineByType(modType, line); - } else { - throw new InvalidArgumentException("Operator contains invalid input: " + clazz); - } - } + /** + * Updates line parameters of modifier operator to make it look like a proper + * modifier. + * + * @param operator + * modifier operator for which line will be modified + */ + @SuppressWarnings("unchecked") + public void updateLineEndPoint(NodeOperator operator) { + Class<? extends AbstractNode> clazz = operator.getInputs().get(1).getClass(); + if (Modifier.class.isAssignableFrom(clazz)) { + ModifierType modType = getModifierTypeForClazz((Class<? extends Modifier>) clazz); + if (modType == null) { + throw new InvalidArgumentException("Unknown modifier class: " + clazz); + } + PolylineData line = operator.getLine(); + updateLineByType(modType, line); + } else { + throw new InvalidArgumentException("Operator contains invalid input: " + clazz); + } + } - /** - * Updates line parameters to make it look like a proper modifier. - * - * @param modType - * type of modifier - * @param line - * line to update - */ - private void updateLineByType(ModifierType modType, PolylineData line) { - line.setEndAtd(modType.getAtd().copy()); - line.setType(modType.getLineType()); - line.trimEnd(modType.getTrimLength()); - } + /** + * Updates line parameters to make it look like a proper modifier. + * + * @param modType + * type of modifier + * @param line + * line to update + */ + private void updateLineByType(ModifierType modType, PolylineData line) { + line.setEndAtd(modType.getAtd().copy()); + line.setType(modType.getLineType()); + line.trimEnd(modType.getTrimLength()); + } - /** - * Returns type of the modifier in modifier operator. - * - * @param modifierOperator - * opertor for which type will be returned - * @return type of the modifier in modifier operator - */ - public ModifierType getModifierTypeForOperator(NodeOperator modifierOperator) { - Modifier mod = (Modifier) modifierOperator.getInputs().get(0); - return getModifierTypeForClazz(mod.getClass()); - } + /** + * Returns type of the modifier in modifier operator. + * + * @param modifierOperator + * opertor for which type will be returned + * @return type of the modifier in modifier operator + */ + public ModifierType getModifierTypeForOperator(NodeOperator modifierOperator) { + Modifier mod = (Modifier) modifierOperator.getInputs().get(0); + return getModifierTypeForClazz(mod.getClass()); + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorType.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorType.java index 7f6d880876..5c0ad3dab2 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorType.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorType.java @@ -1,10 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.NandOperator; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.OrOperator; -import lcsb.mapviewer.model.map.reaction.UnknownOperator; +import lcsb.mapviewer.model.map.reaction.*; /** * This enum defines how different types of CellDesigner operators should be @@ -15,80 +11,80 @@ import lcsb.mapviewer.model.map.reaction.UnknownOperator; */ public enum OperatorType { - /** - * Boolean and operator. - */ - AND_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_AND", AndOperator.class), + /** + * Boolean and operator. + */ + AND_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_AND", AndOperator.class), - /** - * Boolean not and operator. - */ - NAND_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_NOT", NandOperator.class), + /** + * Boolean not and operator. + */ + NAND_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_NOT", NandOperator.class), - /** - * Boolean or operator. - */ - OR_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_OR", OrOperator.class), + /** + * Boolean or operator. + */ + OR_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_OR", OrOperator.class), - /** - * Boolean unknown operator. - */ - UNKNOWN_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_UNKNOWN", UnknownOperator.class); + /** + * Boolean unknown operator. + */ + UNKNOWN_OPERATOR_STRING("BOOLEAN_LOGIC_GATE_UNKNOWN", UnknownOperator.class); - /** - * CellDEsigner string identifing this operator. - */ - private String stringName; - /** - * Class in our model representing this operator. - */ - private Class<? extends NodeOperator> clazz; + /** + * CellDEsigner string identifing this operator. + */ + private String stringName; + /** + * Class in our model representing this operator. + */ + private Class<? extends NodeOperator> clazz; - /** - * Default constructor. Initialize enum with data. - * - * @param string - * {@link #stringName} - * @param clazz - * {@link #clazz} - */ - OperatorType(String string, Class<? extends NodeOperator> clazz) { - stringName = string; - this.clazz = clazz; - } + /** + * Default constructor. Initialize enum with data. + * + * @param string + * {@link #stringName} + * @param clazz + * {@link #clazz} + */ + OperatorType(String string, Class<? extends NodeOperator> clazz) { + stringName = string; + this.clazz = clazz; + } - /** - * @return the stringName - * @see #stringName - */ - public String getStringName() { - return stringName; - } + /** + * Returns {@link OperatorType} that should be applied to a class given in the + * parameter. + * + * @param clazz + * class for which we are looking for {@link OperatorType} + * @return {@link OperatorType} that should be applied to a class given in the + * parameter + */ + public static OperatorType getTypeByClass(Class<? extends NodeOperator> clazz) { + for (OperatorType type : OperatorType.values()) { + if (type.getClazz().equals(clazz)) { + return type; + } + } + return null; + } - /** - * @return the clazz - * @see #clazz - */ - public Class<? extends NodeOperator> getClazz() { - return clazz; - } + /** + * @return the stringName + * @see #stringName + */ + public String getStringName() { + return stringName; + } - /** - * Returns {@link OperatorType} that should be applied to a class given in the - * parameter. - * - * @param clazz - * class for which we are looking for {@link OperatorType} - * @return {@link OperatorType} that should be applied to a class given in the - * parameter - */ - public static OperatorType getTypeByClass(Class<? extends NodeOperator> clazz) { - for (OperatorType type : OperatorType.values()) { - if (type.getClazz().equals(clazz)) { - return type; - } - } - return null; - } + /** + * @return the clazz + * @see #clazz + */ + public Class<? extends NodeOperator> getClazz() { + return clazz; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtils.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtils.java index 64198f2339..4cc93d5b92 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtils.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtils.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidStateException; @@ -15,78 +16,78 @@ import lcsb.mapviewer.model.map.reaction.NodeOperator; */ public class OperatorTypeUtils { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(OperatorTypeUtils.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(OperatorTypeUtils.class); - /** - * Return {@link OperatorType} for the operator class. - * - * @param clazz - * clazz for which we are looking for operator type - * @return {@link OperatorType} corresponding to the given class - */ - public OperatorType getOperatorTypeForClazz(Class<? extends NodeOperator> clazz) { - for (OperatorType modType : OperatorType.values()) { - if (clazz.equals(modType.getClazz())) { - return modType; - } - } - return null; - } + /** + * Return {@link OperatorType} for the operator class. + * + * @param clazz + * clazz for which we are looking for operator type + * @return {@link OperatorType} corresponding to the given class + */ + public OperatorType getOperatorTypeForClazz(Class<? extends NodeOperator> clazz) { + for (OperatorType modType : OperatorType.values()) { + if (clazz.equals(modType.getClazz())) { + return modType; + } + } + return null; + } - /** - * Return {@link OperatorType} for the CellDesigner string representing - * operator. - * - * @param type - * CellDesigner string representing operator - * @return {@link OperatorType} corresponding to the given type - */ - protected OperatorType getOperatorTypeForStringType(String type) { - for (OperatorType modType : OperatorType.values()) { - if (type.equalsIgnoreCase(modType.getStringName())) { - return modType; - } - } - return null; - } + /** + * Return {@link OperatorType} for the CellDesigner string representing + * operator. + * + * @param type + * CellDesigner string representing operator + * @return {@link OperatorType} corresponding to the given type + */ + protected OperatorType getOperatorTypeForStringType(String type) { + for (OperatorType modType : OperatorType.values()) { + if (type.equalsIgnoreCase(modType.getStringName())) { + return modType; + } + } + return null; + } - /** - * Creates operator for the type identified by CellDesigner string. - * - * @param type - * CellDesigner string identifing operator type. - * @return empty {@link NodeOperator} of the type given in parameter - */ - public NodeOperator createModifierForStringType(String type) { - NodeOperator operator = null; - OperatorType opType = getOperatorTypeForStringType(type); - if (opType == null) { - throw new InvalidArgumentException("Unknown modifier type: " + type); - } - try { - operator = opType.getClazz().getConstructor().newInstance(); - } catch (Exception e) { - throw new InvalidStateException("Problem with instantiation of NodeOperator class: " + type, e); - } - return operator; - } + /** + * Creates operator for the type identified by CellDesigner string. + * + * @param type + * CellDesigner string identifing operator type. + * @return empty {@link NodeOperator} of the type given in parameter + */ + public NodeOperator createModifierForStringType(String type) { + NodeOperator operator = null; + OperatorType opType = getOperatorTypeForStringType(type); + if (opType == null) { + throw new InvalidArgumentException("Unknown modifier type: " + type); + } + try { + operator = opType.getClazz().getConstructor().newInstance(); + } catch (Exception e) { + throw new InvalidStateException("Problem with instantiation of NodeOperator class: " + type, e); + } + return operator; + } - /** - * Returns CellDesigner string for the operator type. - * - * @param modifierOperator - * operator for which CellDesigner string is looked for - * @return CellDesigner string for the operator type - */ - public String getStringTypeByOperator(NodeOperator modifierOperator) { - OperatorType operatorType = getOperatorTypeForClazz(modifierOperator.getClass()); - if (operatorType != null) { - return operatorType.getStringName(); - } - return null; - } + /** + * Returns CellDesigner string for the operator type. + * + * @param modifierOperator + * operator for which CellDesigner string is looked for + * @return CellDesigner string for the operator type + */ + public String getStringTypeByOperator(NodeOperator modifierOperator) { + OperatorType operatorType = getOperatorTypeForClazz(modifierOperator.getClass()); + if (operatorType != null) { + return operatorType.getStringName(); + } + return null; + } } diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/package-info.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/package-info.java index c61e202f20..3f916f3e82 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/package-info.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/types/package-info.java @@ -3,4 +3,3 @@ * used in our model. */ package lcsb.mapviewer.converter.model.celldesigner.types; - diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitCollectionXmlParser.java index 953a422ca2..7703997ab8 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitCollectionXmlParser.java @@ -24,7 +24,7 @@ public class UnitCollectionXmlParser { public String toXml(Set<SbmlUnit> units) { StringBuilder builder = new StringBuilder(); builder.append("<listOfUnitDefinitions>\n"); - for (SbmlUnit unit: units) { + for (SbmlUnit unit : units) { builder.append(unitParser.toXml(unit)); } builder.append("</listOfUnitDefinitions>\n"); diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitXmlParser.java index fa9a1d9ac7..724e0b2386 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/unit/UnitXmlParser.java @@ -3,14 +3,13 @@ package lcsb.mapviewer.converter.model.celldesigner.unit; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; -import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; -import lcsb.mapviewer.model.map.kinetics.SbmlUnitTypeFactor; +import lcsb.mapviewer.model.map.kinetics.*; public class UnitXmlParser { /** diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java index 9e1b17f23e..790087f132 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/CellDesignerTestFunctions.java @@ -2,39 +2,22 @@ package lcsb.mapviewer.converter.model.celldesigner; import static org.junit.Assert.assertEquals; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.List; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; +import javax.xml.parsers.*; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.junit.*; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -48,14 +31,11 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelComparator; public abstract class CellDesignerTestFunctions { - private Logger logger = LogManager.getLogger(CellDesignerTestFunctions.class); - protected static double EPSILON = Configuration.EPSILON; - - private MinervaLoggerAppender appender; - @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + private Logger logger = LogManager.getLogger(CellDesignerTestFunctions.class); + private MinervaLoggerAppender appender; @Before public final void _setUp() throws Exception { @@ -246,7 +226,6 @@ public abstract class CellDesignerTestFunctions { assertEquals(0, comparator.compare(model, model2)); } - protected Model serializeModel(Model model) throws InconsistentModelException, UnsupportedEncodingException, InvalidInputDataExecption { CellDesignerXmlParser parser = new CellDesignerXmlParser(); @@ -261,5 +240,4 @@ public abstract class CellDesignerTestFunctions { return model2; } - } 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 b2c402159d..0716583693 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 @@ -1,13 +1,14 @@ package lcsb.mapviewer.converter.model.celldesigner; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; -import java.awt.Color; +import java.awt.*; import java.awt.geom.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java index 2b3f5b5628..c630d756dd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/ComplexParserTests.java @@ -1,21 +1,15 @@ package lcsb.mapviewer.converter.model.celldesigner; -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 static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.io.ByteArrayInputStream; -import java.util.ArrayList; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.ConverterParams; @@ -24,18 +18,9 @@ import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; 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 lcsb.mapviewer.model.map.model.ModelFullIndexed; -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.Protein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; import lcsb.mapviewer.modelutils.map.ElementUtils; public class ComplexParserTests extends CellDesignerTestFunctions { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupExceptionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupExceptionTest.java index af15a37f2c..c393d0440d 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupExceptionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/InvalidGroupExceptionTest.java @@ -2,26 +2,24 @@ package lcsb.mapviewer.converter.model.celldesigner; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class InvalidGroupExceptionTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor() { - assertNotNull(new InvalidGroupException()); - assertNotNull(new InvalidGroupException("str")); - assertNotNull(new InvalidGroupException("str2", new Exception())); - assertNotNull(new InvalidGroupException(new Exception())); - } + @Test + public void testConstructor() { + assertNotNull(new InvalidGroupException()); + assertNotNull(new InvalidGroupException("str")); + assertNotNull(new InvalidGroupException("str2", new Exception())); + assertNotNull(new InvalidGroupException(new Exception())); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java index efd8836919..9f9baf61dd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/LayerXmlParserTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.converter.model.celldesigner; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.Collection; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java index 77be63a349..c140cc05c0 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/NestedComplexParsingTests.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SbmlValidationTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SbmlValidationTests.java index 015835c412..8fdaaf5f94 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SbmlValidationTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/SbmlValidationTests.java @@ -5,9 +5,7 @@ import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AllAliasTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AllAliasTests.java index 0e90824423..4da792bc5a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AllAliasTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/AllAliasTests.java @@ -5,9 +5,9 @@ import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ AliasCollectionXmlParserTest.class, - ComplexAliasXmlParserTest.class, - CompartmentAliasXmlParserTest.class, - SpeciesAliasXmlParserTest.class, + ComplexAliasXmlParserTest.class, + CompartmentAliasXmlParserTest.class, + SpeciesAliasXmlParserTest.class, }) public class AllAliasTests { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java index 3d233cffe1..aca802ebdd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/ComplexAliasXmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.*; @@ -14,8 +15,8 @@ import lcsb.mapviewer.model.map.species.Complex; public class ComplexAliasXmlParserTest extends CellDesignerTestFunctions { Model model; - private ComplexAliasXmlParser parser; CellDesignerElementCollection elements; + private ComplexAliasXmlParser parser; @Before public void setUp() throws Exception { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java index 3e983e66b9..20662bf304 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/alias/SpeciesAliasXmlParserTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.alias; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; @@ -24,13 +24,12 @@ public class SpeciesAliasXmlParserTest extends CellDesignerTestFunctions { static Logger logger = LogManager.getLogger(SpeciesAliasXmlParser.class); Model model; + CellDesignerElementCollection elements; private SpeciesAliasXmlParser parser; - private String testCompartmentAliasId2 = "s3"; private String testCompartmentAliasId = "s4"; private String testSpeciesId = "s5"; private String testAliasId = "s6"; - CellDesignerElementCollection elements; @Before public void setUp() throws Exception { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java index 1d4244c0d4..31d2fb394d 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/NoteFieldTest.java @@ -2,31 +2,28 @@ package lcsb.mapviewer.converter.model.celldesigner.annotation; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class NoteFieldTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testVallues() { - for (NoteField field : NoteField.values()) { - assertNotNull(NoteField.valueOf(field.toString())); - assertNotNull(field.getClazz()); - } - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testVallues() { + for (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/compartment/AllCompartmentTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/AllCompartmentTests.java index b8476cc09e..ab8f482825 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/AllCompartmentTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/AllCompartmentTests.java @@ -6,8 +6,8 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ CompartmentCollectionXmlParserTest.class, - CompartmentParserTests.class, - CompartmentXmlParserTest.class, + CompartmentParserTests.class, + CompartmentXmlParserTest.class, }) public class AllCompartmentTests { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java index ed2af3a9f2..1907d1bb66 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentCollectionXmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java index c251c2c564..f36ef35e55 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/compartment/CompartmentParserTests.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionCollectionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionCollectionXmlParserTest.java index 618f799af2..b972d36396 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionCollectionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionCollectionXmlParserTest.java @@ -4,7 +4,8 @@ import static org.junit.Assert.assertEquals; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.common.comparator.SetComparator; @@ -19,7 +20,8 @@ public class FunctionCollectionXmlParserTest extends CellDesignerTestFunctions { public void testToXml() throws Exception { FunctionCollectionXmlParser parser = new FunctionCollectionXmlParser(); Set<SbmlFunction> functions = parser - .parseXmlFunctionCollection(super.getXmlDocumentFromFile("testFiles/function/function_list.xml").getFirstChild()); + .parseXmlFunctionCollection( + super.getXmlDocumentFromFile("testFiles/function/function_list.xml").getFirstChild()); String xml = parser.toXml(functions); Set<SbmlFunction> functions2 = parser.parseXmlFunctionCollection(super.getNodeFromXmlString(xml)); diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParserTest.java index a06fcc19c3..631326e015 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/function/FunctionXmlParserTest.java @@ -1,12 +1,11 @@ package lcsb.mapviewer.converter.model.celldesigner.function; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import java.io.IOException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverterTest.java index 97e3e031bd..01466f3a29 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AbstractCellDesignerAliasConverterTest.java @@ -2,20 +2,16 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; import static org.junit.Assert.assertEquals; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; - import lcsb.mapviewer.common.geometry.LineTransformation; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerEllipseTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerPolygonTransformation; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerRectangleTransformation; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.*; +import lcsb.mapviewer.model.map.species.*; public class AbstractCellDesignerAliasConverterTest extends CellDesignerTestFunctions { Logger logger = LogManager.getLogger(AbstractCellDesignerAliasConverterTest.class); @@ -30,11 +26,11 @@ public class AbstractCellDesignerAliasConverterTest extends CellDesignerTestFunc @Test public void testGetAnchorPointCoordinatesForInvalidImplementation() { - Protein alias = new GenericProtein("id"); - alias.setWidth(1); - alias.setHeight(1); - converter.getAnchorPointCoordinates(alias, 0); - assertEquals(1, getWarnings().size()); + Protein alias = new GenericProtein("id"); + alias.setWidth(1); + alias.setHeight(1); + converter.getAnchorPointCoordinates(alias, 0); + assertEquals(1, getWarnings().size()); } @Test diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AllGeometryTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AllGeometryTests.java index 09f80e2522..9dd9555a46 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AllGeometryTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AllGeometryTests.java @@ -1,26 +1,26 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.AllHelperTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.AllHelperTests; + @RunWith(Suite.class) @SuiteClasses({ AbstractCellDesignerAliasConverterTest.class, - AllHelperTests.class, - AntisenseRnaCellDesignerAliasConverterTest.class, - CellDesignerAliasConverterTest.class, - ComplexConverterTest.class, - DegradedCellDesignerAliasConverterTest.class, - GeneCellDesignerAliasConverterTest.class, - IonCellDesignerAliasConverterTest.class, - ProteinConverterTest.class, - ProteinCellDesignerAliasConverterTest.class, - ReactionCellDesignerConverterTest.class, - RnaCellDesignerAliasConverterTest.class, - SimpleMoleculeCellDesignerAliasConverterTest.class, - UnknownCellDesignerAliasConverterTest.class, + AllHelperTests.class, + AntisenseRnaCellDesignerAliasConverterTest.class, + CellDesignerAliasConverterTest.class, + ComplexConverterTest.class, + DegradedCellDesignerAliasConverterTest.class, + GeneCellDesignerAliasConverterTest.class, + IonCellDesignerAliasConverterTest.class, + ProteinConverterTest.class, + ProteinCellDesignerAliasConverterTest.class, + ReactionCellDesignerConverterTest.class, + RnaCellDesignerAliasConverterTest.class, + SimpleMoleculeCellDesignerAliasConverterTest.class, + UnknownCellDesignerAliasConverterTest.class, }) public class AllGeometryTests { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverterTest.java index a12653e3a1..2f5634b2d5 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/AntisenseRnaCellDesignerAliasConverterTest.java @@ -5,10 +5,7 @@ import static org.junit.Assert.assertNotNull; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; import lcsb.mapviewer.model.map.model.Model; @@ -18,42 +15,42 @@ import lcsb.mapviewer.model.map.species.Species; public class AntisenseRnaCellDesignerAliasConverterTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetPointCoordinatesForSbgn() { - AntisenseRnaCellDesignerAliasConverter converter = new AntisenseRnaCellDesignerAliasConverter(true); - - Model model = new ModelFullIndexed(null); - Species alias = new GenericProtein("id"); - alias.setWidth(10); - alias.setHeight(10); - alias.setModel(model); - Point2D point = converter.getPointCoordinates(alias, CellDesignerAnchor.E); - assertNotNull(point); - } - - @Test - public void testGetAntisenseRnaPathForSbgn() { - AntisenseRnaCellDesignerAliasConverter converter = new AntisenseRnaCellDesignerAliasConverter(true); - - Model model = new ModelFullIndexed(null); - Species alias = new GenericProtein("id"); - alias.setWidth(10); - alias.setHeight(10); - alias.setModel(model); - PathIterator path = converter.getBoundPathIterator(alias); - assertNotNull(path); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetPointCoordinatesForSbgn() { + AntisenseRnaCellDesignerAliasConverter converter = new AntisenseRnaCellDesignerAliasConverter(true); + + Model model = new ModelFullIndexed(null); + Species alias = new GenericProtein("id"); + alias.setWidth(10); + alias.setHeight(10); + alias.setModel(model); + Point2D point = converter.getPointCoordinates(alias, CellDesignerAnchor.E); + assertNotNull(point); + } + + @Test + public void testGetAntisenseRnaPathForSbgn() { + AntisenseRnaCellDesignerAliasConverter converter = new AntisenseRnaCellDesignerAliasConverter(true); + + Model model = new ModelFullIndexed(null); + Species alias = new GenericProtein("id"); + alias.setWidth(10); + alias.setHeight(10); + alias.setModel(model); + PathIterator path = converter.getBoundPathIterator(alias); + assertNotNull(path); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java index 5cadff0013..a7e10d2352 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ComplexConverterTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverterTest.java index a91f48f823..060317c4f1 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/DegradedCellDesignerAliasConverterTest.java @@ -5,10 +5,7 @@ import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Degraded; @@ -16,42 +13,42 @@ import lcsb.mapviewer.model.map.species.Species; public class DegradedCellDesignerAliasConverterTest { - DegradedCellDesignerAliasConverter converter = new DegradedCellDesignerAliasConverter(false); - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetAnchorPointCoordinatesForInvalidAlias() { - Degraded alias = new Degraded("id"); - alias.setWidth(-1); - Point2D point = converter.getAnchorPointCoordinates(alias, 0); - assertNotNull(point); - } - - @Test - public void testGetAnchorPointCoordinatesForInvalidAlias2() { - Species alias = new Degraded("id"); - Point2D point = converter.getAnchorPointCoordinates(alias, 0); - assertNotNull(point); - } - - @Test - public void testNotImplementedMethod() { - try { - converter.getBoundPathIterator(null); - } catch (NotImplementedException e) { - assertTrue(e.getMessage().contains("This class doesn't have bound")); - } - } + DegradedCellDesignerAliasConverter converter = new DegradedCellDesignerAliasConverter(false); + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetAnchorPointCoordinatesForInvalidAlias() { + Degraded alias = new Degraded("id"); + alias.setWidth(-1); + Point2D point = converter.getAnchorPointCoordinates(alias, 0); + assertNotNull(point); + } + + @Test + public void testGetAnchorPointCoordinatesForInvalidAlias2() { + Species alias = new Degraded("id"); + Point2D point = converter.getAnchorPointCoordinates(alias, 0); + assertNotNull(point); + } + + @Test + public void testNotImplementedMethod() { + try { + converter.getBoundPathIterator(null); + } catch (NotImplementedException e) { + assertTrue(e.getMessage().contains("This class doesn't have bound")); + } + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverterTest.java index e4dfc70012..52a3079aea 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/GeneCellDesignerAliasConverterTest.java @@ -6,7 +6,8 @@ import static org.junit.Assert.assertNotNull; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.model.Model; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverterTest.java index c7cbcccba4..15fd4f9d77 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/IonCellDesignerAliasConverterTest.java @@ -5,10 +5,7 @@ import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Ion; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java index c50ba1f308..1fefc5cd18 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinCellDesignerAliasConverterTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java index fc6f42a034..c8774ca65f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ProteinConverterTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverterTest.java index 08dbb62a49..ff5601803e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/ReactionCellDesignerConverterTest.java @@ -1,30 +1,27 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ReactionCellDesignerConverterTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testConstructor() { - ReactionCellDesignerConverter onverter = new ReactionCellDesignerConverter(); - assertNotNull(onverter); - } + @Test + public void testConstructor() { + ReactionCellDesignerConverter onverter = new ReactionCellDesignerConverter(); + assertNotNull(onverter); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverterTest.java index e6f8670cc3..9ba53f5cd1 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/RnaCellDesignerAliasConverterTest.java @@ -5,10 +5,7 @@ import static org.junit.Assert.assertNotNull; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.converter.model.celldesigner.geometry.helper.CellDesignerAnchor; import lcsb.mapviewer.model.map.model.Model; @@ -18,42 +15,42 @@ import lcsb.mapviewer.model.map.species.Species; public class RnaCellDesignerAliasConverterTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetPointCoordinatesForSbgn() { - RnaCellDesignerAliasConverter converter = new RnaCellDesignerAliasConverter(true); - - Model model = new ModelFullIndexed(null); - Species alias = new GenericProtein("id"); - alias.setWidth(10); - alias.setHeight(10); - alias.setModel(model); - Point2D point = converter.getPointCoordinates(alias, CellDesignerAnchor.E); - assertNotNull(point); - } - - @Test - public void testGetAntisebseRnaPathForSbgn() { - RnaCellDesignerAliasConverter converter = new RnaCellDesignerAliasConverter(true); - - Model model = new ModelFullIndexed(null); - Species alias = new GenericProtein("id"); - alias.setWidth(10); - alias.setHeight(10); - alias.setModel(model); - PathIterator path = converter.getBoundPathIterator(alias); - assertNotNull(path); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetPointCoordinatesForSbgn() { + RnaCellDesignerAliasConverter converter = new RnaCellDesignerAliasConverter(true); + + Model model = new ModelFullIndexed(null); + Species alias = new GenericProtein("id"); + alias.setWidth(10); + alias.setHeight(10); + alias.setModel(model); + Point2D point = converter.getPointCoordinates(alias, CellDesignerAnchor.E); + assertNotNull(point); + } + + @Test + public void testGetAntisebseRnaPathForSbgn() { + RnaCellDesignerAliasConverter converter = new RnaCellDesignerAliasConverter(true); + + Model model = new ModelFullIndexed(null); + Species alias = new GenericProtein("id"); + alias.setWidth(10); + alias.setHeight(10); + alias.setModel(model); + PathIterator path = converter.getBoundPathIterator(alias); + assertNotNull(path); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java index 7fb94dd1f6..634f2ab333 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/SimpleMoleculeCellDesignerAliasConverterTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.awt.geom.Point2D; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverterTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverterTest.java index 0307655070..102748f343 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverterTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/UnknownCellDesignerAliasConverterTest.java @@ -5,10 +5,7 @@ import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Unknown; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/AllHelperTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/AllHelperTests.java index 364015e077..f883b0ad41 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/AllHelperTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/AllHelperTests.java @@ -6,12 +6,12 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ CellDesignerAnchorTest.class, - CellDesignerEllipseTransformationTest.class, - CellDesignerLineTransformationTest.class, - CellDesignerPointTransformationTest.class, - CellDesignerPolygonTransformationTest.class, - CellDesignerRectangleTransformationTest.class, - PolylineDataFactoryTest.class, + CellDesignerEllipseTransformationTest.class, + CellDesignerLineTransformationTest.class, + CellDesignerPointTransformationTest.class, + CellDesignerPolygonTransformationTest.class, + CellDesignerRectangleTransformationTest.class, + PolylineDataFactoryTest.class, }) public class AllHelperTests { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerAnchorTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerAnchorTest.java index d390e8afd6..fee260db95 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerAnchorTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerAnchorTest.java @@ -2,30 +2,27 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CellDesignerAnchorTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetters() { - for (CellDesignerAnchor value : CellDesignerAnchor.values()) { - assertNotNull(value.getName()); - } - } + @Test + public void testGetters() { + for (CellDesignerAnchor value : CellDesignerAnchor.values()) { + assertNotNull(value.getName()); + } + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformationTest.java index d72af04eab..1656978ee5 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerEllipseTransformationTest.java @@ -4,142 +4,140 @@ import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CellDesignerEllipseTransformationTest { - CellDesignerEllipseTransformation et = new CellDesignerEllipseTransformation(); - double x = 0; - double y = 10; - double width = 20; - double height = 30; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetPointOnEllipseByAnchorNull() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, null); - assertEquals(x + width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.E); - assertEquals(x + width, p.getX(), 1e-6); - assertEquals(y + height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.W); - assertEquals(x, p.getX(), 1e-6); - assertEquals(y + height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorN() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.N); - assertEquals(x + width / 2, p.getX(), 1e-6); - assertEquals(y, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorS() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.S); - assertEquals(x + width / 2, p.getX(), 1e-6); - assertEquals(y + height, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorESE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.ESE); - assertEquals(x + width / 2 + Math.cos(Math.PI / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 + Math.sin(Math.PI / 8) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorSE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SE); - assertEquals(x + width / 2 + Math.cos(Math.PI / 4) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 + Math.sin(Math.PI / 4) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorSSE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SSE); - assertEquals(x + width / 2 + Math.cos(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 + Math.sin(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); - - } - - @Test - public void testGetPointOnEllipseByAnchorSSW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SSW); - assertEquals(x + width / 2 - Math.sin(Math.PI / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 + Math.cos(Math.PI / 8) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorSW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SW); - assertEquals(x + width / 2 - Math.sin(Math.PI / 4) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 + Math.cos(Math.PI / 4) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorWSW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.WSW); - assertEquals(x + width / 2 - Math.sin(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 + Math.cos(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorWNW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.WNW); - assertEquals(x + width / 2 - Math.sin(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 - Math.cos(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorNW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NW); - assertEquals(x + width / 2 - Math.sin(Math.PI / 4) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 - Math.cos(Math.PI / 4) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorNNW() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NNW); - assertEquals(x + width / 2 - Math.sin(Math.PI / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 - Math.cos(Math.PI / 8) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorNNE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NNE); - assertEquals(x + width / 2 + Math.sin(Math.PI / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 - Math.cos(Math.PI / 8) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorNE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NE); - assertEquals(x + width / 2 + Math.sin(Math.PI / 4) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 - Math.cos(Math.PI / 4) * height / 2, p.getY(), 1e-6); - } - - @Test - public void testGetPointOnEllipseByAnchorENE() { - Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.ENE); - assertEquals(x + width / 2 + Math.sin(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); - assertEquals(y + height / 2 - Math.cos(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); - } + CellDesignerEllipseTransformation et = new CellDesignerEllipseTransformation(); + double x = 0; + double y = 10; + double width = 20; + double height = 30; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetPointOnEllipseByAnchorNull() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, null); + assertEquals(x + width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.E); + assertEquals(x + width, p.getX(), 1e-6); + assertEquals(y + height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.W); + assertEquals(x, p.getX(), 1e-6); + assertEquals(y + height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorN() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.N); + assertEquals(x + width / 2, p.getX(), 1e-6); + assertEquals(y, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorS() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.S); + assertEquals(x + width / 2, p.getX(), 1e-6); + assertEquals(y + height, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorESE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.ESE); + assertEquals(x + width / 2 + Math.cos(Math.PI / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 + Math.sin(Math.PI / 8) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorSE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SE); + assertEquals(x + width / 2 + Math.cos(Math.PI / 4) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 + Math.sin(Math.PI / 4) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorSSE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SSE); + assertEquals(x + width / 2 + Math.cos(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 + Math.sin(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); + + } + + @Test + public void testGetPointOnEllipseByAnchorSSW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SSW); + assertEquals(x + width / 2 - Math.sin(Math.PI / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 + Math.cos(Math.PI / 8) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorSW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.SW); + assertEquals(x + width / 2 - Math.sin(Math.PI / 4) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 + Math.cos(Math.PI / 4) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorWSW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.WSW); + assertEquals(x + width / 2 - Math.sin(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 + Math.cos(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorWNW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.WNW); + assertEquals(x + width / 2 - Math.sin(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 - Math.cos(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorNW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NW); + assertEquals(x + width / 2 - Math.sin(Math.PI / 4) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 - Math.cos(Math.PI / 4) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorNNW() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NNW); + assertEquals(x + width / 2 - Math.sin(Math.PI / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 - Math.cos(Math.PI / 8) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorNNE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NNE); + assertEquals(x + width / 2 + Math.sin(Math.PI / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 - Math.cos(Math.PI / 8) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorNE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.NE); + assertEquals(x + width / 2 + Math.sin(Math.PI / 4) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 - Math.cos(Math.PI / 4) * height / 2, p.getY(), 1e-6); + } + + @Test + public void testGetPointOnEllipseByAnchorENE() { + Point2D p = et.getPointOnEllipseByAnchor(x, y, width, height, CellDesignerAnchor.ENE); + assertEquals(x + width / 2 + Math.sin(Math.PI * 3 / 8) * width / 2, p.getX(), 1e-6); + assertEquals(y + height / 2 - Math.cos(Math.PI * 3 / 8) * height / 2, p.getY(), 1e-6); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java index c8a1c21eac..78cdb13c41 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerPointTransformationTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.geometry.helper; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformationTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformationTest.java index a34cb8711a..a1c3b366e7 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformationTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/geometry/helper/CellDesignerRectangleTransformationTest.java @@ -4,33 +4,30 @@ import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.common.Configuration; public class CellDesignerRectangleTransformationTest { - CellDesignerRectangleTransformation transformation = new CellDesignerRectangleTransformation(); + CellDesignerRectangleTransformation transformation = new CellDesignerRectangleTransformation(); - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetPointOnRectangleByAnchor() { - Point2D poitn = transformation.getPointOnRectangleByAnchor(0, 0, 10, 12, null); - assertEquals(0.0, poitn.distance(new Point2D.Double(5, 6)), Configuration.EPSILON); - } + @Test + public void testGetPointOnRectangleByAnchor() { + Point2D poitn = transformation.getPointOnRectangleByAnchor(0, 0, 10, 12, null); + assertEquals(0.0, poitn.distance(new Point2D.Double(5, 6)), Configuration.EPSILON); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java index 4a4c0c5eba..05ce513fec 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/KineticsXmlParserTest.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -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 static org.junit.Assert.*; import java.io.IOException; import java.util.HashMap; @@ -17,9 +14,7 @@ import org.w3c.dom.Node; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerTestFunctions; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.species.Element; @@ -110,18 +105,18 @@ public class KineticsXmlParserTest extends CellDesignerTestFunctions { @Test public void testToXmlDefinition() throws Exception { - Model model = super.getModelForFile("testFiles/reactions/kinetics.xml"); - CellDesignerElementCollection elements = new CellDesignerElementCollection(); - for (Element element : model.getElements()) { - elements.getElementId(element); - } - SbmlKinetics kinetics = model.getReactionByReactionId("re1").getKinetics(); - - KineticsXmlParser parser = new KineticsXmlParser(model); - String xml = parser.toXml(model.getReactionByReactionId("re1").getKinetics(), elements); - - assertNotNull(xml); - assertTrue(xml.indexOf(elements.getElementId(kinetics.getElements().iterator().next())) >= 0); + Model model = super.getModelForFile("testFiles/reactions/kinetics.xml"); + CellDesignerElementCollection elements = new CellDesignerElementCollection(); + for (Element element : model.getElements()) { + elements.getElementId(element); + } + SbmlKinetics kinetics = model.getReactionByReactionId("re1").getKinetics(); + + KineticsXmlParser parser = new KineticsXmlParser(model); + String xml = parser.toXml(model.getReactionByReactionId("re1").getKinetics(), elements); + + assertNotNull(xml); + assertTrue(xml.indexOf(elements.getElementId(kinetics.getElements().iterator().next())) >= 0); } @Test diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java index 01869c993a..37df0180a5 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ModificationReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.FileInputStream; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParserTest.java index 95f92dda20..e6df431bc1 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionCollectionXmlParserTest.java @@ -6,10 +6,9 @@ import static org.junit.Assert.assertNotNull; import java.awt.geom.Line2D; import java.util.List; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.w3c.dom.Node; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerElementCollection; @@ -21,169 +20,169 @@ import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; public class ReactionCollectionXmlParserTest extends CellDesignerTestFunctions { - Logger logger = LogManager.getLogger(ReactionCollectionXmlParserTest.class); - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testParseXmlReactionCollection() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - - CellDesignerElementCollection elements = new CellDesignerElementCollection(); - ReactionCollectionXmlParser parser = new ReactionCollectionXmlParser(model, elements, false); - - String xmlString = readFile("testFiles/reactions/listOfReactions.xml"); - Node node = getNodeFromXmlString(xmlString); - List<Reaction> reactions = parser.parseXmlReactionCollection(node); - - assertEquals(3, reactions.size()); - - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; - } - } - - @Test - public void testReactionCollectionToXmlString() throws Exception { - try { - Model model = getModelFilledWithSpecies(); - - CellDesignerElementCollection elements = new CellDesignerElementCollection(); - ReactionCollectionXmlParser parser = new ReactionCollectionXmlParser(model, elements, false); - - String xmlString = readFile("testFiles/reactions/listOfReactions.xml"); - Node node = getNodeFromXmlString(xmlString); - List<Reaction> reactions = parser.parseXmlReactionCollection(node); - - elements = new CellDesignerElementCollection(); - parser = new ReactionCollectionXmlParser(model, elements, false); - String xmlString2 = parser.reactionCollectionToXmlString(reactions); - assertNotNull(xmlString2); - - elements = new CellDesignerElementCollection(); - parser = new ReactionCollectionXmlParser(model, elements, false); - node = getNodeFromXmlString(xmlString2); - List<Reaction> reactions2 = parser.parseXmlReactionCollection(node); - - assertEquals(reactions.size(), reactions2.size()); - for (int i = 0; i < reactions.size(); i++) { - Reaction a = reactions.get(0); - Reaction b = reactions2.get(0); - - List<Line2D> linesA = a.getLines(); - List<Line2D> linesB = b.getLines(); - for (int j = 0; j < linesA.size(); j++) { - Line2D lineA = linesA.get(j); - Line2D lineB = linesB.get(j); - assertEquals(lineA.getX1(), lineB.getX1(), EPSILON); - assertEquals(lineA.getY1(), lineB.getY1(), EPSILON); - assertEquals(lineA.getX2(), lineB.getX2(), EPSILON); - assertEquals(lineA.getY2(), lineB.getY2(), EPSILON); - } - } - - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw e; - } - } - - private Model getModelFilledWithSpecies() { - Model model = new ModelFullIndexed(null); - - Species sa1 = new GenericProtein("sa1"); - sa1.setX(100.0); - sa1.setY(200.0); - sa1.setWidth(300.0); - sa1.setHeight(400.0); - model.addElement(sa1); - - Species sa2 = new GenericProtein("sa2"); - sa2.setX(1050.0); - sa2.setY(2050.0); - sa2.setWidth(300.0); - sa2.setHeight(450.0); - model.addElement(sa2); - - Species sa3 = new GenericProtein("sa3"); - sa3.setX(600.0); - sa3.setY(250.0); - sa3.setWidth(300.0); - sa3.setHeight(400.0); - model.addElement(sa3); - - Species sa4 = new GenericProtein("sa4"); - sa4.setX(550.0); - sa4.setY(350.0); - sa4.setWidth(300.0); - sa4.setHeight(450.0); - model.addElement(sa4); - - Species sa5 = new GenericProtein("sa5"); - sa5.setX(10.0); - sa5.setY(250.0); - sa5.setWidth(300.0); - sa5.setHeight(450.0); - model.addElement(sa5); - - Species sa6 = new GenericProtein("sa6"); - sa6.setX(10.0); - sa6.setY(250.0); - sa6.setWidth(300.0); - sa6.setHeight(450.0); - model.addElement(sa6); - - Species sa10 = new GenericProtein("sa10"); - sa10.setX(210.0); - sa10.setY(220.0); - sa10.setWidth(320.0); - sa10.setHeight(250.0); - model.addElement(sa10); - - Species sa11 = new GenericProtein("sa11"); - sa11.setX(11.0); - sa11.setY(320.0); - sa11.setWidth(321.0); - sa11.setHeight(150.0); - model.addElement(sa11); - - Species sa12 = new GenericProtein("sa12"); - sa12.setX(12.0); - sa12.setY(20.0); - sa12.setWidth(321.0); - sa12.setHeight(150.0); - model.addElement(sa12); - - Species sa13 = new GenericProtein("sa13"); - sa13.setX(513.0); - sa13.setY(20.0); - sa13.setWidth(321.0); - sa13.setHeight(150.0); - model.addElement(sa13); - - Species sa14 = new GenericProtein("sa14"); - sa14.setX(14.0); - sa14.setY(820.0); - sa14.setWidth(321.0); - sa14.setHeight(150.0); - model.addElement(sa14); - - Species sa15 = new GenericProtein("sa15"); - sa15.setX(815.0); - sa15.setY(620.0); - sa15.setWidth(321.0); - sa15.setHeight(150.0); - model.addElement(sa15); - - return model; - } + Logger logger = LogManager.getLogger(ReactionCollectionXmlParserTest.class); + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testParseXmlReactionCollection() throws Exception { + try { + Model model = getModelFilledWithSpecies(); + + CellDesignerElementCollection elements = new CellDesignerElementCollection(); + ReactionCollectionXmlParser parser = new ReactionCollectionXmlParser(model, elements, false); + + String xmlString = readFile("testFiles/reactions/listOfReactions.xml"); + Node node = getNodeFromXmlString(xmlString); + List<Reaction> reactions = parser.parseXmlReactionCollection(node); + + assertEquals(3, reactions.size()); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw e; + } + } + + @Test + public void testReactionCollectionToXmlString() throws Exception { + try { + Model model = getModelFilledWithSpecies(); + + CellDesignerElementCollection elements = new CellDesignerElementCollection(); + ReactionCollectionXmlParser parser = new ReactionCollectionXmlParser(model, elements, false); + + String xmlString = readFile("testFiles/reactions/listOfReactions.xml"); + Node node = getNodeFromXmlString(xmlString); + List<Reaction> reactions = parser.parseXmlReactionCollection(node); + + elements = new CellDesignerElementCollection(); + parser = new ReactionCollectionXmlParser(model, elements, false); + String xmlString2 = parser.reactionCollectionToXmlString(reactions); + assertNotNull(xmlString2); + + elements = new CellDesignerElementCollection(); + parser = new ReactionCollectionXmlParser(model, elements, false); + node = getNodeFromXmlString(xmlString2); + List<Reaction> reactions2 = parser.parseXmlReactionCollection(node); + + assertEquals(reactions.size(), reactions2.size()); + for (int i = 0; i < reactions.size(); i++) { + Reaction a = reactions.get(0); + Reaction b = reactions2.get(0); + + List<Line2D> linesA = a.getLines(); + List<Line2D> linesB = b.getLines(); + for (int j = 0; j < linesA.size(); j++) { + Line2D lineA = linesA.get(j); + Line2D lineB = linesB.get(j); + assertEquals(lineA.getX1(), lineB.getX1(), EPSILON); + assertEquals(lineA.getY1(), lineB.getY1(), EPSILON); + assertEquals(lineA.getX2(), lineB.getX2(), EPSILON); + assertEquals(lineA.getY2(), lineB.getY2(), EPSILON); + } + } + + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw e; + } + } + + private Model getModelFilledWithSpecies() { + Model model = new ModelFullIndexed(null); + + Species sa1 = new GenericProtein("sa1"); + sa1.setX(100.0); + sa1.setY(200.0); + sa1.setWidth(300.0); + sa1.setHeight(400.0); + model.addElement(sa1); + + Species sa2 = new GenericProtein("sa2"); + sa2.setX(1050.0); + sa2.setY(2050.0); + sa2.setWidth(300.0); + sa2.setHeight(450.0); + model.addElement(sa2); + + Species sa3 = new GenericProtein("sa3"); + sa3.setX(600.0); + sa3.setY(250.0); + sa3.setWidth(300.0); + sa3.setHeight(400.0); + model.addElement(sa3); + + Species sa4 = new GenericProtein("sa4"); + sa4.setX(550.0); + sa4.setY(350.0); + sa4.setWidth(300.0); + sa4.setHeight(450.0); + model.addElement(sa4); + + Species sa5 = new GenericProtein("sa5"); + sa5.setX(10.0); + sa5.setY(250.0); + sa5.setWidth(300.0); + sa5.setHeight(450.0); + model.addElement(sa5); + + Species sa6 = new GenericProtein("sa6"); + sa6.setX(10.0); + sa6.setY(250.0); + sa6.setWidth(300.0); + sa6.setHeight(450.0); + model.addElement(sa6); + + Species sa10 = new GenericProtein("sa10"); + sa10.setX(210.0); + sa10.setY(220.0); + sa10.setWidth(320.0); + sa10.setHeight(250.0); + model.addElement(sa10); + + Species sa11 = new GenericProtein("sa11"); + sa11.setX(11.0); + sa11.setY(320.0); + sa11.setWidth(321.0); + sa11.setHeight(150.0); + model.addElement(sa11); + + Species sa12 = new GenericProtein("sa12"); + sa12.setX(12.0); + sa12.setY(20.0); + sa12.setWidth(321.0); + sa12.setHeight(150.0); + model.addElement(sa12); + + Species sa13 = new GenericProtein("sa13"); + sa13.setX(513.0); + sa13.setY(20.0); + sa13.setWidth(321.0); + sa13.setHeight(150.0); + model.addElement(sa13); + + Species sa14 = new GenericProtein("sa14"); + sa14.setX(14.0); + sa14.setY(820.0); + sa14.setWidth(321.0); + sa14.setHeight(150.0); + model.addElement(sa14); + + Species sa15 = new GenericProtein("sa15"); + sa15.setX(815.0); + sa15.setY(620.0); + sa15.setWidth(321.0); + sa15.setHeight(150.0); + model.addElement(sa15); + + return model; + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java index 08b6429d49..77f8e187e9 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionLineDataTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.junit.*; import org.mockito.Mockito; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserExceptionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserExceptionTest.java index ac6b375532..725fc1166e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserExceptionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserExceptionTest.java @@ -2,41 +2,38 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.reaction.Reaction; public class ReactionParserExceptionTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testConstructor() { - Reaction reaction = new Reaction(); - reaction.setIdReaction("1"); - ReactionParserException exception = new ReactionParserException("text", reaction); - assertEquals("1", exception.getReactionId()); - } - - @Test - public void testConstructor2() { - Reaction reaction = new Reaction(); - reaction.setIdReaction("1"); - ReactionParserException exception = new ReactionParserException("text", reaction, new Exception()); - assertEquals("1", exception.getReactionId()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConstructor() { + Reaction reaction = new Reaction(); + reaction.setIdReaction("1"); + ReactionParserException exception = new ReactionParserException("text", reaction); + assertEquals("1", exception.getReactionId()); + } + + @Test + public void testConstructor2() { + Reaction reaction = new Reaction(); + reaction.setIdReaction("1"); + ReactionParserException exception = new ReactionParserException("text", reaction, new Exception()); + assertEquals("1", exception.getReactionId()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java index 893fccc418..a9d175d32f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/ReactionParserTests.java @@ -2,10 +2,11 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.util.*; +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -25,9 +26,9 @@ import lcsb.mapviewer.model.map.species.*; public class ReactionParserTests extends CellDesignerTestFunctions { - private Logger logger = LogManager.getLogger(ReactionParserTests.class.getName()); ReactionXmlParser parser; CellDesignerElementCollection elements; + private Logger logger = LogManager.getLogger(ReactionParserTests.class.getName()); @Before public void setUp() throws Exception { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassExceptionTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassExceptionTest.java index 88d28638b1..8e037cae3b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassExceptionTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/reaction/UnknownModifierClassExceptionTest.java @@ -1,32 +1,29 @@ package lcsb.mapviewer.converter.model.celldesigner.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class UnknownModifierClassExceptionTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - String modificationType = "str"; - UnknownModifierClassException exception = new UnknownModifierClassException(null, null, null); - exception.setModificationType(modificationType); - assertEquals(modificationType, exception.getModificationType()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + String modificationType = "str"; + UnknownModifierClassException exception = new UnknownModifierClassException(null, null, null); + exception.setModificationType(modificationType); + assertEquals(modificationType, exception.getModificationType()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java index 4d9bc17924..5b23ce5c84 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/AntisenseRnaXmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.StringReader; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java index 9385be4dfb..336f829172 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ComplexParserTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.species; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java index 0de7742276..46bdaefefd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/InternalModelSpeciesDataTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java index a3b2f730ff..e73008f4bb 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ModificationResidueXmlParserTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.awt.geom.Point2D; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java index 2a6eba764b..43b397c4af 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinMappingTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.lang.reflect.Field; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java index b85fd90d02..c3ce2f8215 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/ProteinXmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.StringReader; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java index dfe1e00006..b3f2dd07b8 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesMappingTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.lang.reflect.Field; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java index f6dbdcfc63..1919807087 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/species/SpeciesSbmlParserTest.java @@ -27,11 +27,7 @@ import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; import lcsb.mapviewer.model.map.species.*; public class SpeciesSbmlParserTest extends CellDesignerTestFunctions { - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(SpeciesSbmlParserTest.class.getName()); - SpeciesSbmlParser parser; - String testGeneFile = "testFiles/xmlNodeTestExamples/sbml_gene.xml"; String testDegradedFile = "testFiles/xmlNodeTestExamples/sbml_degraded.xml"; String testDrugFile = "testFiles/xmlNodeTestExamples/sbml_drug.xml"; @@ -41,10 +37,10 @@ public class SpeciesSbmlParserTest extends CellDesignerTestFunctions { String testRnaFile = "testFiles/xmlNodeTestExamples/sbml_rna.xml"; String testSimpleMoleculeFile = "testFiles/xmlNodeTestExamples/sbml_simple_molecule.xml"; String testUnknownFile = "testFiles/xmlNodeTestExamples/sbml_unknown.xml"; - CellDesignerElementCollection elements; - int idCounter = 0; + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(SpeciesSbmlParserTest.class.getName()); @Before public void setUp() throws Exception { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AllStructureTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AllStructureTests.java index e9194757a1..2dc8cbe13f 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AllStructureTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/AllStructureTests.java @@ -8,30 +8,30 @@ import lcsb.mapviewer.converter.model.celldesigner.structure.fields.AllFieldsTes @RunWith(Suite.class) @SuiteClasses({ AllFieldsTests.class, - AntisenseRnaTest.class, - CellDesignerChemicalTest.class, - CompartmentTest.class, - ComplexSpeciesTest.class, - ConnectSchemeTest.class, - DegradedTest.class, - DrugTest.class, - ElementTest.class, - GenericProteinTest.class, - GeneTest.class, - IonChannelProteinTest.class, - IonTest.class, - LinePropertiesTest.class, - ModificationResidueTest.class, - PhenotypeTest.class, - ProteinTest.class, - ReceptorProteinTest.class, - RnaTest.class, - SimpleMoleculeTest.class, - SpeciesStateTest.class, - SpeciesTest.class, - TruncatedProteinTest.class, - UnknownTest.class, - ViewTest.class, + AntisenseRnaTest.class, + CellDesignerChemicalTest.class, + CompartmentTest.class, + ComplexSpeciesTest.class, + ConnectSchemeTest.class, + DegradedTest.class, + DrugTest.class, + ElementTest.class, + GenericProteinTest.class, + GeneTest.class, + IonChannelProteinTest.class, + IonTest.class, + LinePropertiesTest.class, + ModificationResidueTest.class, + PhenotypeTest.class, + ProteinTest.class, + ReceptorProteinTest.class, + RnaTest.class, + SimpleMoleculeTest.class, + SpeciesStateTest.class, + SpeciesTest.class, + TruncatedProteinTest.class, + UnknownTest.class, + ViewTest.class, }) public class AllStructureTests { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemicalTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemicalTest.java index aef53547d4..2aacce4623 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemicalTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/CellDesignerChemicalTest.java @@ -2,39 +2,36 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CellDesignerChemicalTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - String smiles = "smiles"; - String inChI = "inchi"; - String inChIKey = "key"; - - CellDesignerChemical<?> chemical = new CellDesignerIon(); - chemical.setSmiles(smiles); - chemical.setInChI(inChI); - chemical.setInChIKey(inChIKey); - - assertEquals(smiles, chemical.getSmiles()); - assertEquals(inChI, chemical.getInChI()); - assertEquals(inChIKey, chemical.getInChIKey()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + String smiles = "smiles"; + String inChI = "inchi"; + String inChIKey = "key"; + + CellDesignerChemical<?> chemical = new CellDesignerIon(); + chemical.setSmiles(smiles); + chemical.setInChI(inChI); + chemical.setInChIKey(inChIKey); + + assertEquals(smiles, chemical.getSmiles()); + assertEquals(inChI, chemical.getInChI()); + assertEquals(inChIKey, chemical.getInChIKey()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java index 2add8eea61..bd7362244a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ComplexSpeciesTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.HashSet; import java.util.Set; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ConnectSchemeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ConnectSchemeTest.java index 5b5ba309a6..382ecbd0a1 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ConnectSchemeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ConnectSchemeTest.java @@ -5,41 +5,38 @@ import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.ConnectScheme; public class ConnectSchemeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - String connectIndex = "1"; - Integer integerConnectIndex = 1; - String connectPolicy = "2"; - Map<String, String> directions = new HashMap<>(); - ConnectScheme cs = new ConnectScheme(); - cs.setConnectPolicy(connectPolicy); - cs.setConnectIndex(connectIndex); - cs.setLineDirections(directions); - - assertEquals(integerConnectIndex, cs.getConnectIndex()); - assertEquals(connectPolicy, cs.getConnectPolicy()); - assertEquals(directions, cs.getLineDirections()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + String connectIndex = "1"; + Integer integerConnectIndex = 1; + String connectPolicy = "2"; + Map<String, String> directions = new HashMap<>(); + ConnectScheme cs = new ConnectScheme(); + cs.setConnectPolicy(connectPolicy); + cs.setConnectIndex(connectIndex); + cs.setLineDirections(directions); + + assertEquals(integerConnectIndex, cs.getConnectIndex()); + assertEquals(connectPolicy, cs.getConnectPolicy()); + assertEquals(directions, cs.getLineDirections()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java index 4c3af94067..dbb8476084 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DegradedTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java index 1a2f20201d..12c297184e 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/DrugTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java index 266c2bdf3a..54d6368195 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GeneTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java index 73e83739e7..56c53a16ea 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/GenericProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java index 9a9e856d67..b091b75a18 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonChannelProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java index ec56e6bf4c..a9ffc54b2b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/IonTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/LinePropertiesTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/LinePropertiesTest.java index ad1c9dcc49..fd2a97d2b7 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/LinePropertiesTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/LinePropertiesTest.java @@ -1,34 +1,31 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.LineProperties; public class LinePropertiesTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - String type = "str_t"; - LineProperties lp = new LineProperties(); - lp.setType(type); - assertEquals(type,lp.getType()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + String type = "str_t"; + LineProperties lp = new LineProperties(); + lp.setType(type); + assertEquals(type, lp.getType()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java index 298b1523ad..cf4e64a306 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/PhenotypeTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java index f4736e225a..85e800dccf 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ProteinTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java index 17d0cb16d5..2c7a993afb 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ReceptorProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java index 35c0176da9..e58b9ba42a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SimpleMoleculeTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java index 6f49cb2230..b8c7717001 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/SpeciesStateTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; import java.util.ArrayList; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java index ed7f2d903c..3ba57e8f19 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/TruncatedProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java index 0f898b7e36..f5eb8f021a 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/UnknownTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ViewTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ViewTest.java index ae6f2152a3..d3279e5b77 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ViewTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/ViewTest.java @@ -1,36 +1,33 @@ package lcsb.mapviewer.converter.model.celldesigner.structure; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.converter.model.celldesigner.structure.fields.View; public class ViewTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetters() { - Point2D innerPosition = new Point2D.Double(); - View view = new View(); - view.setInnerPosition(innerPosition); - assertEquals(innerPosition, view.getInnerPosition()); - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetters() { + Point2D innerPosition = new Point2D.Double(); + View view = new View(); + view.setInnerPosition(innerPosition); + assertEquals(innerPosition, view.getInnerPosition()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidueTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidueTest.java index 41d152d0db..da30520b11 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidueTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/structure/fields/CellDesignerModificationResidueTest.java @@ -2,29 +2,26 @@ package lcsb.mapviewer.converter.model.celldesigner.structure.fields; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class CellDesignerModificationResidueTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void test() { - CellDesignerModificationResidue region = new CellDesignerModificationResidue(); - assertNotNull(region.toString()); - } + @Test + public void test() { + CellDesignerModificationResidue region = new CellDesignerModificationResidue(); + assertNotNull(region.toString()); + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/AllTypesTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/AllTypesTests.java index d76440b14f..6d4d31cff0 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/AllTypesTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/AllTypesTests.java @@ -6,9 +6,9 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ModifierTypeTest.class, - ModifierTypeUtilsTest.class, - OperatorTypeTest.class, - OperatorTypeUtilsTest.class, + ModifierTypeUtilsTest.class, + OperatorTypeTest.class, + OperatorTypeUtilsTest.class, }) public class AllTypesTests { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeTest.java index b10acf49c6..2fd0635f90 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeTest.java @@ -2,30 +2,27 @@ package lcsb.mapviewer.converter.model.celldesigner.types; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ModifierTypeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void test() { - for (ModifierType type : ModifierType.values()) { - assertNotNull(ModifierType.valueOf(type.toString())); - } - } + @Test + public void test() { + for (ModifierType type : ModifierType.values()) { + assertNotNull(ModifierType.valueOf(type.toString())); + } + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java index 7a87b70661..b23ea7333b 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/ModifierTypeUtilsTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.awt.geom.Point2D; import java.lang.reflect.Field; diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeTest.java index 51c5880ba5..2da98c2cef 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeTest.java @@ -1,31 +1,28 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class OperatorTypeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void test() { - for (OperatorType type : OperatorType.values()) { - assertNotNull(OperatorType.valueOf(type.toString())); - } - } + @Test + public void test() { + for (OperatorType type : OperatorType.values()) { + assertNotNull(OperatorType.valueOf(type.toString())); + } + } } diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java index fefc4b51cb..b4f84190bd 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/types/OperatorTypeUtilsTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.celldesigner.types; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNull; import java.lang.reflect.Field; diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlConverter.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlConverter.java index 0cfeba5677..95ed20c123 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlConverter.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlConverter.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter.model.sbgnml; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; +import java.io.*; import javax.xml.bind.JAXBException; @@ -14,10 +12,7 @@ import org.sbgn.bindings.Sbgn; import lcsb.mapviewer.common.MimeType; import lcsb.mapviewer.common.MinervaLoggerAppender; -import lcsb.mapviewer.converter.Converter; -import lcsb.mapviewer.converter.ConverterException; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.InvalidInputDataExecption; +import lcsb.mapviewer.converter.*; import lcsb.mapviewer.model.map.model.Model; public class SbgnmlXmlConverter extends Converter { 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 3e5e337ef5..c3cc9949f4 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 @@ -1,30 +1,17 @@ package lcsb.mapviewer.converter.model.sbgnml; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.stream.Collectors; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.sbgn.ArcClazz; -import org.sbgn.GlyphClazz; -import org.sbgn.Language; -import org.sbgn.bindings.Arc; -import org.sbgn.bindings.Arc.End; -import org.sbgn.bindings.Arc.Next; -import org.sbgn.bindings.Arc.Start; -import org.sbgn.bindings.Bbox; -import org.sbgn.bindings.Glyph; -import org.sbgn.bindings.Label; +import org.sbgn.*; +import org.sbgn.bindings.*; import org.sbgn.bindings.Map; -import org.sbgn.bindings.Port; -import org.sbgn.bindings.Sbgn; +import org.sbgn.bindings.Arc.*; import lcsb.mapviewer.common.comparator.DoubleComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -33,45 +20,10 @@ import lcsb.mapviewer.model.graphics.ArrowType; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.modifier.Trigger; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -import lcsb.mapviewer.model.map.reaction.DissociationOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.OrOperator; -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.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.TruncatedProtein; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.modifier.*; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -84,66 +36,55 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class SbgnmlXmlExporter { - /** - * Helps in providing human readable identifiers of elements for logging. - */ - private ElementUtils eu = new ElementUtils(); - - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(SbgnmlXmlExporter.class.getName()); - - /** - * Counter of the arcs parsed so far, used in generating arc's id. - */ - private int arcCounter; - - /** - * Set of all the operators parsed so far, used in generating operator's id. - */ - private Set<NodeOperator> parsedOperators; - - /** - * Map of operator IDs used when parsing arcs targeting an operator. - */ - private java.util.Map<NodeOperator, String> operatorIds; - - /** - * Map of all glyphs and ports generated so far with id as key. - */ - private java.util.Map<String, Object> sourceTargetMap; - /** * Side margin for units of information. */ private static final double UNIT_OF_INFORMATION_MARGIN = 10.0; - /** * Height of generated units of information. */ private static final double UNIT_OF_INFORMATION_HEIGHT = 12.0; - /** * Height and width of generated operators. */ private static final double OPERATOR_SIZE = 40.0; - /** * Distance between operator circle and port point. */ private static final double OPERATOR_PORT_DISTANCE = 20.0; - /** * Distance between process glyph and port point. */ private static final double PROCESS_PORT_DISTANCE = 10.0; - /** * Length of random alphabetic string added in the begining of ID, if it is a * number. SBGN-ML doesn't accept numbers as ID. */ private static final int ID_RANDOM_STRING_LENGTH = 5; + /** + * Helps in providing human readable identifiers of elements for logging. + */ + private ElementUtils eu = new ElementUtils(); + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(SbgnmlXmlExporter.class.getName()); + /** + * Counter of the arcs parsed so far, used in generating arc's id. + */ + private int arcCounter; + /** + * Set of all the operators parsed so far, used in generating operator's id. + */ + private Set<NodeOperator> parsedOperators; + /** + * Map of operator IDs used when parsing arcs targeting an operator. + */ + private java.util.Map<NodeOperator, String> operatorIds; + /** + * Map of all glyphs and ports generated so far with id as key. + */ + private java.util.Map<String, Object> sourceTargetMap; /** * Transforms model into SBGN-ML xml. 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 c2d769e636..59866a2253 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 @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbgnml; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.File; @@ -9,18 +9,9 @@ import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.sbgn.ArcClazz; -import org.sbgn.GlyphClazz; -import org.sbgn.SbgnUtil; -import org.sbgn.bindings.Arc; -import org.sbgn.bindings.Arc.End; -import org.sbgn.bindings.Arc.Next; -import org.sbgn.bindings.Arc.Start; -import org.sbgn.bindings.Bbox; -import org.sbgn.bindings.Glyph; -import org.sbgn.bindings.Map; -import org.sbgn.bindings.Port; -import org.sbgn.bindings.Sbgn; +import org.sbgn.*; +import org.sbgn.bindings.*; +import org.sbgn.bindings.Arc.*; import lcsb.mapviewer.common.comparator.DoubleComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -33,48 +24,16 @@ import lcsb.mapviewer.converter.model.celldesigner.geometry.ReactionCellDesigner import lcsb.mapviewer.converter.model.celldesigner.types.ModifierType; import lcsb.mapviewer.converter.model.celldesigner.types.ModifierTypeUtils; import lcsb.mapviewer.converter.model.sbgnml.structures.Process; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.SquareCompartment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.modifier.Trigger; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.OrOperator; -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.SplitOperator; -import lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.modifier.*; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; /** * This class is a parser for SBGN-ML files. @@ -84,44 +43,37 @@ import lcsb.mapviewer.model.map.species.field.Residue; */ public class SbgnmlXmlParser { + /** + * Default margin for container name. + */ + private static final double CONTAINER_NAME_MARGIN = 5.0; + /** + * Part of height of the line used to cross degraded circle that goes behind + * this circle. + */ + private static final int CROSS_LINE_EXTENDED_LENGTH = 7; + /** + * Default color for parsed compartments. + */ + private static final Color COMPARTMENT_COLOR = new Color(0.5f, 0.5f, 1.0f); + private final PointTransformation pt = new PointTransformation(); /** * Default class logger. */ private Logger logger = LogManager.getLogger(SbgnmlXmlParser.class.getName()); - /** * List of all processes to be parsed. */ private List<Process> processes = new ArrayList<Process>(); - /** * List of all logic operator glyphs parsed so far. */ private List<Glyph> logicOperators = new ArrayList<Glyph>(); - /** * List of all logic arcs parsed so far. */ private List<Arc> logicArcs = new ArrayList<Arc>(); - /** - * Default margin for container name. - */ - private static final double CONTAINER_NAME_MARGIN = 5.0; - - /** - * Part of height of the line used to cross degraded circle that goes behind - * this circle. - */ - private static final int CROSS_LINE_EXTENDED_LENGTH = 7; - - /** - * Default color for parsed compartments. - */ - private static final Color COMPARTMENT_COLOR = new Color(0.5f, 0.5f, 1.0f); - - private final PointTransformation pt = new PointTransformation(); - /** * Method used to create a model from SBGN-ML file. * diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/package-info.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/package-info.java index a2833a7d9d..59cfb45c53 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/package-info.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/package-info.java @@ -1,4 +1,5 @@ /** - * lcsb.mapviewer.converter.model.sbgnml is the main package of SBGN-ML converter. + * lcsb.mapviewer.converter.model.sbgnml is the main package of SBGN-ML + * converter. */ package lcsb.mapviewer.converter.model.sbgnml; \ No newline at end of file diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/Process.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/Process.java index 1a12c70805..4c19a4ec03 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/Process.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/Process.java @@ -4,9 +4,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import org.sbgn.bindings.Arc; -import org.sbgn.bindings.Glyph; -import org.sbgn.bindings.Port; +import org.sbgn.bindings.*; import lcsb.mapviewer.common.comparator.DoubleComparator; @@ -18,220 +16,226 @@ import lcsb.mapviewer.common.comparator.DoubleComparator; */ public class Process { - /** - * Central point of a reaction represented by a glyph. - */ - private Glyph centralPoint; - - /** - * Product arcs. - */ - private List<Arc> productArcs = new ArrayList<Arc>(); - - /** - * Reagent arcs. - */ - private List<Arc> reagentArcs = new ArrayList<Arc>(); - - /** - * Modifier arcs. - */ - private List<Arc> modifierArcs = new ArrayList<Arc>(); - - /** - * Port for all reagents. - */ - private Port reagentsPort; - - /** - * Port for all products. - */ - private Port productsPort; - - /** - * Is the process reversible. - */ - private boolean reversible; - - /** - * Default constructor. - * - * @param centralPoint - * central point of the process - */ - public Process(Glyph centralPoint) { - this.reversible = false; - this.productsPort = null; - this.reagentsPort = null; - this.centralPoint = centralPoint; - } - - /** - * Adds a product arc to the process. - * - * @param a - * the arc to be added - */ - public void addProductArc(Arc a) { - if (this.getCentralPoint().getPort().size() == 2) { - double dx = a.getEnd().getX() - a.getStart().getX(); - double dy = a.getEnd().getY() - a.getStart().getY(); - double centralDx = this.getCentralPoint().getPort().get(0).getX() - this.getCentralPoint().getPort().get(1).getX(); - double centralDy = this.getCentralPoint().getPort().get(0).getY() - this.getCentralPoint().getPort().get(1).getY(); - DoubleComparator comparator = new DoubleComparator(); - if (comparator.compare(dy / dx, centralDy / centralDx) == 0) { - productArcs.add(0, a); - } else { - productArcs.add(a); - } - } else { - productArcs.add(a); - } - } - - /** - * Adds a reagent arc to the process. - * - * @param a - * the arc to be added - */ - public void addReagentArc(Arc a) { - if (this.getCentralPoint().getPort().size() == 2) { - double dx = a.getEnd().getX() - a.getStart().getX(); - double dy = a.getEnd().getY() - a.getStart().getY(); - double centralDx = this.getCentralPoint().getPort().get(0).getX() - this.getCentralPoint().getPort().get(1).getX(); - double centralDy = this.getCentralPoint().getPort().get(0).getY() - this.getCentralPoint().getPort().get(1).getY(); - DoubleComparator comparator = new DoubleComparator(); - if (comparator.compare(dy / dx, centralDy / centralDx) == 0) { - reagentArcs.add(0, a); - } else { - reagentArcs.add(a); - } - } else { - reagentArcs.add(a); - } - } - - /** - * Adds a influence arc to the process. - * - * @param a - * the arc to be added - */ - public void addInfluenceArc(Arc a) { - modifierArcs.add(a); - } - - /** - * @return the reagentArcs - * @see #reagentArcs - */ - public List<Arc> getReagentArcs() { - return reagentArcs; - } - - /** - * @return the productArcs - * @see #productArcs - */ - public List<Arc> getProductArcs() { - return productArcs; - } - - /** - * @return the centralPoint - * @see #centralPoint - */ - public Glyph getCentralPoint() { - return centralPoint; - } - - /** - * @param centralPoint - * the centralPoint to set - * @see #centralPoint - */ - public void setCentralPoint(Glyph centralPoint) { - this.centralPoint = centralPoint; - } - - /** - * @return the modifierArcs - * @see #modifierArcs - */ - public List<Arc> getModifierArcs() { - return modifierArcs; - } - - /** - * @return the reagentsPort - * @see #reagentsPort - */ - public Port getReagentsPort() { - return reagentsPort; - } - - /** - * @param reagentsPort - * the reagentsPort to set - * @see #reagentsPort - */ - public void setReagentsPort(Port reagentsPort) { - this.reagentsPort = reagentsPort; - } - - /** - * @return the productsPort - * @see #productsPort - */ - public Port getProductsPort() { - return productsPort; - } - - /** - * @param productsPort - * the productsPort to set - * @see #productsPort - */ - public void setProductsPort(Port productsPort) { - this.productsPort = productsPort; - } - - /** - * @return the reversible - * @see #reversible - */ - public boolean isReversible() { - return reversible; - } - - /** - * @param reversible - * the reversible to set - * @see #reversible - */ - public void setReversible(boolean reversible) { - this.reversible = reversible; - } - - /** - * Method used to retrieve product arcs in reversible process. - * - * @return list of product arcs - */ - public List<Arc> getRevProductArcs() { - List<Arc> result = productArcs.stream().filter(a -> a.getSource().equals(productsPort)).collect(Collectors.toList()); - return result; - } - - /** - * Method used to retrieve reagent arcs in reversible process. - * - * @return list of reagent arcs - */ - public List<Arc> getRevReagentArcs() { - List<Arc> result = productArcs.stream().filter(a -> a.getSource().equals(reagentsPort)).collect(Collectors.toList()); - return result; - } + /** + * Central point of a reaction represented by a glyph. + */ + private Glyph centralPoint; + + /** + * Product arcs. + */ + private List<Arc> productArcs = new ArrayList<Arc>(); + + /** + * Reagent arcs. + */ + private List<Arc> reagentArcs = new ArrayList<Arc>(); + + /** + * Modifier arcs. + */ + private List<Arc> modifierArcs = new ArrayList<Arc>(); + + /** + * Port for all reagents. + */ + private Port reagentsPort; + + /** + * Port for all products. + */ + private Port productsPort; + + /** + * Is the process reversible. + */ + private boolean reversible; + + /** + * Default constructor. + * + * @param centralPoint + * central point of the process + */ + public Process(Glyph centralPoint) { + this.reversible = false; + this.productsPort = null; + this.reagentsPort = null; + this.centralPoint = centralPoint; + } + + /** + * Adds a product arc to the process. + * + * @param a + * the arc to be added + */ + public void addProductArc(Arc a) { + if (this.getCentralPoint().getPort().size() == 2) { + double dx = a.getEnd().getX() - a.getStart().getX(); + double dy = a.getEnd().getY() - a.getStart().getY(); + double centralDx = this.getCentralPoint().getPort().get(0).getX() + - this.getCentralPoint().getPort().get(1).getX(); + double centralDy = this.getCentralPoint().getPort().get(0).getY() + - this.getCentralPoint().getPort().get(1).getY(); + DoubleComparator comparator = new DoubleComparator(); + if (comparator.compare(dy / dx, centralDy / centralDx) == 0) { + productArcs.add(0, a); + } else { + productArcs.add(a); + } + } else { + productArcs.add(a); + } + } + + /** + * Adds a reagent arc to the process. + * + * @param a + * the arc to be added + */ + public void addReagentArc(Arc a) { + if (this.getCentralPoint().getPort().size() == 2) { + double dx = a.getEnd().getX() - a.getStart().getX(); + double dy = a.getEnd().getY() - a.getStart().getY(); + double centralDx = this.getCentralPoint().getPort().get(0).getX() + - this.getCentralPoint().getPort().get(1).getX(); + double centralDy = this.getCentralPoint().getPort().get(0).getY() + - this.getCentralPoint().getPort().get(1).getY(); + DoubleComparator comparator = new DoubleComparator(); + if (comparator.compare(dy / dx, centralDy / centralDx) == 0) { + reagentArcs.add(0, a); + } else { + reagentArcs.add(a); + } + } else { + reagentArcs.add(a); + } + } + + /** + * Adds a influence arc to the process. + * + * @param a + * the arc to be added + */ + public void addInfluenceArc(Arc a) { + modifierArcs.add(a); + } + + /** + * @return the reagentArcs + * @see #reagentArcs + */ + public List<Arc> getReagentArcs() { + return reagentArcs; + } + + /** + * @return the productArcs + * @see #productArcs + */ + public List<Arc> getProductArcs() { + return productArcs; + } + + /** + * @return the centralPoint + * @see #centralPoint + */ + public Glyph getCentralPoint() { + return centralPoint; + } + + /** + * @param centralPoint + * the centralPoint to set + * @see #centralPoint + */ + public void setCentralPoint(Glyph centralPoint) { + this.centralPoint = centralPoint; + } + + /** + * @return the modifierArcs + * @see #modifierArcs + */ + public List<Arc> getModifierArcs() { + return modifierArcs; + } + + /** + * @return the reagentsPort + * @see #reagentsPort + */ + public Port getReagentsPort() { + return reagentsPort; + } + + /** + * @param reagentsPort + * the reagentsPort to set + * @see #reagentsPort + */ + public void setReagentsPort(Port reagentsPort) { + this.reagentsPort = reagentsPort; + } + + /** + * @return the productsPort + * @see #productsPort + */ + public Port getProductsPort() { + return productsPort; + } + + /** + * @param productsPort + * the productsPort to set + * @see #productsPort + */ + public void setProductsPort(Port productsPort) { + this.productsPort = productsPort; + } + + /** + * @return the reversible + * @see #reversible + */ + public boolean isReversible() { + return reversible; + } + + /** + * @param reversible + * the reversible to set + * @see #reversible + */ + public void setReversible(boolean reversible) { + this.reversible = reversible; + } + + /** + * Method used to retrieve product arcs in reversible process. + * + * @return list of product arcs + */ + public List<Arc> getRevProductArcs() { + List<Arc> result = productArcs.stream().filter(a -> a.getSource().equals(productsPort)) + .collect(Collectors.toList()); + return result; + } + + /** + * Method used to retrieve reagent arcs in reversible process. + * + * @return list of reagent arcs + */ + public List<Arc> getRevReagentArcs() { + List<Arc> result = productArcs.stream().filter(a -> a.getSource().equals(reagentsPort)) + .collect(Collectors.toList()); + return result; + } } diff --git a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/package-info.java b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/package-info.java index b463f7a41a..1e3ff62dee 100644 --- a/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/package-info.java +++ b/converter-SBGNML/src/main/java/lcsb/mapviewer/converter/model/sbgnml/structures/package-info.java @@ -1,4 +1,5 @@ /** - * lcsb.mapviewer.converter.model.sbgnml.structures is a group of additional structures used in the process of parsing SBGN-ML file. + * lcsb.mapviewer.converter.model.sbgnml.structures is a group of additional + * structures used in the process of parsing SBGN-ML file. */ package lcsb.mapviewer.converter.model.sbgnml.structures; \ No newline at end of file diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/AllSbgnmlTests.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/AllSbgnmlTests.java index 1c40a8d7eb..aba2c53f65 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/AllSbgnmlTests.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/AllSbgnmlTests.java @@ -6,11 +6,11 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ CellDesigner2SbgnmlConversionTest.class, - CellDesignerToSbgnTest.class, - DbSerializationTest.class, - SbgnmlXmlExporterTest.class, - SbgnmlXmlParserTest.class, - SbgnmlXmlParserTest2.class, + CellDesignerToSbgnTest.class, + DbSerializationTest.class, + SbgnmlXmlExporterTest.class, + SbgnmlXmlParserTest.class, + SbgnmlXmlParserTest2.class, }) public class AllSbgnmlTests { diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java index 57144608ea..54da7290fb 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/CellDesignerToSbgnTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbgnml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/DbSerializationTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/DbSerializationTest.java index ba4c23cd12..7f6000f2a5 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/DbSerializationTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/DbSerializationTest.java @@ -6,18 +6,14 @@ import java.io.File; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelComparator; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.persist.DbUtils; import lcsb.mapviewer.persist.dao.map.ModelDao; diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java index c0d037d571..0e3dd16e2c 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlTestFunctions.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbgnml; -import java.awt.Desktop; +import java.awt.*; import java.io.File; import java.nio.file.Files; diff --git a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java index ea82c2e93f..6df4e8cd5a 100644 --- a/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java +++ b/converter-SBGNML/src/test/java/lcsb/mapviewer/converter/model/sbgnml/SbgnmlXmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbgnml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.*; import java.nio.file.*; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/AbstractImageGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/AbstractImageGenerator.java index 0bfed2214f..ad1836ccba 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/AbstractImageGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/AbstractImageGenerator.java @@ -1,15 +1,12 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; +import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.OutputStream; -import java.util.ArrayList; +import java.util.*; import java.util.List; -import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -18,25 +15,17 @@ import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.commands.SemanticZoomLevelMatcher; import lcsb.mapviewer.common.MimeType; import lcsb.mapviewer.converter.graphics.bioEntity.BioEntityConverterImpl; -import lcsb.mapviewer.converter.graphics.layer.LayerLineConverter; -import lcsb.mapviewer.converter.graphics.layer.LayerOvalConverter; -import lcsb.mapviewer.converter.graphics.layer.LayerRectConverter; -import lcsb.mapviewer.converter.graphics.layer.LayerTextConverter; +import lcsb.mapviewer.converter.graphics.layer.*; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.Drawable; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.PathwayCompartment; import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.layout.graphics.*; import lcsb.mapviewer.model.map.model.Model; 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.model.map.species.*; /** * This class is responsible for creation of the image from the model. It's an @@ -77,1042 +66,1032 @@ import lcsb.mapviewer.model.map.species.Species; */ public abstract class AbstractImageGenerator { - /** - * Class that allows to check if element is visible (or transparent) when - * drawing. It's used to filter out invisible elements when drawing - * semantic/hierarchy view. - */ - private SemanticZoomLevelMatcher zoomLevelMatcher = new SemanticZoomLevelMatcher(); - /** * Model is drawn as a partial image (x,y,width,height parameters of * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params * Params} class. This partial image sometimes contains some object that doesn't * intersect with this border (usually text descriptions). This margin defines * how far extend drawing. - * + * * TODO maybe more efficient (and safe) solution would be to include text * Description as parts of the object border */ private static final int SINGLE_FRAME_MARGIN = 100; - + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(AbstractImageGenerator.class); + /** + * Class that allows to check if element is visible (or transparent) when + * drawing. It's used to filter out invisible elements when drawing + * semantic/hierarchy view. + */ + private SemanticZoomLevelMatcher zoomLevelMatcher = new SemanticZoomLevelMatcher(); /** * On which level in hierarchical view we should visualize map. */ private int level = Integer.MAX_VALUE; - /** * Zoom factor of the drawing. */ private double scale = 1; - /** * This is a frame border from which we take all elements to draw. */ private Rectangle2D.Double border = null; - /** * Object that helps to convert {@link ColorSchema} values into colors. */ private ColorExtractor colorExtractor = null; + /** + * Graphics object which allows to draw objects. + */ + private Graphics2D graphics; + /** + * SBGN display format. + */ + private boolean sbgnFormat = false; + /** + * List of params used for drawing. + */ + private Params params; + /** + * Flag indicating {@link #draw()} method was executed. + */ + private boolean drawn = false; /** - * This class contains a list of params that are used for drawing. - * - * @author Piotr Gawron + * Default constructor. Create an image that is described by params. For more + * information see + * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params + * params}. + * + * @param params + * list of all params to create appropriate image + * @throws DrawingException + * thrown when there was a problem with drawing a map + * + */ + protected AbstractImageGenerator(final Params params) { + this.params = params; + } + + /** + * Don't allow to create default public constructors with empty list of + * parameters. + */ + protected AbstractImageGenerator() { + super(); + } + + /** + * This method creates a graphics object for different implementations of canvas + * with fixed width and height. + * + * @param width + * width of the canvas (graphics2d) to be created + * @param height + * height of the canvas (graphics2d) to be created + */ + protected abstract void createImageObject(double width, double height); + + /** + * Draw a model into {@link #getGraphics()} object. * + * @throws DrawingException + * thrown when there is a problem with drawing */ - public static class Params { + protected void draw() throws DrawingException { + if (isDrawn()) { + logger.warn("Model was already drawn. Skipping"); + return; + } + this.level = params.getLevel(); + this.scale = params.getScale(); - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(Params.class); + colorExtractor = new ColorExtractor(params.getMinColor(), params.getMaxColor(), params.getSimpleColor()); - /** - * Scale at which we want to visualize the map. The default value is 1.0 (no - * magnification). - */ - private double scale = 1; + // set border frame extended by a margin + border = new Rectangle2D.Double(params.getX() - SINGLE_FRAME_MARGIN, params.getY() - SINGLE_FRAME_MARGIN, + params.getWidth() * scale + 2 * SINGLE_FRAME_MARGIN, params.getHeight() * scale + 2 * SINGLE_FRAME_MARGIN); + createImageObject(params.getWidth(), params.getHeight()); - /** - * x coordinate from which we start to draw a map. This is absolute value on the - * map (scale doesn't influence it). - */ + // turn on anti-aliasing + graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - private double x = 0; + graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - /** - * y coordinate from which we start to draw a map. This is absolute value on the - * map (scale doesn't influence it). - */ - private double y = 0; + graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - /** - * width of the generated image. It's an absolute value in pixels, therefore - * when scale is set to value different than 1.0 the width on the map will also - * be modified to fit into width pixels. - */ - private Double width = null; + // set scale + graphics.scale(1 / scale, 1 / scale); - /** - * height of the generated image. It's an absolute value in pixels, therefore - * when scale is set to value different than 1.0 the height on the map will also - * be modified to fit into height pixels. - */ - private Double height = null; + // move the upper left corner to coordinates + graphics.translate(-params.getX(), -params.getY()); - /** - * Model to be visualized. - */ - private Model model = null; + if (params.isBackground()) { + // create a background + graphics.setColor(Color.WHITE); + graphics.fillRect((int) params.getX() - 1, (int) params.getY() - 1, + ((int) Math.ceil(params.getWidth() * scale)) + 2, ((int) Math.ceil(params.getHeight() * scale)) + 2); + graphics.setColor(Color.BLACK); + } - /** - * Should we draw white background. - */ - private boolean background = true; + // Get the SBGN display format option from the model + this.sbgnFormat = params.isSbgn(); - /** - * At which hierarchy level we visualize map. Level=0 means that we want to see - * as little elements as possible, whereas level=infinity means that we want to - * see everything. - */ - private int level = Integer.MAX_VALUE; + List<Drawable> bioEntities = new ArrayList<>(); + bioEntities.addAll(params.getModel().getBioEntities()); + for (Layer layer : params.getModel().getLayers()) { + if (layer.isVisible()) { + bioEntities.addAll(layer.getDrawables()); + } + } + bioEntities.sort(BioEntity.Z_INDEX_COMPARATOR); - /** - * Should the visualization include hierarchical view or not. - */ - private boolean nested = false; + // draw all elements + for (Drawable element : bioEntities) { + if (element instanceof Species) { + drawSpecies((Species) element); + } else if (element instanceof Reaction) { + drawReaction((Reaction) element); + } else if (element instanceof Compartment) { + drawCompartment((Compartment) element); + } else if (element instanceof LayerText) { + drawText((LayerText) element); + } else if (element instanceof LayerOval) { + drawOval((LayerOval) element); + } else if (element instanceof LayerRect) { + drawRect((LayerRect) element); + } else if (element instanceof PolylineData) { + drawLine((PolylineData) element); + } else { + throw new DrawingException("Unknown class type: " + element); + } + } + closeImageObject(); + setDrawn(true); + } - /** - * Should sbgn standard be used. - */ - private boolean sbgn = false; + private void drawText(LayerText element) { + new LayerTextConverter().draw(element, graphics); + } - /** - * List of objects containging information about layouts visualized in the - * javascript (on client side). Every object (map) represents data for single - * layout. In this map we have pairs between {@link Element}/ {@link Reaction} - * and {@link ColorSchema} used to visualize the element. - * - */ - private List<Map<Object, ColorSchema>> visibleLayouts = new ArrayList<>(); + private void drawRect(LayerRect element) { + new LayerRectConverter().draw(element, graphics); + } - /** - * Color that should be used for drawing overlays with minimum value. - */ - private Color minColor = Color.BLACK; + private void drawOval(LayerOval element) { + new LayerOvalConverter().draw(element, graphics); + } - /** - * Color that should be used for drawing overlays with maximum value. - */ - private Color maxColor = Color.BLACK; + private void drawLine(PolylineData element) { + new LayerLineConverter().draw(element, graphics); + } - private Color simpleColor = Color.BLACK; + /** + * Method called after drawing. It should close drawing canvas properly. + */ + protected abstract void closeImageObject(); - /** - * @param scale - * scale to set - * @return object with all parameters - * @see #scale - */ - public Params scale(final double scale) { - this.scale = scale; - return this; - } + /** + * This method draw a {@link Compartment} on a graphics. + * + * @param compartment + * object that we want to draw + * @throws DrawingException + * thrown when there was a problem with drawing {@link Compartment} + */ + protected void drawCompartment(final Compartment compartment) throws DrawingException { + // get a converter for this compartment + BioEntityConverterImpl converter = new BioEntityConverterImpl(compartment, colorExtractor); + ConverterParams compartmentParams = new ConverterParams().level(level).nested(params.nested); - /** - * @param scale - * scale to set - * @return object with all parameters - * @see #scale - */ - public Params scale(final int scale) { - this.scale = scale; - return this; + if (params.nested) { + compartmentParams.scale(Math.max(scale, 1)); } - /** - * - * @param x - * x coordinate to be set - * @return object with all parameters - * @see #x - */ - public Params x(final double x) { - this.x = x; - return this; - } + converter.draw(compartment, graphics, compartmentParams, params.getVisibleLayoutsForElement(compartment)); - /** - * @param x - * x coordinate to be set - * @return object with all parameters - * @see #x - */ - public Params x(final int x) { - this.x = x; - return this; + if (zoomLevelMatcher.isTransparent(level, compartment.getTransparencyLevel()) || !params.nested) { + if (!compartment.containsIdenticalSpecies()) { + if (!(compartment instanceof PathwayCompartment)) { + converter.drawText(compartment, graphics, compartmentParams); + } + } } + } - /** - * @param y - * y coordinate to be set - * @return object with all parameters - * @see #y - */ - public Params y(final double y) { - this.y = y; - return this; + /** + * This method draw a {@link Species} on a graphics. + * + * @param species + * object to be drawn + * @throws DrawingException + * thrown when there was a problem with drawing a {@link Species} + */ + protected void drawSpecies(final Species species) throws DrawingException { + if (!cross(species.getBorder())) { + return; } - /** - * @param y - * y coordinate to be set - * @return object with all parameters - * @see #y - */ - public Params y(final int y) { - this.y = y; - return this; + boolean rescale = false; + if (species instanceof Complex) { + Complex complex = (Complex) species; + if (complex.getElements().size() == 0) { + rescale = true; + } else { + rescale = true; + for (Element child : complex.getElements()) { + if ((zoomLevelMatcher.isVisible(level, child.getVisibilityLevel())) || !params.nested) { + rescale = false; + } + } + } } - /** - * @param width - * width to set - * @return object with all parameters - * @see #width - */ - public Params width(final double width) { - this.width = width; - return this; + // at the beginning try to find an appropriate converter + BioEntityConverterImpl converter = new BioEntityConverterImpl(species, sbgnFormat, colorExtractor); + double customScale = 1; + if (rescale) { + customScale = scale; } + converter.draw(species, graphics, + new ConverterParams().scale(customScale).level(level).sbgnFormat(sbgnFormat).nested(params.nested), + params.getVisibleLayoutsForElement(species)); - /** - * @param width - * width to set - * @return object with all parameters - * @see #width - */ - public Params width(final int width) { - this.width = (double) width; - return this; - } + } - /** - * - * @param height - * height to set - * @return object with all parameters - * @see #height - */ - public Params height(final double height) { - this.height = height; - return this; + /** + * This method draw a reaction on a graphics. + * + * @param reaction + * object to be drawn + * @throws DrawingException + * thrown when there was a problem with drawing a {@link Reaction} + */ + protected void drawReaction(final Reaction reaction) throws DrawingException { + if (!cross(reaction.getLines())) { + return; } + BioEntityConverterImpl converter = new BioEntityConverterImpl(reaction, sbgnFormat, colorExtractor); + converter.draw(reaction, graphics, new ConverterParams().sbgnFormat(sbgnFormat).nested(params.nested).level(level), + params.getVisibleLayoutsForElement(reaction)); + } - /** - * @param height - * height to set - * @return object with all parameters - * @see #height - */ - public Params height(final int height) { - this.height = (double) height; - return this; + /** + * Checks if one of the lines in parameter cross the frame. + * + * @param lines + * list of lines to check + * @return true if the cross point exist, false otherwise + */ + private boolean cross(final List<Line2D> lines) { + for (Line2D line2d : lines) { + if (border.intersectsLine(line2d)) { + return true; + } } + return false; + } - /** - * - * @param background - * background flag to set - * @return object with all parameters - * @see #background - */ - public Params background(final boolean background) { - this.background = background; - return this; - } + /** + * Checks if the rectangle in the parameters cross the fram in which we are + * currently draw image. + * + * @param rect + * rectangle to check + * @return true if rectangle check the frame, false otherwise + */ + protected boolean cross(final Rectangle2D rect) { + return border.intersects(rect); + } - /** - * - * @param nested - * nested flag to set - * @return object with all parameters - * @see #nested - */ - public Params nested(final boolean nested) { - this.nested = nested; - return this; - } + /** + * @return the graphics + */ + protected Graphics2D getGraphics() { + return graphics; + } - /** - * - * @param model - * model to set - * @return object with all parameters - * @see #model - */ - public Params model(final Model model) { - this.model = model; - if (this.width == null) { - this.width = model.getWidth(); - } - if (this.height == null) { - this.height = model.getHeight(); - } - return this; - } + /** + * @param graphics + * the graphics to set + */ + protected void setGraphics(Graphics2D graphics) { + this.graphics = graphics; + } - /** - * - * @param level - * level to set - * @return object with all parameters - * @see #level - */ - public Params level(final int level) { - this.level = level; - return this; +/** + * Saves generated image into file. + * + * @param fileName + * file where the images should be saved + * @throws IOException + * thrown when there is problem with output file + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + public final void saveToFile(String fileName) throws IOException, DrawingException { + if (!isDrawn()) { + draw(); } + saveToFileImplementation(fileName); + } /** - * - * @return scale value - * @see #scale - */ - public double getScale() { - return scale; - } + * Saves generated image from {@link #getGraphics()} into file. + * + * @param fileName + * file where the images should be saved + * @throws IOException + * thrown when there is problem with output file + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + protected abstract void saveToFileImplementation(String fileName) throws IOException;; - /** - * - * @return x coordinate value - * @see #x - */ - public double getX() { - return x; + /** + * Saves generated image into {@link OutputStream}. + * + * @param os + * stream where the images should be saved + * @throws IOException + * thrown when there is problem with output stream + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + public final void saveToOutputStream(OutputStream os) throws IOException, DrawingException { + if (!isDrawn()) { + draw(); } + saveToOutputStreamImplementation(os); + } - /** - * - * @return y coordinate value - * @see #y - */ - public double getY() { - return y; + /** + * Saves generated image from {@link #getGraphics()} into {@link OutputStream} . + * + * @param os + * stream where the images should be saved + * @throws IOException + * thrown when there is problem with output stream + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + protected abstract void saveToOutputStreamImplementation(OutputStream os) throws IOException; + + /** + * Saves part of the generated image file. + * + * @param fileName + * file where the images should be saved + * @param x + * x left margin of the image part + * @param y + * y top margin of the image part + * @param width + * width of the image part + * @param height + * hieght of the image part + * @throws IOException + * thrown when there is problem with output file + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + public final void savePartToFile(final int x, final int y, final int width, final int height, final String fileName) + throws IOException, DrawingException { + if (!isDrawn()) { + draw(); + } + savePartToFileImplementation(x, y, width, height, fileName); + } + + /** + * Saves part of the generated image from {@link #getGraphics()} into file. + * + * @param fileName + * file where the images should be saved + * @param x + * x left margin of the image part + * @param y + * y top margin of the image part + * @param width + * width of the image part + * @param height + * hieght of the image part + * @throws IOException + * thrown when there is problem with output file + */ + protected abstract void savePartToFileImplementation(final int x, final int y, final int width, final int height, + final String fileName) throws IOException; + + /** + * Saves part of the generated image into {@link OutputStream}. + * + * @param os + * stream where the images should be saved + * @param x + * x left margin of the image part + * @param y + * y top margin of the image part + * @param width + * width of the image part + * @param height + * hieght of the image part + * @throws IOException + * thrown when there is problem with output file + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + public final void savePartToOutputStream(final int x, final int y, final int width, final int height, + final OutputStream os) throws IOException, DrawingException { + if (!isDrawn()) { + draw(); } + savePartToOutputStreamImplementation(x, y, width, height, os); + } + + /** + * Saves part of the generated image from {@link #getGraphics()} into + * {@link OutputStream}. + * + * @param os + * stream where the images should be saved + * @param x + * x left margin of the image part + * @param y + * y top margin of the image part + * @param width + * width of the image part + * @param height + * hieght of the image part + * @throws IOException + * thrown when there is problem with output file + * @throws DrawingException + * thrown when there was a problem with drawing map + */ + protected abstract void savePartToOutputStreamImplementation(final int x, final int y, final int width, + final int height, final OutputStream os) throws IOException; + + /** + * Returns name of the format to which this graphic converter will transform. + * + * @return name of the format to which this graphic converter will transform + */ + public abstract String getFormatName(); + + /** + * Returns {@link MimeType} that should be used for files generated by this + * image generator. + * + * @return {@link MimeType} that should be used for files generated by this + * image generator + */ + public abstract MimeType getMimeType(); + + /** + * Returns default file extension used by this image generator. + * + * @return default file extension used by this image generator + */ + public abstract String getFileExtension(); + + /** + * @return the sbgnFormat + */ + protected boolean isSbgnFormat() { + return sbgnFormat; + } + + /** + * @param sbgnFormat + * the sbgnFormat to set + */ + protected void sbgnFormat(boolean sbgnFormat) { + this.sbgnFormat = sbgnFormat; + } + + /** + * @return the drawn + * @see #drawn + */ + private boolean isDrawn() { + return drawn; + } + + /** + * @param drawn + * the drawn to set + * @see #drawn + */ + private void setDrawn(boolean drawn) { + this.drawn = drawn; + } + + /** + * @return the params + * @see #params + */ + protected Params getParams() { + return params; + } + + /** + * @param params + * the params to set + * @see #params + */ + protected void setParams(Params params) { + this.params = params; + } + + /** + * This class contains a list of params that are used for drawing. + * + * @author Piotr Gawron + * + */ + public static class Params { /** - * - * @return width value - * @see #width + * Default class logger. */ - public double getWidth() { - return width; - } + private final Logger logger = LogManager.getLogger(Params.class); /** - * - * @return height value - * @see #height + * Scale at which we want to visualize the map. The default value is 1.0 (no + * magnification). */ - public double getHeight() { - return height; - } + private double scale = 1; /** - * - * @return model object - * @see #model + * x coordinate from which we start to draw a map. This is absolute value on the + * map (scale doesn't influence it). */ - public Model getModel() { - return model; - } + + private double x = 0; /** - * - * @return background value - * @see #background + * y coordinate from which we start to draw a map. This is absolute value on the + * map (scale doesn't influence it). */ - public boolean isBackground() { - return background; - } + private double y = 0; /** - * - * @return nested value - * @see #nested + * width of the generated image. It's an absolute value in pixels, therefore + * when scale is set to value different than 1.0 the width on the map will also + * be modified to fit into width pixels. */ - public boolean isNested() { - return nested; - } + private Double width = null; /** - * @return the level - * @see #level + * height of the generated image. It's an absolute value in pixels, therefore + * when scale is set to value different than 1.0 the height on the map will also + * be modified to fit into height pixels. */ - public int getLevel() { - return level; - } + private Double height = null; /** - * Sets {@link #level} parameter from {@link String}. - * - * @param zoomLevel - * new {@link #level} value - * @return object with all parameters + * Model to be visualized. */ - public Params level(String zoomLevel) { - if (zoomLevel == null) { - logger.warn("Parameter equals to null..."); - } else { - this.level = Integer.valueOf(zoomLevel); - } - return this; - } + private Model model = null; - @Override - public String toString() { - String result = "[" + this.getClass().getSimpleName() + "] " + "Model:" + model + "," + "scale:" + scale + "," - + "x:" + x + "," + "y:" + y + "," + "width:" + width + "," + "height:" + height + "," + "background:" - + background + "," + "level:" + level + "," + "nested:" + nested + ","; - return result; - } + /** + * Should we draw white background. + */ + private boolean background = true; /** - * Adds layout data that is visualized on the client side. Layout data contains - * mapping between {@link Element}/{@link Reaction} and {@link ColorSchema} used - * for coloring specific element. - * - * @param map - * layout data containing mapping between {@link Element}/ - * {@link Reaction} and {@link ColorSchema} used for coloring specific - * element + * At which hierarchy level we visualize map. Level=0 means that we want to see + * as little elements as possible, whereas level=infinity means that we want to + * see everything. */ - public void addVisibleLayout(Map<Object, ColorSchema> map) { - visibleLayouts.add(map); - } + private int level = Integer.MAX_VALUE; /** - * @return the visibleLayouts - * @see #visibleLayouts + * Should the visualization include hierarchical view or not. */ - public List<Map<Object, ColorSchema>> getVisibleLayouts() { - return visibleLayouts; + private boolean nested = false; + + /** + * Should sbgn standard be used. + */ + private boolean sbgn = false; + + /** + * List of objects containging information about layouts visualized in the + * javascript (on client side). Every object (map) represents data for single + * layout. In this map we have pairs between {@link Element}/ {@link Reaction} + * and {@link ColorSchema} used to visualize the element. + * + */ + private List<Map<Object, ColorSchema>> visibleLayouts = new ArrayList<>(); + + /** + * Color that should be used for drawing overlays with minimum value. + */ + private Color minColor = Color.BLACK; + + /** + * Color that should be used for drawing overlays with maximum value. + */ + private Color maxColor = Color.BLACK; + + private Color simpleColor = Color.BLACK; + + /** + * @param scale + * scale to set + * @return object with all parameters + * @see #scale + */ + public Params scale(final double scale) { + this.scale = scale; + return this; } /** - * Returns list with {@link ColorSchema} used to visualize the specific object - * in layouts visualized in the javascript. - * - * @param object - * object ({@link Element} or {@link Reaction}) for which we return - * list of {@link ColorSchema} in different layouts - * @return list with {@link ColorSchema} used to visualize the specific object - * in layouts visualized in the javascript - * @see #visibleLayouts + * @param scale + * scale to set + * @return object with all parameters + * @see #scale */ - public List<ColorSchema> getVisibleLayoutsForElement(Object object) { - List<ColorSchema> result = new ArrayList<>(); - for (Map<Object, ColorSchema> map : visibleLayouts) { - result.add(map.get(object)); - } - return result; + public Params scale(final int scale) { + this.scale = scale; + return this; } /** - * Returns {@link Color} that should be used for drawing overlays with maximum - * value. - * - * @return {@link Color} that should be used for drawing overlays with maximum - * value + * + * @param x + * x coordinate to be set + * @return object with all parameters + * @see #x */ - public Color getMaxColor() { - return maxColor; + public Params x(final double x) { + this.x = x; + return this; } - public Color getSimpleColor() { - return simpleColor; + /** + * @param x + * x coordinate to be set + * @return object with all parameters + * @see #x + */ + public Params x(final int x) { + this.x = x; + return this; } /** - * Returns {@link Color} that should be used for drawing overlays with minimum - * value. - * - * @return {@link Color} that should be used for drawing overlays with minimum - * value + * @param y + * y coordinate to be set + * @return object with all parameters + * @see #y */ - public Color getMinColor() { - return minColor; + public Params y(final double y) { + this.y = y; + return this; } /** - * @param minColor - * minColor to set + * @param y + * y coordinate to be set * @return object with all parameters - * @see #minColor + * @see #y */ - public Params minColor(Color minColor) { - this.minColor = minColor; + public Params y(final int y) { + this.y = y; return this; } /** - * @param maxColor - * maxColor to set + * @param width + * width to set * @return object with all parameters - * @see #maxColor + * @see #width */ - public Params maxColor(Color maxColor) { - this.maxColor = maxColor; + public Params width(final double width) { + this.width = width; return this; } /** - * @param simpleColor - * simpleColor to set + * @param width + * width to set * @return object with all parameters - * @see #simpleColor + * @see #width */ - public Params simpleColor(Color simpleColor) { - this.simpleColor = simpleColor; + public Params width(final int width) { + this.width = (double) width; return this; } /** - * @return the sbgn - * @see #sbgn + * + * @param height + * height to set + * @return object with all parameters + * @see #height */ - public boolean isSbgn() { - return sbgn; + public Params height(final double height) { + this.height = height; + return this; } /** - * @param sbgn - * the sbgn to set - * @see #sbgn + * @param height + * height to set * @return object with all parameters + * @see #height */ - public Params sbgn(boolean sbgn) { - this.sbgn = sbgn; + public Params height(final int height) { + this.height = (double) height; return this; } - public Params colorExtractor(ColorExtractor colorExtractor) { - return minColor(colorExtractor.getMinColor()).maxColor(colorExtractor.getMaxColor()) - .simpleColor(colorExtractor.getSimpleColor()); + /** + * + * @param background + * background flag to set + * @return object with all parameters + * @see #background + */ + public Params background(final boolean background) { + this.background = background; + return this; } - } + /** + * + * @param nested + * nested flag to set + * @return object with all parameters + * @see #nested + */ + public Params nested(final boolean nested) { + this.nested = nested; + return this; + } - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(AbstractImageGenerator.class); + /** + * + * @param model + * model to set + * @return object with all parameters + * @see #model + */ + public Params model(final Model model) { + this.model = model; + if (this.width == null) { + this.width = model.getWidth(); + } + if (this.height == null) { + this.height = model.getHeight(); + } + return this; + } - /** - * Graphics object which allows to draw objects. - */ - private Graphics2D graphics; + /** + * + * @param level + * level to set + * @return object with all parameters + * @see #level + */ + public Params level(final int level) { + this.level = level; + return this; + } - /** - * SBGN display format. - */ - private boolean sbgnFormat = false; + /** + * + * @return scale value + * @see #scale + */ + public double getScale() { + return scale; + } - /** - * List of params used for drawing. - */ - private Params params; + /** + * + * @return x coordinate value + * @see #x + */ + public double getX() { + return x; + } - /** - * This method creates a graphics object for different implementations of canvas - * with fixed width and height. - * - * @param width - * width of the canvas (graphics2d) to be created - * @param height - * height of the canvas (graphics2d) to be created - */ - protected abstract void createImageObject(double width, double height); - - /** - * Default constructor. Create an image that is described by params. For more - * information see - * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params - * params}. - * - * @param params - * list of all params to create appropriate image - * @throws DrawingException - * thrown when there was a problem with drawing a map - * - */ - protected AbstractImageGenerator(final Params params) { - this.params = params; - } - - /** - * Flag indicating {@link #draw()} method was executed. - */ - private boolean drawn = false; - - /** - * Draw a model into {@link #getGraphics()} object. - * - * @throws DrawingException - * thrown when there is a problem with drawing - */ - protected void draw() throws DrawingException { - if (isDrawn()) { - logger.warn("Model was already drawn. Skipping"); - return; + /** + * + * @return y coordinate value + * @see #y + */ + public double getY() { + return y; } - this.level = params.getLevel(); - this.scale = params.getScale(); - colorExtractor = new ColorExtractor(params.getMinColor(), params.getMaxColor(), params.getSimpleColor()); + /** + * + * @return width value + * @see #width + */ + public double getWidth() { + return width; + } - // set border frame extended by a margin - border = new Rectangle2D.Double(params.getX() - SINGLE_FRAME_MARGIN, params.getY() - SINGLE_FRAME_MARGIN, - params.getWidth() * scale + 2 * SINGLE_FRAME_MARGIN, params.getHeight() * scale + 2 * SINGLE_FRAME_MARGIN); - createImageObject(params.getWidth(), params.getHeight()); + /** + * + * @return height value + * @see #height + */ + public double getHeight() { + return height; + } - // turn on anti-aliasing - graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + /** + * + * @return model object + * @see #model + */ + public Model getModel() { + return model; + } - graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + /** + * + * @return background value + * @see #background + */ + public boolean isBackground() { + return background; + } - graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + /** + * + * @return nested value + * @see #nested + */ + public boolean isNested() { + return nested; + } - // set scale - graphics.scale(1 / scale, 1 / scale); + /** + * @return the level + * @see #level + */ + public int getLevel() { + return level; + } - // move the upper left corner to coordinates - graphics.translate(-params.getX(), -params.getY()); + /** + * Sets {@link #level} parameter from {@link String}. + * + * @param zoomLevel + * new {@link #level} value + * @return object with all parameters + */ + public Params level(String zoomLevel) { + if (zoomLevel == null) { + logger.warn("Parameter equals to null..."); + } else { + this.level = Integer.valueOf(zoomLevel); + } + return this; + } - if (params.isBackground()) { - // create a background - graphics.setColor(Color.WHITE); - graphics.fillRect((int) params.getX() - 1, (int) params.getY() - 1, - ((int) Math.ceil(params.getWidth() * scale)) + 2, ((int) Math.ceil(params.getHeight() * scale)) + 2); - graphics.setColor(Color.BLACK); + @Override + public String toString() { + String result = "[" + this.getClass().getSimpleName() + "] " + "Model:" + model + "," + "scale:" + scale + "," + + "x:" + x + "," + "y:" + y + "," + "width:" + width + "," + "height:" + height + "," + "background:" + + background + "," + "level:" + level + "," + "nested:" + nested + ","; + return result; } - // Get the SBGN display format option from the model - this.sbgnFormat = params.isSbgn(); + /** + * Adds layout data that is visualized on the client side. Layout data contains + * mapping between {@link Element}/{@link Reaction} and {@link ColorSchema} used + * for coloring specific element. + * + * @param map + * layout data containing mapping between {@link Element}/ + * {@link Reaction} and {@link ColorSchema} used for coloring specific + * element + */ + public void addVisibleLayout(Map<Object, ColorSchema> map) { + visibleLayouts.add(map); + } - List<Drawable> bioEntities = new ArrayList<>(); - bioEntities.addAll(params.getModel().getBioEntities()); - for (Layer layer : params.getModel().getLayers()) { - if (layer.isVisible()) { - bioEntities.addAll(layer.getDrawables()); - } + /** + * @return the visibleLayouts + * @see #visibleLayouts + */ + public List<Map<Object, ColorSchema>> getVisibleLayouts() { + return visibleLayouts; } - bioEntities.sort(BioEntity.Z_INDEX_COMPARATOR); - // draw all elements - for (Drawable element : bioEntities) { - if (element instanceof Species) { - drawSpecies((Species) element); - } else if (element instanceof Reaction) { - drawReaction((Reaction) element); - } else if (element instanceof Compartment) { - drawCompartment((Compartment) element); - } else if (element instanceof LayerText) { - drawText((LayerText) element); - } else if (element instanceof LayerOval) { - drawOval((LayerOval) element); - } else if (element instanceof LayerRect) { - drawRect((LayerRect) element); - } else if (element instanceof PolylineData) { - drawLine((PolylineData) element); - } else { - throw new DrawingException("Unknown class type: " + element); + /** + * Returns list with {@link ColorSchema} used to visualize the specific object + * in layouts visualized in the javascript. + * + * @param object + * object ({@link Element} or {@link Reaction}) for which we return + * list of {@link ColorSchema} in different layouts + * @return list with {@link ColorSchema} used to visualize the specific object + * in layouts visualized in the javascript + * @see #visibleLayouts + */ + public List<ColorSchema> getVisibleLayoutsForElement(Object object) { + List<ColorSchema> result = new ArrayList<>(); + for (Map<Object, ColorSchema> map : visibleLayouts) { + result.add(map.get(object)); } + return result; } - closeImageObject(); - setDrawn(true); - } - private void drawText(LayerText element) { - new LayerTextConverter().draw(element, graphics); - } + /** + * Returns {@link Color} that should be used for drawing overlays with maximum + * value. + * + * @return {@link Color} that should be used for drawing overlays with maximum + * value + */ + public Color getMaxColor() { + return maxColor; + } - private void drawRect(LayerRect element) { - new LayerRectConverter().draw(element, graphics); - } + public Color getSimpleColor() { + return simpleColor; + } - private void drawOval(LayerOval element) { - new LayerOvalConverter().draw(element, graphics); - } + /** + * Returns {@link Color} that should be used for drawing overlays with minimum + * value. + * + * @return {@link Color} that should be used for drawing overlays with minimum + * value + */ + public Color getMinColor() { + return minColor; + } - private void drawLine(PolylineData element) { - new LayerLineConverter().draw(element, graphics); - } + /** + * @param minColor + * minColor to set + * @return object with all parameters + * @see #minColor + */ + public Params minColor(Color minColor) { + this.minColor = minColor; + return this; + } - /** - * Method called after drawing. It should close drawing canvas properly. - */ - protected abstract void closeImageObject(); + /** + * @param maxColor + * maxColor to set + * @return object with all parameters + * @see #maxColor + */ + public Params maxColor(Color maxColor) { + this.maxColor = maxColor; + return this; + } - /** - * Don't allow to create default public constructors with empty list of - * parameters. - */ - protected AbstractImageGenerator() { - super(); - } - - /** - * This method draw a {@link Compartment} on a graphics. - * - * @param compartment - * object that we want to draw - * @throws DrawingException - * thrown when there was a problem with drawing {@link Compartment} - */ - protected void drawCompartment(final Compartment compartment) throws DrawingException { - // get a converter for this compartment - BioEntityConverterImpl converter = new BioEntityConverterImpl(compartment, colorExtractor); - ConverterParams compartmentParams = new ConverterParams().level(level).nested(params.nested); - - if (params.nested) { - compartmentParams.scale(Math.max(scale, 1)); - } - - converter.draw(compartment, graphics, compartmentParams, params.getVisibleLayoutsForElement(compartment)); - - if (zoomLevelMatcher.isTransparent(level, compartment.getTransparencyLevel()) || !params.nested) { - if (!compartment.containsIdenticalSpecies()) { - if (!(compartment instanceof PathwayCompartment)) { - converter.drawText(compartment, graphics, compartmentParams); - } - } - } - } - - /** - * This method draw a {@link Species} on a graphics. - * - * @param species - * object to be drawn - * @throws DrawingException - * thrown when there was a problem with drawing a {@link Species} - */ - protected void drawSpecies(final Species species) throws DrawingException { - if (!cross(species.getBorder())) { - return; - } - - boolean rescale = false; - if (species instanceof Complex) { - Complex complex = (Complex) species; - if (complex.getElements().size() == 0) { - rescale = true; - } else { - rescale = true; - for (Element child : complex.getElements()) { - if ((zoomLevelMatcher.isVisible(level, child.getVisibilityLevel())) || !params.nested) { - rescale = false; - } - } - } - } - - // at the beginning try to find an appropriate converter - BioEntityConverterImpl converter = new BioEntityConverterImpl(species, sbgnFormat, colorExtractor); - double customScale = 1; - if (rescale) { - customScale = scale; - } - converter.draw(species, graphics, - new ConverterParams().scale(customScale).level(level).sbgnFormat(sbgnFormat).nested(params.nested), - params.getVisibleLayoutsForElement(species)); - - } - - /** - * This method draw a reaction on a graphics. - * - * @param reaction - * object to be drawn - * @throws DrawingException - * thrown when there was a problem with drawing a {@link Reaction} - */ - protected void drawReaction(final Reaction reaction) throws DrawingException { - if (!cross(reaction.getLines())) { - return; - } - BioEntityConverterImpl converter = new BioEntityConverterImpl(reaction, sbgnFormat, colorExtractor); - converter.draw(reaction, graphics, new ConverterParams().sbgnFormat(sbgnFormat).nested(params.nested).level(level), - params.getVisibleLayoutsForElement(reaction)); - } - - /** - * Checks if one of the lines in parameter cross the frame. - * - * @param lines - * list of lines to check - * @return true if the cross point exist, false otherwise - */ - private boolean cross(final List<Line2D> lines) { - for (Line2D line2d : lines) { - if (border.intersectsLine(line2d)) { - return true; - } - } - return false; - } - - /** - * Checks if the rectangle in the parameters cross the fram in which we are - * currently draw image. - * - * @param rect - * rectangle to check - * @return true if rectangle check the frame, false otherwise - */ - protected boolean cross(final Rectangle2D rect) { - return border.intersects(rect); - } - - /** - * @return the graphics - */ - protected Graphics2D getGraphics() { - return graphics; - } - - /** - * @param graphics - * the graphics to set - */ - protected void setGraphics(Graphics2D graphics) { - this.graphics = graphics; - } - - /** - * Saves generated image into file. - * - * @param fileName - * file where the images should be saved - * @throws IOException - * thrown when there is problem with output file - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - public final void saveToFile(String fileName) throws IOException, DrawingException { - if (!isDrawn()) { - draw(); + /** + * @param simpleColor + * simpleColor to set + * @return object with all parameters + * @see #simpleColor + */ + public Params simpleColor(Color simpleColor) { + this.simpleColor = simpleColor; + return this; } - saveToFileImplementation(fileName); - }; - - /** - * Saves generated image from {@link #getGraphics()} into file. - * - * @param fileName - * file where the images should be saved - * @throws IOException - * thrown when there is problem with output file - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - protected abstract void saveToFileImplementation(String fileName) throws IOException; - /** - * Saves generated image into {@link OutputStream}. - * - * @param os - * stream where the images should be saved - * @throws IOException - * thrown when there is problem with output stream - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - public final void saveToOutputStream(OutputStream os) throws IOException, DrawingException { - if (!isDrawn()) { - draw(); + /** + * @return the sbgn + * @see #sbgn + */ + public boolean isSbgn() { + return sbgn; } - saveToOutputStreamImplementation(os); - } - - /** - * Saves generated image from {@link #getGraphics()} into {@link OutputStream} . - * - * @param os - * stream where the images should be saved - * @throws IOException - * thrown when there is problem with output stream - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - protected abstract void saveToOutputStreamImplementation(OutputStream os) throws IOException; - /** - * Saves part of the generated image file. - * - * @param fileName - * file where the images should be saved - * @param x - * x left margin of the image part - * @param y - * y top margin of the image part - * @param width - * width of the image part - * @param height - * hieght of the image part - * @throws IOException - * thrown when there is problem with output file - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - public final void savePartToFile(final int x, final int y, final int width, final int height, final String fileName) - throws IOException, DrawingException { - if (!isDrawn()) { - draw(); + /** + * @param sbgn + * the sbgn to set + * @see #sbgn + * @return object with all parameters + */ + public Params sbgn(boolean sbgn) { + this.sbgn = sbgn; + return this; } - savePartToFileImplementation(x, y, width, height, fileName); - } - - /** - * Saves part of the generated image from {@link #getGraphics()} into file. - * - * @param fileName - * file where the images should be saved - * @param x - * x left margin of the image part - * @param y - * y top margin of the image part - * @param width - * width of the image part - * @param height - * hieght of the image part - * @throws IOException - * thrown when there is problem with output file - */ - protected abstract void savePartToFileImplementation(final int x, final int y, final int width, final int height, - final String fileName) throws IOException; - /** - * Saves part of the generated image into {@link OutputStream}. - * - * @param os - * stream where the images should be saved - * @param x - * x left margin of the image part - * @param y - * y top margin of the image part - * @param width - * width of the image part - * @param height - * hieght of the image part - * @throws IOException - * thrown when there is problem with output file - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - public final void savePartToOutputStream(final int x, final int y, final int width, final int height, - final OutputStream os) throws IOException, DrawingException { - if (!isDrawn()) { - draw(); + public Params colorExtractor(ColorExtractor colorExtractor) { + return minColor(colorExtractor.getMinColor()).maxColor(colorExtractor.getMaxColor()) + .simpleColor(colorExtractor.getSimpleColor()); } - savePartToOutputStreamImplementation(x, y, width, height, os); - } - - /** - * Saves part of the generated image from {@link #getGraphics()} into - * {@link OutputStream}. - * - * @param os - * stream where the images should be saved - * @param x - * x left margin of the image part - * @param y - * y top margin of the image part - * @param width - * width of the image part - * @param height - * hieght of the image part - * @throws IOException - * thrown when there is problem with output file - * @throws DrawingException - * thrown when there was a problem with drawing map - */ - protected abstract void savePartToOutputStreamImplementation(final int x, final int y, final int width, - final int height, final OutputStream os) throws IOException; - /** - * Returns name of the format to which this graphic converter will transform. - * - * @return name of the format to which this graphic converter will transform - */ - public abstract String getFormatName(); - - /** - * Returns {@link MimeType} that should be used for files generated by this - * image generator. - * - * @return {@link MimeType} that should be used for files generated by this - * image generator - */ - public abstract MimeType getMimeType(); - - /** - * Returns default file extension used by this image generator. - * - * @return default file extension used by this image generator - */ - public abstract String getFileExtension(); - - /** - * @return the sbgnFormat - */ - protected boolean isSbgnFormat() { - return sbgnFormat; - } - - /** - * @param sbgnFormat - * the sbgnFormat to set - */ - protected void sbgnFormat(boolean sbgnFormat) { - this.sbgnFormat = sbgnFormat; - } - - /** - * @return the drawn - * @see #drawn - */ - private boolean isDrawn() { - return drawn; - } - - /** - * @param drawn - * the drawn to set - * @see #drawn - */ - private void setDrawn(boolean drawn) { - this.drawn = drawn; - } - - /** - * @return the params - * @see #params - */ - protected Params getParams() { - return params; - } - - /** - * @param params - * the params to set - * @see #params - */ - protected void setParams(Params params) { - this.params = params; } } \ No newline at end of file diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ConverterParams.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ConverterParams.java index 5e09864ab1..a791fe3f3d 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ConverterParams.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ConverterParams.java @@ -8,111 +8,111 @@ package lcsb.mapviewer.converter.graphics; */ public class ConverterParams { - /** - * At which level the object is visualized. It helps to deterimine font size. - * However it's possible that this value is not required. - */ - private int level = 0; + /** + * At which level the object is visualized. It helps to deterimine font size. + * However it's possible that this value is not required. + */ + private int level = 0; - /** - * What is the scale. It allows to adjust font size to be readable. - */ - private double scale = 1; + /** + * What is the scale. It allows to adjust font size to be readable. + */ + private double scale = 1; - /** - * Should the map be displayed in SBGN format. - */ - private boolean sbgnFormat = false; + /** + * Should the map be displayed in SBGN format. + */ + private boolean sbgnFormat = false; - /** - * Does the visualization include nesting/hierarchy. - */ - private boolean nested = false; + /** + * Does the visualization include nesting/hierarchy. + */ + private boolean nested = false; - /** - * @param scale - * the scale to set - * @return object with all parameters - * @see #scale - */ - public ConverterParams scale(final double scale) { - this.scale = scale; - return this; - } + /** + * @param scale + * the scale to set + * @return object with all parameters + * @see #scale + */ + public ConverterParams scale(final double scale) { + this.scale = scale; + return this; + } - /** - * @param nested - * the nested to set - * @return object with all parameters - * @see #nested - */ - public ConverterParams nested(final boolean nested) { - this.nested = nested; - return this; - } + /** + * @param nested + * the nested to set + * @return object with all parameters + * @see #nested + */ + public ConverterParams nested(final boolean nested) { + this.nested = nested; + return this; + } - /** - * @return the level - * @see #level - */ - public int getLevel() { - return level; - } + /** + * @return the level + * @see #level + */ + public int getLevel() { + return level; + } - /** - * @param level - * the level to set - * @return ConverterParams object with all parameters - * @see #level - */ - public ConverterParams level(int level) { - this.level = level; - return this; - } + /** + * @param level + * the level to set + * @return ConverterParams object with all parameters + * @see #level + */ + public ConverterParams level(int level) { + this.level = level; + return this; + } - /** - * @param sbgnFormat - * the sbgnFormat to set - * @return ConverterParams object with all parameters - * @see #sbgnFormat - */ - public ConverterParams sbgnFormat(boolean sbgnFormat) { - this.sbgnFormat = sbgnFormat; - return this; - } + /** + * @param sbgnFormat + * the sbgnFormat to set + * @return ConverterParams object with all parameters + * @see #sbgnFormat + */ + public ConverterParams sbgnFormat(boolean sbgnFormat) { + this.sbgnFormat = sbgnFormat; + return this; + } - /** - * @return the scale - * @see #scale - */ - public double getScale() { - return scale; - } + /** + * @return the scale + * @see #scale + */ + public double getScale() { + return scale; + } - /** - * @return the sbgnFormat - * @see #sbgnFormat - */ - public boolean isSbgnFormat() { - return sbgnFormat; - } + /** + * @return the sbgnFormat + * @see #sbgnFormat + */ + public boolean isSbgnFormat() { + return sbgnFormat; + } - /** - * @return the nested - * @see #nested - */ - public boolean isNested() { - return nested; - } + /** + * @return the nested + * @see #nested + */ + public boolean isNested() { + return nested; + } - @Override - public String toString() { - String result = "[" + this.getClass().getSimpleName() + "] " + - "level:" + level + "," + - "scale:" + scale + "," + - "nested:" + nested + "," + - "sbgnFormat:" + sbgnFormat; - return result; - } + @Override + public String toString() { + String result = "[" + this.getClass().getSimpleName() + "] " + + "level:" + level + "," + + "scale:" + scale + "," + + "nested:" + nested + "," + + "sbgnFormat:" + sbgnFormat; + return result; + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/DrawingException.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/DrawingException.java index bf1d439e69..a92ed96b7a 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/DrawingException.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/DrawingException.java @@ -8,31 +8,31 @@ package lcsb.mapviewer.converter.graphics; */ public class DrawingException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param string - * exception message - * @param e - * super exception - */ - public DrawingException(String string, Exception e) { - super(string, e); - } + /** + * Default constructor. + * + * @param string + * exception message + * @param e + * super exception + */ + public DrawingException(String string, Exception e) { + super(string, e); + } - /** - * Default constructor. - * - * @param string - * exception message - */ - public DrawingException(String string) { - super(string); - } + /** + * Default constructor. + * + * @param string + * exception message + */ + public DrawingException(String string) { + super(string); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ImageGenerators.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ImageGenerators.java index 1380ea0939..c0cecc00c7 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ImageGenerators.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/ImageGenerators.java @@ -1,12 +1,13 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Color; +import java.awt.*; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.MimeType; import lcsb.mapviewer.common.Pair; @@ -24,155 +25,156 @@ import lcsb.mapviewer.model.map.model.ModelFullIndexed; * */ public class ImageGenerators { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ImageGenerators.class); - /** - * List of {@link AbstractImageGenerator} classes available in the system. - */ - private List<Pair<String, Class<? extends AbstractImageGenerator>>> availableGenerators; + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ImageGenerators.class); + /** + * List of {@link AbstractImageGenerator} classes available in the system. + */ + private List<Pair<String, Class<? extends AbstractImageGenerator>>> availableGenerators; - /** - * List of all possible objects extending {@link AbstractImageGenerator} - * interface that are available in the system. - */ - private List<AbstractImageGenerator> generatorInstances = null; + /** + * List of all possible objects extending {@link AbstractImageGenerator} + * interface that are available in the system. + */ + private List<AbstractImageGenerator> generatorInstances = null; - /** - * Default constructor. - */ - public ImageGenerators() { - try { - availableGenerators = new ArrayList<Pair<String, Class<? extends AbstractImageGenerator>>>(); - Model model = new ModelFullIndexed(null); - AbstractImageGenerator.Params params = new AbstractImageGenerator.Params(). - model(model). - width(1). - minColor(Color.WHITE).maxColor(Color.WHITE).height(1); - generatorInstances = new ArrayList<>(); - generatorInstances.add(new PngImageGenerator(params)); - generatorInstances.add(new PdfImageGenerator(params)); - generatorInstances.add(new SvgImageGenerator(params)); - // generatorInstances.add(new JpgImageGenerator(params)); - for (AbstractImageGenerator abstractImageGenerator : generatorInstances) { - availableGenerators - .add(new Pair<String, Class<? extends AbstractImageGenerator>>(abstractImageGenerator.getFormatName(), abstractImageGenerator.getClass())); - } + /** + * Default constructor. + */ + public ImageGenerators() { + try { + availableGenerators = new ArrayList<Pair<String, Class<? extends AbstractImageGenerator>>>(); + Model model = new ModelFullIndexed(null); + AbstractImageGenerator.Params params = new AbstractImageGenerator.Params().model(model).width(1) + .minColor(Color.WHITE).maxColor(Color.WHITE).height(1); + generatorInstances = new ArrayList<>(); + generatorInstances.add(new PngImageGenerator(params)); + generatorInstances.add(new PdfImageGenerator(params)); + generatorInstances.add(new SvgImageGenerator(params)); + // generatorInstances.add(new JpgImageGenerator(params)); + for (AbstractImageGenerator abstractImageGenerator : generatorInstances) { + availableGenerators + .add(new Pair<String, Class<? extends AbstractImageGenerator>>(abstractImageGenerator.getFormatName(), + abstractImageGenerator.getClass())); + } - } catch (DrawingException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } - } + } catch (DrawingException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } + } - /** - * Returns {@link #availableGenerators}. - * - * @return {@link #availableGenerators} - */ - public List<Pair<String, Class<? extends AbstractImageGenerator>>> getAvailableImageGenerators() { - return availableGenerators; - } + /** + * Returns {@link #availableGenerators}. + * + * @return {@link #availableGenerators} + */ + public List<Pair<String, Class<? extends AbstractImageGenerator>>> getAvailableImageGenerators() { + return availableGenerators; + } - /** - * Generates image and saves it to a file. - * - * @param generatorClass - * which {@link AbstractImageGenerator} should be used to generate an - * image - * @param params - * parameters of the image generation process (scaling, size, - * nesting, etc) - * @param filename - * name of the file where result should be saved - * @return {@link MimeType} of the generated object - * @throws IOException - * thrown when there is a problem with output file - * @throws DrawingException - * thrown when there is a problem drawing map - */ - public MimeType generate(Class<? extends AbstractImageGenerator> generatorClass, AbstractImageGenerator.Params params, String filename) - throws IOException, DrawingException { - try { - AbstractImageGenerator generator = generatorClass.getConstructor(AbstractImageGenerator.Params.class).newInstance(params); - generator.saveToFile(filename); - return generator.getMimeType(); - } catch (InstantiationException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } catch (IllegalAccessException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } catch (IllegalArgumentException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } catch (InvocationTargetException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } catch (NoSuchMethodException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } catch (SecurityException e) { - throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); - } - } + /** + * Generates image and saves it to a file. + * + * @param generatorClass + * which {@link AbstractImageGenerator} should be used to generate an + * image + * @param params + * parameters of the image generation process (scaling, size, nesting, + * etc) + * @param filename + * name of the file where result should be saved + * @return {@link MimeType} of the generated object + * @throws IOException + * thrown when there is a problem with output file + * @throws DrawingException + * thrown when there is a problem drawing map + */ + public MimeType generate(Class<? extends AbstractImageGenerator> generatorClass, AbstractImageGenerator.Params params, + String filename) + throws IOException, DrawingException { + try { + AbstractImageGenerator generator = generatorClass.getConstructor(AbstractImageGenerator.Params.class) + .newInstance(params); + generator.saveToFile(filename); + return generator.getMimeType(); + } catch (InstantiationException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } catch (IllegalAccessException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } catch (IllegalArgumentException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } catch (InvocationTargetException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } catch (NoSuchMethodException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } catch (SecurityException e) { + throw new InvalidStateException("Problem with ImageGenarater instance creation...", e); + } + } - /** - * Generates image and saves it to a file. - * - * @param generatorClass - * name of the {@link AbstractImageGenerator} implementation that - * should be used to generate an image - * @param params - * parameters of the image generation process (scaling, size, - * nesting, etc) - * @param filename - * name of the file where result should be saved - * @return {@link MimeType} of the generated object - * @throws IOException - * thrown when there is a problem with output file - * @throws DrawingException - * thrown when there is a problem drawing map - */ - public MimeType generate(String generatorClass, Params params, String filename) throws IOException, DrawingException { - for (Pair<String, Class<? extends AbstractImageGenerator>> element : availableGenerators) { - if (element.getRight().getCanonicalName().equals(generatorClass)) { - return generate(element.getRight(), params, filename); - } - } - throw new InvalidArgumentException("Unknown class type: " + generatorClass); + /** + * Generates image and saves it to a file. + * + * @param generatorClass + * name of the {@link AbstractImageGenerator} implementation that + * should be used to generate an image + * @param params + * parameters of the image generation process (scaling, size, nesting, + * etc) + * @param filename + * name of the file where result should be saved + * @return {@link MimeType} of the generated object + * @throws IOException + * thrown when there is a problem with output file + * @throws DrawingException + * thrown when there is a problem drawing map + */ + public MimeType generate(String generatorClass, Params params, String filename) throws IOException, DrawingException { + for (Pair<String, Class<? extends AbstractImageGenerator>> element : availableGenerators) { + if (element.getRight().getCanonicalName().equals(generatorClass)) { + return generate(element.getRight(), params, filename); + } + } + throw new InvalidArgumentException("Unknown class type: " + generatorClass); - } + } - /** - * Returns file extension that should be used for files generated by - * implementation of {@link AbstractImageGenerator} class. - * - * @param generatorClass - * name of the class that extends {@link AbstractImageGenerator} - * @return file extension that should be used for files generated by - * implementation of {@link AbstractImageGenerator} class - */ - public String getExtension(String generatorClass) { - for (Pair<String, Class<? extends AbstractImageGenerator>> element : availableGenerators) { - if (element.getRight().getCanonicalName().equals(generatorClass)) { - return getExtension(element.getRight()); - } - } - throw new InvalidArgumentException("Unknown class type: " + generatorClass); - } + /** + * Returns file extension that should be used for files generated by + * implementation of {@link AbstractImageGenerator} class. + * + * @param generatorClass + * name of the class that extends {@link AbstractImageGenerator} + * @return file extension that should be used for files generated by + * implementation of {@link AbstractImageGenerator} class + */ + public String getExtension(String generatorClass) { + for (Pair<String, Class<? extends AbstractImageGenerator>> element : availableGenerators) { + if (element.getRight().getCanonicalName().equals(generatorClass)) { + return getExtension(element.getRight()); + } + } + throw new InvalidArgumentException("Unknown class type: " + generatorClass); + } - /** - * Returns file extension that should be used for files generated by - * implementation of {@link AbstractImageGenerator} class. - * - * @param generatorClass - * class that extends {@link AbstractImageGenerator} - * @return file extension that should be used for files generated by - * implementation of {@link AbstractImageGenerator} class - */ - public String getExtension(Class<? extends AbstractImageGenerator> generatorClass) { - for (AbstractImageGenerator imageGenerator : generatorInstances) { - if (generatorClass.isAssignableFrom(imageGenerator.getClass())) { - return imageGenerator.getFileExtension(); - } - } - throw new InvalidArgumentException("Unknown class type: " + generatorClass); - } + /** + * Returns file extension that should be used for files generated by + * implementation of {@link AbstractImageGenerator} class. + * + * @param generatorClass + * class that extends {@link AbstractImageGenerator} + * @return file extension that should be used for files generated by + * implementation of {@link AbstractImageGenerator} class + */ + public String getExtension(Class<? extends AbstractImageGenerator> generatorClass) { + for (AbstractImageGenerator imageGenerator : generatorInstances) { + if (generatorClass.isAssignableFrom(imageGenerator.getClass())) { + return imageGenerator.getFileExtension(); + } + } + throw new InvalidArgumentException("Unknown class type: " + generatorClass); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/JpgImageGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/JpgImageGenerator.java index e5c57e4b79..1fbff3b27e 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/JpgImageGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/JpgImageGenerator.java @@ -1,11 +1,8 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; import javax.imageio.ImageIO; @@ -20,65 +17,66 @@ import lcsb.mapviewer.common.MimeType; */ public class JpgImageGenerator extends NormalImageGenerator { - /** - * Default constructor. Create an image that is described by params. For more - * information see - * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params - * params}. - * - * @param params - * parameters used for the image creation. - * @throws DrawingException - * thrown when there was a problem with drawing a map - */ - public JpgImageGenerator(Params params) throws DrawingException { - super(params); - } + /** + * Default constructor. Create an image that is described by params. For more + * information see + * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params + * params}. + * + * @param params + * parameters used for the image creation. + * @throws DrawingException + * thrown when there was a problem with drawing a map + */ + public JpgImageGenerator(Params params) throws DrawingException { + super(params); + } - @Override - public void saveToFileImplementation(String fileName) throws IOException { - FileOutputStream fos = new FileOutputStream(new File(fileName)); - saveToOutputStreamImplementation(fos); - fos.close(); - } + @Override + protected void closeImageObject() { + } - @Override - public void saveToOutputStreamImplementation(OutputStream os) throws IOException { - ImageIO.write(getBi(), "JPG", os); - } + @Override + public void saveToFileImplementation(String fileName) throws IOException { + FileOutputStream fos = new FileOutputStream(new File(fileName)); + saveToOutputStreamImplementation(fos); + fos.close(); + } - @Override - public void savePartToFileImplementation(int x, int y, int width, int height, String fileName) throws IOException { - FileOutputStream fos = new FileOutputStream(new File(fileName)); - savePartToOutputStreamImplementation(x, y, width, height, fos); - fos.close(); - } + @Override + public void saveToOutputStreamImplementation(OutputStream os) throws IOException { + ImageIO.write(getBi(), "JPG", os); + } - @Override - public void savePartToOutputStreamImplementation(int x, int y, int width, int height, OutputStream os) throws IOException { - BufferedImage tmpBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D tmpGraphics = tmpBI.createGraphics(); - tmpGraphics.drawImage(getBi(), 0, 0, width, height, x, y, x + width, y + width, null); - ImageIO.write(tmpBI, "JPG", os); - } + @Override + public void savePartToFileImplementation(int x, int y, int width, int height, String fileName) throws IOException { + FileOutputStream fos = new FileOutputStream(new File(fileName)); + savePartToOutputStreamImplementation(x, y, width, height, fos); + fos.close(); + } - @Override - public String getFormatName() { - return "JPG image"; - } + @Override + public void savePartToOutputStreamImplementation(int x, int y, int width, int height, OutputStream os) + throws IOException { + BufferedImage tmpBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics2D tmpGraphics = tmpBI.createGraphics(); + tmpGraphics.drawImage(getBi(), 0, 0, width, height, x, y, x + width, y + width, null); + ImageIO.write(tmpBI, "JPG", os); + } - @Override - public MimeType getMimeType() { - return MimeType.JPG; - } + @Override + public String getFormatName() { + return "JPG image"; + } - @Override - public String getFileExtension() { - return "jpg"; - } + @Override + public MimeType getMimeType() { + return MimeType.JPG; + } - @Override - protected void closeImageObject() { - } + @Override + public String getFileExtension() { + return "jpg"; + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/MapGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/MapGenerator.java index 5a288dec28..a761e69120 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/MapGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/MapGenerator.java @@ -4,7 +4,8 @@ import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.IProgressUpdater; @@ -22,6 +23,176 @@ import lcsb.mapviewer.model.map.model.Model; */ public class MapGenerator { + /** + * Default tile size. It must be 256px*256px, if different value is chosen then + * there are problems with positioning all elements by GoogleMaps API (like + * putting markers, line, getting position etc). + */ + public static final int TILE_SIZE = 256; + /** + * Because generating of PNG file require to transform the whole Model class + * into canvas, the bigger image is created and after the image is created small + * chunks are sliced and saved to files. For instance if TILES_CACHE_NUM=4 and + * TILE_SIZE=256, then ImageGenerator will create PNG images 1024px*1024px and + * this images are sliced into 256px*256px images. Of course TILES_CACHE_NUM + * cannot be too big due to Out of Memory problem. + */ + + static final int TILES_CACHE_NUM = 4; + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(MapGenerator.class.getName()); + + /** + * This method generates PNG images used by GoogleMaps API. + * + * @param params + * {@link MapGeneratorParams params} used for generating images + * @throws IOException + * exception thrown when there are some problems with creating images + * @throws DrawingException + * thrown when there was a problem with drawing a map + */ + public void generateMapImages(MapGeneratorParams params) throws IOException, DrawingException { + + if (params.nested) { + logger + .debug("Creating nested model with " + params.levels + " levels and maximum zoom rate: " + params.zoomFactor); + } else { + logger.debug( + "Creating not nested model with " + params.levels + " levels and maximum zoom rate: " + params.zoomFactor); + } + + // compute number of tiles (for progress bar) + double num = 0; + for (int i = 0; i <= params.levels; i++) { + double m = Math.ceil((int) Math.pow(2, i)) / TILES_CACHE_NUM; + m = Math.ceil(m); + m *= TILES_CACHE_NUM; + num += m * m; + } + + String zoomDirStr = params.directory; + File zoomDir = new File(zoomDirStr); + if (zoomDir.isDirectory()) { + logger.warn("Removing directory: " + zoomDir.getAbsolutePath()); + FileUtils.deleteDirectory(zoomDir); + } else if (zoomDir.isFile()) { + logger.warn("Removing file: " + zoomDir.getAbsolutePath()); + zoomDir.delete(); + } + + int progress = 0; + for (int i = 0; i <= params.levels; i++) { + zoomDirStr = params.directory + System.getProperty("file.separator") + (i + Configuration.MIN_ZOOM_LEVEL) + + System.getProperty("file.separator"); + int tiles = (int) (Math.pow(2, i)); + for (int j = 0; j < tiles + TILES_CACHE_NUM; j++) { + zoomDir = new File(zoomDirStr + System.getProperty("file.separator") + j); + if (!zoomDir.exists()) { + + if (!zoomDir.mkdirs()) { + logger.warn("Problem with creating dir: " + zoomDir.getAbsolutePath()); + } + } + } + for (int j = 0; j < tiles; j += TILES_CACHE_NUM) { + for (int k = 0; k < tiles; k += TILES_CACHE_NUM) { + params.updater.setProgress((IProgressUpdater.MAX_PROGRESS * progress / num)); + progress += TILES_CACHE_NUM * TILES_CACHE_NUM; + if (j * TILE_SIZE * params.zoomFactor > params.model.getWidth() + || k * TILE_SIZE * params.zoomFactor > params.model.getHeight()) { + continue; + } else { + Params imgParams = new Params(); + imgParams.scale(params.zoomFactor); + imgParams.x(j * TILE_SIZE * params.zoomFactor); + imgParams.y(k * TILE_SIZE * params.zoomFactor); + imgParams.width(TILE_SIZE * TILES_CACHE_NUM); + imgParams.height(TILE_SIZE * TILES_CACHE_NUM); + imgParams.model(params.model); + imgParams.sbgn(params.sbgn); + imgParams.level(i); + imgParams.nested(params.nested); + PngImageGenerator generator = new PngImageGenerator(imgParams); + for (int cx = 0; cx < TILES_CACHE_NUM; cx++) { + for (int cy = 0; cy < TILES_CACHE_NUM; cy++) { + if ((j + cx) * TILE_SIZE * params.zoomFactor >= params.model.getWidth() + || (k + cy) * TILE_SIZE * params.zoomFactor >= params.model.getHeight()) { + continue; + } else { + String fileName = zoomDirStr + (j + cx) + System.getProperty("file.separator") + (k + cy) + ".PNG"; + generator.savePartToFile(cx * TILE_SIZE, cy * TILE_SIZE, TILE_SIZE, TILE_SIZE, fileName); + } + } + } + } + } + } + params.zoomFactor /= 2; + } + } + + /** + * Computes how many zoom levels should exists for the map model. + * + * @param model + * map model + * @return zoom levels for the model + */ + public int computeZoomLevels(final Model model) { + return (int) Math.ceil(Math.log(computeZoomFactor(model)) / Math.log(2)); + } + + /** + * Computes the scale that should be used on the top zoom level. + * + * @param model + * model for which computation is done + * @return scale on the top zoom level + */ + public double computeZoomFactor(final Model model) { + return Math.max(model.getHeight(), model.getWidth()) / (TILE_SIZE); + } + + /** + * Removes files that were generated for the layout. + * + * @param dbLayout + * layout object for which images will be removed + * @throws IOException + * thrown whene there are some problems with removing files + */ + public void removeLayout(final Layout dbLayout) throws IOException { + removeLayout(dbLayout, null); + } + + /** + * Removes files that were generated for the layout. + * + * @param dbLayout + * layout object for which images will be removed + * @param homeDir + * determines the directory where images are stored (it's optional) + * @throws IOException + * thrown when there are some problems with removing files + */ + public void removeLayout(final Layout dbLayout, String homeDir) throws IOException { + for (DataOverlayImageLayer imageLayer : dbLayout.getDataOverlayImageLayers()) { + String directory = imageLayer.getDirectory(); + File dir = new File(directory); + if (!dir.isAbsolute() && homeDir != null) { + dir = new File(homeDir + "/" + directory); + } + if (dir.exists()) { + FileUtils.deleteDirectory(dir); + } else { + logger.warn("Trying to remove dir that doesn't exist: " + dir.getAbsolutePath() + " (" + directory + ")"); + } + } + } + /** * Parameter class with information for generating set of images: * <ul> @@ -33,37 +204,37 @@ public class MapGenerator { * <li>{@link #zoomFactor}</li> * <li>{@link #levels}</li>. * </ul> - * - * + * + * * @author Piotr Gawron - * + * */ public class MapGeneratorParams { /** * Information about map to be generated. - * + * */ private Model model; /** * Where we want to put the files. The structure of the directory will be as * follows: directory/subDirA/subDirB/file.PNG. subDirA is a level of zooming. * subDirB is x coordinate of the image. file is y coordinate of the image. - * + * */ private String directory; /** * Do we want to generate images in hierarchical view or normal. - * + * */ private boolean nested = false; /** * Should we remove empty elements in nested view. - * + * */ private boolean removeEmpty = false; /** * Callback function that update progress information. - * + * */ private IProgressUpdater updater = new IProgressUpdater() { @Override @@ -230,176 +401,4 @@ public class MapGenerator { } - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(MapGenerator.class.getName()); - - /** - * Default tile size. It must be 256px*256px, if different value is chosen then - * there are problems with positioning all elements by GoogleMaps API (like - * putting markers, line, getting position etc). - */ - public static final int TILE_SIZE = 256; - - /** - * Because generating of PNG file require to transform the whole Model class - * into canvas, the bigger image is created and after the image is created small - * chunks are sliced and saved to files. For instance if TILES_CACHE_NUM=4 and - * TILE_SIZE=256, then ImageGenerator will create PNG images 1024px*1024px and - * this images are sliced into 256px*256px images. Of course TILES_CACHE_NUM - * cannot be too big due to Out of Memory problem. - */ - - static final int TILES_CACHE_NUM = 4; - - /** - * This method generates PNG images used by GoogleMaps API. - * - * @param params - * {@link MapGeneratorParams params} used for generating images - * @throws IOException - * exception thrown when there are some problems with creating images - * @throws DrawingException - * thrown when there was a problem with drawing a map - */ - public void generateMapImages(MapGeneratorParams params) throws IOException, DrawingException { - - if (params.nested) { - logger - .debug("Creating nested model with " + params.levels + " levels and maximum zoom rate: " + params.zoomFactor); - } else { - logger.debug( - "Creating not nested model with " + params.levels + " levels and maximum zoom rate: " + params.zoomFactor); - } - - // compute number of tiles (for progress bar) - double num = 0; - for (int i = 0; i <= params.levels; i++) { - double m = Math.ceil((int) Math.pow(2, i)) / TILES_CACHE_NUM; - m = Math.ceil(m); - m *= TILES_CACHE_NUM; - num += m * m; - } - - String zoomDirStr = params.directory; - File zoomDir = new File(zoomDirStr); - if (zoomDir.isDirectory()) { - logger.warn("Removing directory: " + zoomDir.getAbsolutePath()); - FileUtils.deleteDirectory(zoomDir); - } else if (zoomDir.isFile()) { - logger.warn("Removing file: " + zoomDir.getAbsolutePath()); - zoomDir.delete(); - } - - int progress = 0; - for (int i = 0; i <= params.levels; i++) { - zoomDirStr = params.directory + System.getProperty("file.separator") + (i + Configuration.MIN_ZOOM_LEVEL) - + System.getProperty("file.separator"); - int tiles = (int) (Math.pow(2, i)); - for (int j = 0; j < tiles + TILES_CACHE_NUM; j++) { - zoomDir = new File(zoomDirStr + System.getProperty("file.separator") + j); - if (!zoomDir.exists()) { - - if (!zoomDir.mkdirs()) { - logger.warn("Problem with creating dir: " + zoomDir.getAbsolutePath()); - } - } - } - for (int j = 0; j < tiles; j += TILES_CACHE_NUM) { - for (int k = 0; k < tiles; k += TILES_CACHE_NUM) { - params.updater.setProgress((IProgressUpdater.MAX_PROGRESS * progress / num)); - progress += TILES_CACHE_NUM * TILES_CACHE_NUM; - if (j * TILE_SIZE * params.zoomFactor > params.model.getWidth() - || k * TILE_SIZE * params.zoomFactor > params.model.getHeight()) { - continue; - } else { - Params imgParams = new Params(); - imgParams.scale(params.zoomFactor); - imgParams.x(j * TILE_SIZE * params.zoomFactor); - imgParams.y(k * TILE_SIZE * params.zoomFactor); - imgParams.width(TILE_SIZE * TILES_CACHE_NUM); - imgParams.height(TILE_SIZE * TILES_CACHE_NUM); - imgParams.model(params.model); - imgParams.sbgn(params.sbgn); - imgParams.level(i); - imgParams.nested(params.nested); - PngImageGenerator generator = new PngImageGenerator(imgParams); - for (int cx = 0; cx < TILES_CACHE_NUM; cx++) { - for (int cy = 0; cy < TILES_CACHE_NUM; cy++) { - if ((j + cx) * TILE_SIZE * params.zoomFactor >= params.model.getWidth() - || (k + cy) * TILE_SIZE * params.zoomFactor >= params.model.getHeight()) { - continue; - } else { - String fileName = zoomDirStr + (j + cx) + System.getProperty("file.separator") + (k + cy) + ".PNG"; - generator.savePartToFile(cx * TILE_SIZE, cy * TILE_SIZE, TILE_SIZE, TILE_SIZE, fileName); - } - } - } - } - } - } - params.zoomFactor /= 2; - } - } - - /** - * Computes how many zoom levels should exists for the map model. - * - * @param model - * map model - * @return zoom levels for the model - */ - public int computeZoomLevels(final Model model) { - return (int) Math.ceil(Math.log(computeZoomFactor(model)) / Math.log(2)); - } - - /** - * Computes the scale that should be used on the top zoom level. - * - * @param model - * model for which computation is done - * @return scale on the top zoom level - */ - public double computeZoomFactor(final Model model) { - return Math.max(model.getHeight(), model.getWidth()) / (TILE_SIZE); - } - - /** - * Removes files that were generated for the layout. - * - * @param dbLayout - * layout object for which images will be removed - * @throws IOException - * thrown whene there are some problems with removing files - */ - public void removeLayout(final Layout dbLayout) throws IOException { - removeLayout(dbLayout, null); - } - - /** - * Removes files that were generated for the layout. - * - * @param dbLayout - * layout object for which images will be removed - * @param homeDir - * determines the directory where images are stored (it's optional) - * @throws IOException - * thrown when there are some problems with removing files - */ - public void removeLayout(final Layout dbLayout, String homeDir) throws IOException { - for (DataOverlayImageLayer imageLayer: dbLayout.getDataOverlayImageLayers()) { - String directory = imageLayer.getDirectory(); - File dir = new File(directory); - if (!dir.isAbsolute() && homeDir != null) { - dir = new File(homeDir + "/" + directory); - } - if (dir.exists()) { - FileUtils.deleteDirectory(dir); - } else { - logger.warn("Trying to remove dir that doesn't exist: " + dir.getAbsolutePath() + " (" + directory + ")"); - } - } - } - } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/NormalImageGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/NormalImageGenerator.java index bae85e5d45..c12642bec7 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/NormalImageGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/NormalImageGenerator.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.converter.graphics; import java.awt.image.BufferedImage; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Extension of the image generator class that use standard awt implementation @@ -12,54 +13,54 @@ import org.apache.logging.log4j.*; * */ public abstract class NormalImageGenerator extends AbstractImageGenerator { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(NormalImageGenerator.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(NormalImageGenerator.class); - /** - * Buffered image structure used for image generating. - */ - private BufferedImage bi; + /** + * Buffered image structure used for image generating. + */ + private BufferedImage bi; - /** - * Default constructor. Create an image that is described by params. For more - * information see - * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params - * params}. - * - * @param params - * parameters used for the image creation. - * @throws DrawingException - * thrown when there was a problem with drawing a map - */ - protected NormalImageGenerator(final Params params) throws DrawingException { - super(params); - } + /** + * Default constructor. Create an image that is described by params. For more + * information see + * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params + * params}. + * + * @param params + * parameters used for the image creation. + * @throws DrawingException + * thrown when there was a problem with drawing a map + */ + protected NormalImageGenerator(final Params params) throws DrawingException { + super(params); + } - @Override - protected void createImageObject(final double width, final double height) { - bi = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_ARGB); - setGraphics(bi.createGraphics()); - } + @Override + protected void createImageObject(final double width, final double height) { + bi = new BufferedImage((int) width, (int) height, BufferedImage.TYPE_INT_ARGB); + setGraphics(bi.createGraphics()); + } - /** - * @return the bi - * @throws DrawingException - * @see #bi - */ - protected BufferedImage getBi() { - return bi; - } + /** + * @return the bi + * @throws DrawingException + * @see #bi + */ + protected BufferedImage getBi() { + return bi; + } - /** - * @param bi - * the bi to set - * @see #bi - */ - protected void setBi(BufferedImage bi) { - this.bi = bi; - } + /** + * @param bi + * the bi to set + * @see #bi + */ + protected void setBi(BufferedImage bi) { + this.bi = bi; + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfFontMapper.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfFontMapper.java index 0f1b991e9a..544f7a7574 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfFontMapper.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfFontMapper.java @@ -1,9 +1,10 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Font; +import java.awt.*; import java.io.IOException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import com.itextpdf.awt.DefaultFontMapper; import com.itextpdf.text.DocumentException; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfImageGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfImageGenerator.java index fac7551c2a..575afeb5c6 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfImageGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PdfImageGenerator.java @@ -1,15 +1,11 @@ package lcsb.mapviewer.converter.graphics; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; import org.apache.commons.io.output.ByteArrayOutputStream; import com.itextpdf.awt.PdfGraphics2D; -import com.itextpdf.text.Document; -import com.itextpdf.text.DocumentException; -import com.itextpdf.text.Rectangle; +import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfWriter; @@ -36,6 +32,21 @@ public class PdfImageGenerator extends AbstractImageGenerator { */ private Document pdfDocument; + /** + * Default constructor. Create an image that is described by params. For more + * information see + * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params + * params}. + * + * @param params + * parameters used for the image creation. + * @throws DrawingException + * thrown when there was a problem with drawing a map + */ + public PdfImageGenerator(final Params params) throws DrawingException { + super(params); + } + @Override protected void createImageObject(final double width, final double height) { try { @@ -53,6 +64,12 @@ public class PdfImageGenerator extends AbstractImageGenerator { } + @Override + protected void closeImageObject() { + getGraphics().dispose(); + pdfDocument.close(); + } + @Override public void saveToFileImplementation(final String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); @@ -60,27 +77,6 @@ public class PdfImageGenerator extends AbstractImageGenerator { fos.close(); } - /** - * Default constructor. Create an image that is described by params. For more - * information see - * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params - * params}. - * - * @param params - * parameters used for the image creation. - * @throws DrawingException - * thrown when there was a problem with drawing a map - */ - public PdfImageGenerator(final Params params) throws DrawingException { - super(params); - } - - @Override - protected void closeImageObject() { - getGraphics().dispose(); - pdfDocument.close(); - } - @Override public void saveToOutputStreamImplementation(OutputStream os) throws IOException { inMemoryOutputStream.writeTo(os); diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PngImageGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PngImageGenerator.java index 2c92508fcd..732fba87c8 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PngImageGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/PngImageGenerator.java @@ -1,15 +1,13 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; import javax.imageio.ImageIO; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.MimeType; @@ -22,71 +20,72 @@ import lcsb.mapviewer.common.MimeType; */ public class PngImageGenerator extends NormalImageGenerator { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(PngImageGenerator.class); - - /** - * Default constructor. Create an image that is described by params. For more - * information see - * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params - * params}. - * - * @param params - * parameters used for the image creation. - * @throws DrawingException - * thrown when there was a problem with drawing a map - */ - public PngImageGenerator(Params params) throws DrawingException { - super(params); - } - - @Override - protected void closeImageObject() { - } - - @Override - public void saveToFileImplementation(String fileName) throws IOException { - FileOutputStream fos = new FileOutputStream(new File(fileName)); - saveToOutputStreamImplementation(fos); - fos.close(); - } - - @Override - public void saveToOutputStreamImplementation(OutputStream os) throws IOException { - ImageIO.write(getBi(), "PNG", os); - } - - @Override - public void savePartToFileImplementation(int x, int y, int width, int height, String fileName) throws IOException { - FileOutputStream fos = new FileOutputStream(new File(fileName)); - savePartToOutputStreamImplementation(x, y, width, height, fos); - fos.close(); - } - - @Override - public void savePartToOutputStreamImplementation(int x, int y, int width, int height, OutputStream os) throws IOException { - BufferedImage tmpBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D tmpGraphics = tmpBI.createGraphics(); - tmpGraphics.drawImage(getBi(), 0, 0, width, height, x, y, x + width, y + width, null); - ImageIO.write(tmpBI, "PNG", os); - } - - @Override - public String getFormatName() { - return "PNG image"; - } - - @Override - public MimeType getMimeType() { - return MimeType.PNG; - } - - @Override - public String getFileExtension() { - return "png"; - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(PngImageGenerator.class); + + /** + * Default constructor. Create an image that is described by params. For more + * information see + * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params + * params}. + * + * @param params + * parameters used for the image creation. + * @throws DrawingException + * thrown when there was a problem with drawing a map + */ + public PngImageGenerator(Params params) throws DrawingException { + super(params); + } + + @Override + protected void closeImageObject() { + } + + @Override + public void saveToFileImplementation(String fileName) throws IOException { + FileOutputStream fos = new FileOutputStream(new File(fileName)); + saveToOutputStreamImplementation(fos); + fos.close(); + } + + @Override + public void saveToOutputStreamImplementation(OutputStream os) throws IOException { + ImageIO.write(getBi(), "PNG", os); + } + + @Override + public void savePartToFileImplementation(int x, int y, int width, int height, String fileName) throws IOException { + FileOutputStream fos = new FileOutputStream(new File(fileName)); + savePartToOutputStreamImplementation(x, y, width, height, fos); + fos.close(); + } + + @Override + public void savePartToOutputStreamImplementation(int x, int y, int width, int height, OutputStream os) + throws IOException { + BufferedImage tmpBI = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); + Graphics2D tmpGraphics = tmpBI.createGraphics(); + tmpGraphics.drawImage(getBi(), 0, 0, width, height, x, y, x + width, y + width, null); + ImageIO.write(tmpBI, "PNG", os); + } + + @Override + public String getFormatName() { + return "PNG image"; + } + + @Override + public MimeType getMimeType() { + return MimeType.PNG; + } + + @Override + public String getFileExtension() { + return "png"; + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/SvgImageGenerator.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/SvgImageGenerator.java index 3ab694582f..def8beed96 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/SvgImageGenerator.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/SvgImageGenerator.java @@ -1,15 +1,10 @@ package lcsb.mapviewer.converter.graphics; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; +import java.io.*; import org.apache.batik.dom.GenericDOMImplementation; import org.apache.batik.svggen.SVGGraphics2D; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; +import org.w3c.dom.*; import lcsb.mapviewer.common.MimeType; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -22,84 +17,86 @@ import lcsb.mapviewer.common.exception.NotImplementedException; * */ public class SvgImageGenerator extends AbstractImageGenerator { - + /** * Root dom element. We need it to be able to provide viewBox. */ private Element root; - @Override - protected void createImageObject(final double width, final double height) { - - // Get a DOMImplementation. - DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); - - // Create an instance of org.w3c.dom.Document. - String svgNS = "http://www.w3.org/2000/svg"; - Document document = domImpl.createDocument(svgNS, "svg", null); - - // Create an instance of the SVG Generator. - SVGGraphics2D graphics =new SVGGraphics2D(document); - root = graphics.getRoot(); - root.setAttributeNS(null, "viewBox", "0 0 "+(int)width+" "+(int)height); - setGraphics(graphics); - - } - - @Override - public void saveToFileImplementation(final String fileName) throws IOException { - saveToOutputStreamImplementation(new FileOutputStream(fileName)); - } - - /** - * Default constructor. Create an image that is described by params. For more - * information see - * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params - * params}. - * - * @param params - * parameters used for the image creation. - * @throws DrawingException - * thrown when there was a problem with drawing a map - */ - public SvgImageGenerator(final Params params) throws DrawingException { - super(params); - } - - @Override - protected void closeImageObject() { - } - - @Override - public void saveToOutputStreamImplementation(OutputStream os) throws IOException { - //for some reason if you remove this line either viewbox is not define or content is not there - ((SVGGraphics2D) getGraphics()).getRoot(root); - ((SVGGraphics2D) getGraphics()).stream(root, new OutputStreamWriter(os)); - } - - @Override - public void savePartToFileImplementation(int x, int y, int width, int height, String fileName) throws IOException { - throw new NotImplementedException("Partial save is not implemented in SVG image generator"); - } - - @Override - public void savePartToOutputStreamImplementation(int x, int y, int width, int height, OutputStream os) throws IOException { - throw new NotImplementedException("Partial save is not implemented in SVG image generator"); - } - - @Override - public String getFormatName() { - return "SVG image"; - } - - @Override - public MimeType getMimeType() { - return MimeType.SVG; - } - - @Override - public String getFileExtension() { - return "svg"; - } + /** + * Default constructor. Create an image that is described by params. For more + * information see + * {@link lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params + * params}. + * + * @param params + * parameters used for the image creation. + * @throws DrawingException + * thrown when there was a problem with drawing a map + */ + public SvgImageGenerator(final Params params) throws DrawingException { + super(params); + } + + @Override + protected void createImageObject(final double width, final double height) { + + // Get a DOMImplementation. + DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); + + // Create an instance of org.w3c.dom.Document. + String svgNS = "http://www.w3.org/2000/svg"; + Document document = domImpl.createDocument(svgNS, "svg", null); + + // Create an instance of the SVG Generator. + SVGGraphics2D graphics = new SVGGraphics2D(document); + root = graphics.getRoot(); + root.setAttributeNS(null, "viewBox", "0 0 " + (int) width + " " + (int) height); + setGraphics(graphics); + + } + + @Override + protected void closeImageObject() { + } + + @Override + public void saveToFileImplementation(final String fileName) throws IOException { + saveToOutputStreamImplementation(new FileOutputStream(fileName)); + } + + @Override + public void saveToOutputStreamImplementation(OutputStream os) throws IOException { + // for some reason if you remove this line either viewbox is not define or + // content is not there + ((SVGGraphics2D) getGraphics()).getRoot(root); + ((SVGGraphics2D) getGraphics()).stream(root, new OutputStreamWriter(os)); + } + + @Override + public void savePartToFileImplementation(int x, int y, int width, int height, String fileName) throws IOException { + throw new NotImplementedException("Partial save is not implemented in SVG image generator"); + } + + @Override + public void savePartToOutputStreamImplementation(int x, int y, int width, int height, OutputStream os) + throws IOException { + throw new NotImplementedException("Partial save is not implemented in SVG image generator"); + } + + @Override + public String getFormatName() { + return "SVG image"; + } + + @Override + public MimeType getMimeType() { + return MimeType.SVG; + } + + @Override + public String getFileExtension() { + return "svg"; + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverter.java index 558e6f9c71..81bb5195e9 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverter.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.converter.graphics.bioEntity; -import java.awt.Graphics2D; +import java.awt.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.SemanticZoomLevelMatcher; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -14,15 +15,8 @@ import lcsb.mapviewer.converter.graphics.DrawingException; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -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.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.species.*; /** * This interface defines what operations should be possible to convert @@ -35,12 +29,16 @@ import lcsb.mapviewer.model.map.species.Species; */ public abstract class BioEntityConverter<T extends BioEntity> { + /** + * Alpha value (0..255) used for visualizing overlay data that are normally + * visualized in javascript. + */ + public static final int LAYOUT_ALPHA = 200; /** * Default class logger. */ @SuppressWarnings("unused") private final Logger logger = LogManager.getLogger(BioEntityConverter.class); - /** * Class that allows to check if element is visible (or transparent) when * drawing. It's used to filter out invisible elements when drawing @@ -48,12 +46,6 @@ public abstract class BioEntityConverter<T extends BioEntity> { */ private SemanticZoomLevelMatcher zoomLevelMatcher = new SemanticZoomLevelMatcher(); - /** - * Alpha value (0..255) used for visualizing overlay data that are normally - * visualized in javascript. - */ - public static final int LAYOUT_ALPHA = 200; - /** * This function draw {@link BioEntity} on the {@link Graphics2D} object. * diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImpl.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImpl.java index e8648ce214..40f9413fa2 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImpl.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImpl.java @@ -1,60 +1,24 @@ package lcsb.mapviewer.converter.graphics.bioEntity; -import java.awt.Graphics2D; +import java.awt.*; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.graphics.ConverterParams; import lcsb.mapviewer.converter.graphics.DrawingException; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.BottomSquareCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.LeftSquareCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.OvalCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.PathwayCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.RightSquareCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.SquareCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.TopSquareCompartmentConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.AntisenseRnaConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.ComplexConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.DegradedConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.DrugConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.GeneConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.IonConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.PhenotypeConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.ProteinConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.RnaConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.SBGNNucleicAcidFeatureConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.SimpleMoleculeConverter; -import lcsb.mapviewer.converter.graphics.bioEntity.element.species.UnknownConverter; +import lcsb.mapviewer.converter.graphics.bioEntity.element.compartment.*; +import lcsb.mapviewer.converter.graphics.bioEntity.element.species.*; import lcsb.mapviewer.converter.graphics.bioEntity.reaction.ReactionConverter; import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.compartment.BottomSquareCompartment; -import lcsb.mapviewer.model.map.compartment.LeftSquareCompartment; -import lcsb.mapviewer.model.map.compartment.OvalCompartment; -import lcsb.mapviewer.model.map.compartment.PathwayCompartment; -import lcsb.mapviewer.model.map.compartment.RightSquareCompartment; -import lcsb.mapviewer.model.map.compartment.SquareCompartment; -import lcsb.mapviewer.model.map.compartment.TopSquareCompartment; +import lcsb.mapviewer.model.map.compartment.*; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.TruncatedProtein; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.modelutils.map.ElementUtils; /** @@ -66,138 +30,119 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class BioEntityConverterImpl extends BioEntityConverter<BioEntity> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(BioEntityConverterImpl.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(BioEntityConverterImpl.class.getName()); + /** + * Converter used for conversion of the {@link Element} given in constructor. + */ + @SuppressWarnings("rawtypes") + private BioEntityConverter elementConverter = null; - /** - * Returns a converter for given element. If converter doesn't exist then - * exception is thrown. - * - * @param element - * {@link Element} for which we are looking for a converter - * @param colorExtractor - * object that helps to convert overlay values into colors - * @return converter that can be applied for the given element - */ - private BioEntityConverter<? extends BioEntity> getConverterForElement(BioEntity element, ColorExtractor colorExtractor) { - if (element == null) { - throw new InvalidArgumentException("element cannot be null"); - } - if (element instanceof GenericProtein) { - return new ProteinConverter(colorExtractor); - } else if (element instanceof IonChannelProtein) { - return new ProteinConverter(colorExtractor); - } else if (element instanceof ReceptorProtein) { - return new ProteinConverter(colorExtractor); - } else if (element instanceof TruncatedProtein) { - return new ProteinConverter(colorExtractor); - } else if (element instanceof Degraded) { - return new DegradedConverter(colorExtractor); - } else if (element instanceof Complex) { - return new ComplexConverter(colorExtractor); - } else if (element instanceof SimpleMolecule) { - return new SimpleMoleculeConverter(colorExtractor); - } else if (element instanceof Drug) { - return new DrugConverter(colorExtractor); - } else if (element instanceof Ion) { - return new IonConverter(colorExtractor); - } else if (element instanceof Phenotype) { - return new PhenotypeConverter(colorExtractor); - } else if (element instanceof Rna) { - return new RnaConverter(colorExtractor); - } else if (element instanceof AntisenseRna) { - return new AntisenseRnaConverter(colorExtractor); - } else if (element instanceof Gene) { - return new GeneConverter(colorExtractor); - } else if (element instanceof Unknown) { - return new UnknownConverter(colorExtractor); - } else if (element instanceof SquareCompartment) { - return new SquareCompartmentConverter(colorExtractor); - } else if (element instanceof OvalCompartment) { - return new OvalCompartmentConverter(colorExtractor); - } else if (element instanceof PathwayCompartment) { - return new PathwayCompartmentConverter(colorExtractor); - } else if (element instanceof BottomSquareCompartment) { - return new BottomSquareCompartmentConverter(colorExtractor); - } else if (element instanceof TopSquareCompartment) { - return new TopSquareCompartmentConverter(colorExtractor); - } else if (element instanceof LeftSquareCompartment) { - return new LeftSquareCompartmentConverter(colorExtractor); - } else if (element instanceof RightSquareCompartment) { - return new RightSquareCompartmentConverter(colorExtractor); - } else if (element instanceof Reaction) { - return new ReactionConverter(colorExtractor); - } else { - throw new NotImplementedException(new ElementUtils().getElementTag(element) + "Unknown element class"); - } - } + /** + * Support constructor. Used in case of SBGN format display + * + * @param element + * {@link Element} for which this converter will be used + * @param colorExtractor + * object that helps to convert overlay values into colors + * @param sbgnFormat + * boolean value indicating if SBGN display format should be used + */ + public BioEntityConverterImpl(final BioEntity element, final boolean sbgnFormat, ColorExtractor colorExtractor) { - /** - * Converter used for conversion of the {@link Element} given in constructor. - */ - @SuppressWarnings("rawtypes") - private BioEntityConverter elementConverter = null; + // If element is a nucleic acid feature to be displayed in SBGN + if (sbgnFormat && (element instanceof AntisenseRna || element instanceof Rna || element instanceof Gene)) { + elementConverter = new SBGNNucleicAcidFeatureConverter(colorExtractor); + } else { + // If not, at the beginning try to find an appropriate converter + elementConverter = getConverterForElement(element, colorExtractor); + } - /** - * Support constructor. Used in case of SBGN format display - * - * @param element - * {@link Element} for which this converter will be used - * @param colorExtractor - * object that helps to convert overlay values into colors - * @param sbgnFormat - * boolean value indicating if SBGN display format should be used - */ - public BioEntityConverterImpl(final BioEntity element, final boolean sbgnFormat, ColorExtractor colorExtractor) { - - // If element is a nucleic acid feature to be displayed in SBGN - if (sbgnFormat && (element instanceof AntisenseRna || element instanceof Rna || element instanceof Gene)) { - elementConverter = new SBGNNucleicAcidFeatureConverter(colorExtractor); - } else { - // If not, at the beginning try to find an appropriate converter - elementConverter = getConverterForElement(element, colorExtractor); - } - - // if we don't know which converter to use then throw an exception - if (elementConverter == null) { - throw new InvalidArgumentException(new ElementUtils().getElementTag(element) + "Unknown converter for class: " + element.getClass()); - } - } - - /** - * Default constructor. - * - * @param colorExtractor - * object that helps to convert overlay values into colors - * @param element - * {@link Element} for which this converter will be used - */ - public BioEntityConverterImpl(final Element element, ColorExtractor colorExtractor) { - this(element, false, colorExtractor); - } + // if we don't know which converter to use then throw an exception + if (elementConverter == null) { + throw new InvalidArgumentException( + new ElementUtils().getElementTag(element) + "Unknown converter for class: " + element.getClass()); + } + } - @SuppressWarnings("unchecked") - @Override - public void drawText(final BioEntity element, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - if (isVisible(element, params)) { - elementConverter.drawText(element, graphics, params); - } - } + /** + * Default constructor. + * + * @param colorExtractor + * object that helps to convert overlay values into colors + * @param element + * {@link Element} for which this converter will be used + */ + public BioEntityConverterImpl(final Element element, ColorExtractor colorExtractor) { + this(element, false, colorExtractor); + } - @SuppressWarnings("unchecked") - @Override - public void draw(BioEntity element, Graphics2D graphics, ConverterParams params, List<ColorSchema> visualizedLayoutsColorSchemas) throws DrawingException { - try { - if (isVisible(element, params)) { - elementConverter.draw(element, graphics, params, visualizedLayoutsColorSchemas); - } - } catch (Exception e) { - throw new DrawingException(new ElementUtils().getElementTag(element) + "Problem with drawing element.", e); - } - } + /** + * Returns a converter for given element. If converter doesn't exist then + * exception is thrown. + * + * @param element + * {@link Element} for which we are looking for a converter + * @param colorExtractor + * object that helps to convert overlay values into colors + * @return converter that can be applied for the given element + */ + private BioEntityConverter<? extends BioEntity> getConverterForElement(BioEntity element, + ColorExtractor colorExtractor) { + if (element == null) { + throw new InvalidArgumentException("element cannot be null"); + } + if (element instanceof GenericProtein) { + return new ProteinConverter(colorExtractor); + } else if (element instanceof IonChannelProtein) { + return new ProteinConverter(colorExtractor); + } else if (element instanceof ReceptorProtein) { + return new ProteinConverter(colorExtractor); + } else if (element instanceof TruncatedProtein) { + return new ProteinConverter(colorExtractor); + } else if (element instanceof Degraded) { + return new DegradedConverter(colorExtractor); + } else if (element instanceof Complex) { + return new ComplexConverter(colorExtractor); + } else if (element instanceof SimpleMolecule) { + return new SimpleMoleculeConverter(colorExtractor); + } else if (element instanceof Drug) { + return new DrugConverter(colorExtractor); + } else if (element instanceof Ion) { + return new IonConverter(colorExtractor); + } else if (element instanceof Phenotype) { + return new PhenotypeConverter(colorExtractor); + } else if (element instanceof Rna) { + return new RnaConverter(colorExtractor); + } else if (element instanceof AntisenseRna) { + return new AntisenseRnaConverter(colorExtractor); + } else if (element instanceof Gene) { + return new GeneConverter(colorExtractor); + } else if (element instanceof Unknown) { + return new UnknownConverter(colorExtractor); + } else if (element instanceof SquareCompartment) { + return new SquareCompartmentConverter(colorExtractor); + } else if (element instanceof OvalCompartment) { + return new OvalCompartmentConverter(colorExtractor); + } else if (element instanceof PathwayCompartment) { + return new PathwayCompartmentConverter(colorExtractor); + } else if (element instanceof BottomSquareCompartment) { + return new BottomSquareCompartmentConverter(colorExtractor); + } else if (element instanceof TopSquareCompartment) { + return new TopSquareCompartmentConverter(colorExtractor); + } else if (element instanceof LeftSquareCompartment) { + return new LeftSquareCompartmentConverter(colorExtractor); + } else if (element instanceof RightSquareCompartment) { + return new RightSquareCompartmentConverter(colorExtractor); + } else if (element instanceof Reaction) { + return new ReactionConverter(colorExtractor); + } else { + throw new NotImplementedException(new ElementUtils().getElementTag(element) + "Unknown element class"); + } + } @SuppressWarnings("unchecked") @Override @@ -205,4 +150,26 @@ public class BioEntityConverterImpl extends BioEntityConverter<BioEntity> { elementConverter.draw(bioEntity, graphics, params); } + @SuppressWarnings("unchecked") + @Override + public void draw(BioEntity element, Graphics2D graphics, ConverterParams params, + List<ColorSchema> visualizedLayoutsColorSchemas) throws DrawingException { + try { + if (isVisible(element, params)) { + elementConverter.draw(element, graphics, params, visualizedLayoutsColorSchemas); + } + } catch (Exception e) { + throw new DrawingException(new ElementUtils().getElementTag(element) + "Problem with drawing element.", e); + } + } + + @SuppressWarnings("unchecked") + @Override + public void drawText(final BioEntity element, final Graphics2D graphics, final ConverterParams params) + throws DrawingException { + if (isVisible(element, params)) { + elementConverter.drawText(element, graphics, params); + } + } + } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/ElementConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/ElementConverter.java index 973cf072fc..440e420986 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/ElementConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/ElementConverter.java @@ -1,7 +1,6 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element; -import java.awt.Graphics2D; -import java.awt.Image; +import java.awt.*; import java.io.ByteArrayInputStream; import java.io.IOException; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/BottomSquareCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/BottomSquareCompartmentConverter.java index 6e5b24fa09..8f67f5ba6e 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/BottomSquareCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/BottomSquareCompartmentConverter.java @@ -1,15 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -27,70 +22,73 @@ import lcsb.mapviewer.model.map.species.Species; */ public class BottomSquareCompartmentConverter extends CompartmentConverter<BottomSquareCompartment> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(BottomSquareCompartmentConverter.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(BottomSquareCompartmentConverter.class.getName()); - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public BottomSquareCompartmentConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public BottomSquareCompartmentConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - @Override - protected void drawImpl(final BottomSquareCompartment compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - // keep the old values of colors and line - Color oldColor = graphics.getColor(); - Stroke oldStroke = graphics.getStroke(); + @Override + protected void drawImpl(final BottomSquareCompartment compartment, final Graphics2D graphics, + final ConverterParams params) throws DrawingException { + // keep the old values of colors and line + Color oldColor = graphics.getColor(); + Stroke oldStroke = graphics.getStroke(); - // create shape of the compartment - Shape s1 = new Line2D.Double(0, compartment.getY(), compartment.getWidth(), compartment.getY()); - Shape s3 = new Line2D.Double(0, compartment.getY() + compartment.getThickness(), compartment.getWidth(), compartment.getY() + compartment.getThickness()); - Area a1 = new Area(new Rectangle2D.Double(0.0, compartment.getY(), compartment.getWidth(), compartment.getHeight())); + // create shape of the compartment + Shape s1 = new Line2D.Double(0, compartment.getY(), compartment.getWidth(), compartment.getY()); + Shape s3 = new Line2D.Double(0, compartment.getY() + compartment.getThickness(), compartment.getWidth(), + compartment.getY() + compartment.getThickness()); + Area a1 = new Area( + new Rectangle2D.Double(0.0, compartment.getY(), compartment.getWidth(), compartment.getHeight())); - Color c1 = compartment.getColor(); - Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); - if (c1.equals(Color.WHITE)) { - c1 = Color.BLACK; - } + Color c1 = compartment.getColor(); + Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); + if (c1.equals(Color.WHITE)) { + c1 = Color.BLACK; + } - // fill the background - boolean fill = !isTransparent(compartment, params); - if (fill) { - graphics.setColor(c1); - } else { - Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); - graphics.setColor(bgAlphaColor); - } - graphics.fill(s1); + // fill the background + boolean fill = !isTransparent(compartment, params); + if (fill) { + graphics.setColor(c1); + } else { + Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); + graphics.setColor(bgAlphaColor); + } + graphics.fill(s1); - // create borders - graphics.setColor(c1); - graphics.setStroke(LineType.SOLID_BOLD.getStroke()); - graphics.draw(s1); - graphics.setStroke(LineType.SOLID.getStroke()); - graphics.draw(s3); - graphics.setColor(c2); - if (fill) { - graphics.fill(a1); - } - // restore color and line type - graphics.setColor(oldColor); - graphics.setStroke(oldStroke); + // create borders + graphics.setColor(c1); + graphics.setStroke(LineType.SOLID_BOLD.getStroke()); + graphics.draw(s1); + graphics.setStroke(LineType.SOLID.getStroke()); + graphics.draw(s3); + graphics.setColor(c2); + if (fill) { + graphics.fill(a1); + } + // restore color and line type + graphics.setColor(oldColor); + graphics.setStroke(oldStroke); - // draw description - if (fill) { - Point2D tmpPoint = compartment.getNamePoint(); - compartment.setNamePoint(compartment.getCenter()); - drawText(compartment, graphics, params); - compartment.setNamePoint(tmpPoint); - } - } + // draw description + if (fill) { + Point2D tmpPoint = compartment.getNamePoint(); + compartment.setNamePoint(compartment.getCenter()); + drawText(compartment, graphics, params); + compartment.setNamePoint(tmpPoint); + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/CompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/CompartmentConverter.java index 99ace59a81..7efa86da7d 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/CompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/CompartmentConverter.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.List; @@ -34,156 +32,154 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public abstract class CompartmentConverter<T extends Compartment> extends ElementConverter<T> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CompartmentConverter.class.getName()); - - /** - * Default font size. - */ - private static final int DEFAULT_FONT_SIZE = 10; - - /** - * Alpha level for inside of the transparent compartments. - */ - public static final int DEFAULT_ALPHA_LEVEL = 8; - - /** - * Class used for transformation of lines. - */ - private LineTransformation lineTransformation = new LineTransformation(); - - /** - * Default alpha level for transparent compartments. - */ - private static int alphaLevel = DEFAULT_ALPHA_LEVEL; - - /** - * Default alpha level for semi-transparent borders. - */ - protected static final int HIGH_ALPHA_LEVEL = 127; - - /** - * Class used for finding place to draw desciption of the compartment. - */ - private PlaceFinder placeFinder; - - /** - * Object used for synchronization when accessing {@link #placeFinder}. - */ - private String placeFinderSynchronization = ""; - - /** - * Object that helps to convert {@link ColorSchema} values into colors. - */ - private ColorExtractor colorExtractor; - - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing elements - * - */ - protected CompartmentConverter(ColorExtractor colorExtractor) { - this.colorExtractor = colorExtractor; - }; - - @Override - public void drawText(final T compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - if (compartment.getWidth() < Configuration.EPSILON || compartment.getHeight() < Configuration.EPSILON) { - throw new DrawingException(new ElementUtils().getElementTag(compartment) + "Dimension of the alias must be bigger than 0."); - } - boolean textCentered = !isTransparent(compartment, params); - Rectangle2D border; - if (textCentered) { - synchronized (placeFinderSynchronization) { - if (placeFinder == null || placeFinder.getModel() != compartment.getModelData()) { - placeFinder = new PlaceFinder(compartment.getModelData().getModel()); - } - border = placeFinder.getRetangle(compartment, params.getLevel()); - } - } else { - border = new Rectangle2D.Double( - compartment.getNamePoint().getX(), compartment.getNamePoint().getY(), - compartment.getWidth() - (compartment.getNamePoint().getX() - compartment.getX()), - compartment.getHeight() - (compartment.getNamePoint().getY() - compartment.getY())); - - } - double fontSize = DEFAULT_FONT_SIZE * params.getScale(); - if (compartment.getFontSize() != null) { - fontSize = compartment.getFontSize() * params.getScale(); - } - String fontName = Font.SANS_SERIF; - try { - fontSize = FontFinder.findMaxFontSize((int) Math.round(fontSize), fontName, graphics, border, compartment.getName()); - FontFinder.drawText((int) fontSize, fontName, graphics, border, compartment.getName(), textCentered); - } catch (RectangleTooSmallException e) { - // if it's too small then don't draw - return; - } - } - - /** - * @return the lineTransformation - */ - protected LineTransformation getLineTransformation() { - return lineTransformation; - } - - /** - * @param lineTransformation - * the lineTransformation to set - */ - protected void setLineTransformation(LineTransformation lineTransformation) { - this.lineTransformation = lineTransformation; - } - - /** - * @return the alphaLevel - */ - public static int getAlphaLevel() { - return alphaLevel; - } - - /** - * @param alphaLevel - * the alphaLevel to set - */ - public static void setAlphaLevel(int alphaLevel) { - CompartmentConverter.alphaLevel = alphaLevel; - } - - @Override - public void draw(T alias, Graphics2D graphics, ConverterParams params, List<ColorSchema> visualizedLayoutsColorSchemas) throws DrawingException { - if (alias.getGlyph() != null) { - drawGlyph(alias, graphics); - } else { - drawImpl(alias, graphics, params); - } - - Color oldColor = graphics.getColor(); - int count = 0; - double width = alias.getWidth() / visualizedLayoutsColorSchemas.size(); - for (ColorSchema schema : visualizedLayoutsColorSchemas) { - if (schema != null) { - double startX = (double) count / (double) visualizedLayoutsColorSchemas.size(); - graphics.setColor(Color.BLACK); - - int x = (int) (startX * alias.getWidth() + alias.getX()); - graphics.drawRect(x, alias.getY().intValue(), (int) width, alias.getHeight().intValue()); - - Color color = colorExtractor.getNormalizedColor(schema); - Color bgAlphaColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), LAYOUT_ALPHA); - graphics.setColor(bgAlphaColor); - graphics.fillRect(x, alias.getY().intValue(), (int) width, alias.getHeight().intValue()); - } - count++; - } - graphics.setColor(oldColor); - } + /** + * Alpha level for inside of the transparent compartments. + */ + public static final int DEFAULT_ALPHA_LEVEL = 8; + /** + * Default alpha level for semi-transparent borders. + */ + protected static final int HIGH_ALPHA_LEVEL = 127; + /** + * Default font size. + */ + private static final int DEFAULT_FONT_SIZE = 10; + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CompartmentConverter.class.getName()); + /** + * Default alpha level for transparent compartments. + */ + private static int alphaLevel = DEFAULT_ALPHA_LEVEL; + /** + * Class used for transformation of lines. + */ + private LineTransformation lineTransformation = new LineTransformation(); + /** + * Class used for finding place to draw desciption of the compartment. + */ + private PlaceFinder placeFinder; + + /** + * Object used for synchronization when accessing {@link #placeFinder}. + */ + private String placeFinderSynchronization = ""; + + /** + * Object that helps to convert {@link ColorSchema} values into colors. + */ + private ColorExtractor colorExtractor; + + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing elements + * + */ + protected CompartmentConverter(ColorExtractor colorExtractor) { + this.colorExtractor = colorExtractor; + }; + + /** + * @return the alphaLevel + */ + public static int getAlphaLevel() { + return alphaLevel; + } + + /** + * @param alphaLevel + * the alphaLevel to set + */ + public static void setAlphaLevel(int alphaLevel) { + CompartmentConverter.alphaLevel = alphaLevel; + } + + /** + * @return the lineTransformation + */ + protected LineTransformation getLineTransformation() { + return lineTransformation; + } + + /** + * @param lineTransformation + * the lineTransformation to set + */ + protected void setLineTransformation(LineTransformation lineTransformation) { + this.lineTransformation = lineTransformation; + } + + @Override + public void draw(T alias, Graphics2D graphics, ConverterParams params, + List<ColorSchema> visualizedLayoutsColorSchemas) throws DrawingException { + if (alias.getGlyph() != null) { + drawGlyph(alias, graphics); + } else { + drawImpl(alias, graphics, params); + } + + Color oldColor = graphics.getColor(); + int count = 0; + double width = alias.getWidth() / visualizedLayoutsColorSchemas.size(); + for (ColorSchema schema : visualizedLayoutsColorSchemas) { + if (schema != null) { + double startX = (double) count / (double) visualizedLayoutsColorSchemas.size(); + graphics.setColor(Color.BLACK); + + int x = (int) (startX * alias.getWidth() + alias.getX()); + graphics.drawRect(x, alias.getY().intValue(), (int) width, alias.getHeight().intValue()); + + Color color = colorExtractor.getNormalizedColor(schema); + Color bgAlphaColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), LAYOUT_ALPHA); + graphics.setColor(bgAlphaColor); + graphics.fillRect(x, alias.getY().intValue(), (int) width, alias.getHeight().intValue()); + } + count++; + } + graphics.setColor(oldColor); + } + + @Override + public void drawText(final T compartment, final Graphics2D graphics, final ConverterParams params) + throws DrawingException { + if (compartment.getWidth() < Configuration.EPSILON || compartment.getHeight() < Configuration.EPSILON) { + throw new DrawingException( + new ElementUtils().getElementTag(compartment) + "Dimension of the alias must be bigger than 0."); + } + boolean textCentered = !isTransparent(compartment, params); + Rectangle2D border; + if (textCentered) { + synchronized (placeFinderSynchronization) { + if (placeFinder == null || placeFinder.getModel() != compartment.getModelData()) { + placeFinder = new PlaceFinder(compartment.getModelData().getModel()); + } + border = placeFinder.getRetangle(compartment, params.getLevel()); + } + } else { + border = new Rectangle2D.Double( + compartment.getNamePoint().getX(), compartment.getNamePoint().getY(), + compartment.getWidth() - (compartment.getNamePoint().getX() - compartment.getX()), + compartment.getHeight() - (compartment.getNamePoint().getY() - compartment.getY())); + + } + double fontSize = DEFAULT_FONT_SIZE * params.getScale(); + if (compartment.getFontSize() != null) { + fontSize = compartment.getFontSize() * params.getScale(); + } + String fontName = Font.SANS_SERIF; + try { + fontSize = FontFinder.findMaxFontSize((int) Math.round(fontSize), fontName, graphics, border, + compartment.getName()); + FontFinder.drawText((int) fontSize, fontName, graphics, border, compartment.getName(), textCentered); + } catch (RectangleTooSmallException e) { + // if it's too small then don't draw + return; + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/LeftSquareCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/LeftSquareCompartmentConverter.java index 7ec656b2e1..b33f237530 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/LeftSquareCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/LeftSquareCompartmentConverter.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -16,8 +13,6 @@ import lcsb.mapviewer.model.graphics.LineType; import lcsb.mapviewer.model.map.compartment.LeftSquareCompartment; import lcsb.mapviewer.model.map.layout.ColorSchema; -import org.apache.logging.log4j.*; - /** * Class responsible for drawing LeftSquareCompartment on the Graphics2D. * @@ -26,73 +21,75 @@ import org.apache.logging.log4j.*; */ public class LeftSquareCompartmentConverter extends CompartmentConverter<LeftSquareCompartment> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(LeftSquareCompartmentConverter.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(LeftSquareCompartmentConverter.class.getName()); - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing elements - * - */ - public LeftSquareCompartmentConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing elements + * + */ + public LeftSquareCompartmentConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - @Override - protected void drawImpl(final LeftSquareCompartment compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - // keep the old values of color and line type - Color oldColor = graphics.getColor(); - Stroke oldStroke = graphics.getStroke(); + @Override + protected void drawImpl(final LeftSquareCompartment compartment, final Graphics2D graphics, + final ConverterParams params) throws DrawingException { + // keep the old values of color and line type + Color oldColor = graphics.getColor(); + Stroke oldStroke = graphics.getStroke(); - // create shape of the compartment - Shape s1 = new Line2D.Double(compartment.getWidth(), compartment.getHeight(), compartment.getWidth(), 0); - Shape s3 = new Line2D.Double( - compartment.getWidth() - compartment.getThickness(), 0, compartment.getWidth() - compartment.getThickness(), compartment.getHeight()); - Area a1 = new Area(new Rectangle2D.Double(0.0, 0.0, compartment.getWidth(), compartment.getHeight())); + // create shape of the compartment + Shape s1 = new Line2D.Double(compartment.getWidth(), compartment.getHeight(), compartment.getWidth(), 0); + Shape s3 = new Line2D.Double( + compartment.getWidth() - compartment.getThickness(), 0, compartment.getWidth() - compartment.getThickness(), + compartment.getHeight()); + Area a1 = new Area(new Rectangle2D.Double(0.0, 0.0, compartment.getWidth(), compartment.getHeight())); - Color c1 = compartment.getColor(); - Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); - if (c1.equals(Color.WHITE)) { - c1 = Color.BLACK; - } + Color c1 = compartment.getColor(); + Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); + if (c1.equals(Color.WHITE)) { + c1 = Color.BLACK; + } - // fill the background - boolean fill = !isTransparent(compartment, params); - if (fill) { - graphics.setColor(c1); - } else { - Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); - graphics.setColor(bgAlphaColor); - } - graphics.fill(s1); + // fill the background + boolean fill = !isTransparent(compartment, params); + if (fill) { + graphics.setColor(c1); + } else { + Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); + graphics.setColor(bgAlphaColor); + } + graphics.fill(s1); - // create borders - graphics.setColor(c1); - graphics.setStroke(LineType.SOLID_BOLD.getStroke()); - graphics.draw(s1); - graphics.setStroke(LineType.SOLID.getStroke()); - graphics.draw(s3); - graphics.setColor(c2); - if (fill) { - graphics.fill(a1); - } + // create borders + graphics.setColor(c1); + graphics.setStroke(LineType.SOLID_BOLD.getStroke()); + graphics.draw(s1); + graphics.setStroke(LineType.SOLID.getStroke()); + graphics.draw(s3); + graphics.setColor(c2); + if (fill) { + graphics.fill(a1); + } - // restore color and line type - graphics.setColor(oldColor); - graphics.setStroke(oldStroke); + // restore color and line type + graphics.setColor(oldColor); + graphics.setStroke(oldStroke); - // draw description - if (fill) { - Point2D tmpPoint = compartment.getNamePoint(); - compartment.setNamePoint(compartment.getCenter()); - drawText(compartment, graphics, params); - compartment.setNamePoint(tmpPoint); - } - } + // draw description + if (fill) { + Point2D tmpPoint = compartment.getNamePoint(); + compartment.setNamePoint(compartment.getCenter()); + drawText(compartment, graphics, params); + compartment.setNamePoint(tmpPoint); + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/OvalCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/OvalCompartmentConverter.java index d52073e682..9732dffbf7 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/OvalCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/OvalCompartmentConverter.java @@ -1,12 +1,7 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Point2D; +import java.awt.*; +import java.awt.geom.*; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -25,83 +20,85 @@ import lcsb.mapviewer.model.map.species.Species; */ public class OvalCompartmentConverter extends CompartmentConverter<OvalCompartment> { - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public OvalCompartmentConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public OvalCompartmentConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - /** - * Returns shape representing alias. - * - * @param compartment - * alias for which we are looking for a Shape - * @return Shape object that represents alias - */ - private Shape getShape(final Compartment compartment) { - return new Ellipse2D.Double(compartment.getX(), compartment.getY(), compartment.getWidth(), compartment.getHeight()); - } + /** + * Returns shape representing alias. + * + * @param compartment + * alias for which we are looking for a Shape + * @return Shape object that represents alias + */ + private Shape getShape(final Compartment compartment) { + return new Ellipse2D.Double(compartment.getX(), compartment.getY(), compartment.getWidth(), + compartment.getHeight()); + } - @Override - protected void drawImpl(final OvalCompartment compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - // keep the old values of color and line type - Color oldColor = graphics.getColor(); - Stroke oldStroke = graphics.getStroke(); + @Override + protected void drawImpl(final OvalCompartment compartment, final Graphics2D graphics, final ConverterParams params) + throws DrawingException { + // keep the old values of color and line type + Color oldColor = graphics.getColor(); + Stroke oldStroke = graphics.getStroke(); - // create shape of the compartment - Shape s1 = getShape(compartment); - compartment.increaseBorder(-compartment.getThickness()); - Shape s3 = getShape(compartment); - compartment.increaseBorder(compartment.getThickness()); + // create shape of the compartment + Shape s1 = getShape(compartment); + compartment.increaseBorder(-compartment.getThickness()); + Shape s3 = getShape(compartment); + compartment.increaseBorder(compartment.getThickness()); - Color c1 = compartment.getColor(); - Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); - if (c1.equals(Color.WHITE)) { - c1 = Color.BLACK; - } + Color c1 = compartment.getColor(); + Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); + if (c1.equals(Color.WHITE)) { + c1 = Color.BLACK; + } - Area a1 = new Area(s1); - a1.subtract(new Area(s3)); + Area a1 = new Area(s1); + a1.subtract(new Area(s3)); - // fill the background - boolean fill = !isTransparent(compartment, params); - if (fill) { - graphics.setColor(c1); - } else { - Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); - graphics.setColor(bgAlphaColor); - } - graphics.fill(s1); + // fill the background + boolean fill = !isTransparent(compartment, params); + if (fill) { + graphics.setColor(c1); + } else { + Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); + graphics.setColor(bgAlphaColor); + } + graphics.fill(s1); - // create borders - graphics.setColor(c1); - graphics.setStroke(LineType.SOLID_BOLD.getStroke()); - graphics.draw(s1); - graphics.setStroke(LineType.SOLID.getStroke()); - graphics.draw(s3); - graphics.setColor(c2); - graphics.fill(a1); + // create borders + graphics.setColor(c1); + graphics.setStroke(LineType.SOLID_BOLD.getStroke()); + graphics.draw(s1); + graphics.setStroke(LineType.SOLID.getStroke()); + graphics.draw(s3); + graphics.setColor(c2); + graphics.fill(a1); - // restore color and line type - graphics.setColor(oldColor); - graphics.setStroke(oldStroke); + // restore color and line type + graphics.setColor(oldColor); + graphics.setStroke(oldStroke); - // draw description - if (fill) { - Point2D tmpPoint = compartment.getNamePoint(); - compartment.setNamePoint(compartment.getCenter()); - drawText(compartment, graphics, params); - compartment.setNamePoint(tmpPoint); - } else { - if (!compartment.containsIdenticalSpecies()) { - drawText(compartment, graphics, params); - } - } - } + // draw description + if (fill) { + Point2D tmpPoint = compartment.getNamePoint(); + compartment.setNamePoint(compartment.getCenter()); + drawText(compartment, graphics, params); + compartment.setNamePoint(tmpPoint); + } else { + if (!compartment.containsIdenticalSpecies()) { + drawText(compartment, graphics, params); + } + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverter.java index 87bcb8fb02..b2741dec63 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverter.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; +import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/RightSquareCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/RightSquareCompartmentConverter.java index 07cbf55467..53bf786fe9 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/RightSquareCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/RightSquareCompartmentConverter.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -17,8 +14,6 @@ import lcsb.mapviewer.model.map.compartment.RightSquareCompartment; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.species.Species; -import org.apache.logging.log4j.*; - /** * Class responsible for drawing RightSquareCompartment on the Graphics2D. * @@ -27,77 +22,80 @@ import org.apache.logging.log4j.*; */ public class RightSquareCompartmentConverter extends CompartmentConverter<RightSquareCompartment> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(RightSquareCompartmentConverter.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(RightSquareCompartmentConverter.class.getName()); - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public RightSquareCompartmentConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public RightSquareCompartmentConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - @Override - protected void drawImpl(final RightSquareCompartment compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - // keep the old values of color and line type - Color oldColor = graphics.getColor(); - Stroke oldStroke = graphics.getStroke(); + @Override + protected void drawImpl(final RightSquareCompartment compartment, final Graphics2D graphics, + final ConverterParams params) throws DrawingException { + // keep the old values of color and line type + Color oldColor = graphics.getColor(); + Stroke oldStroke = graphics.getStroke(); - // create shape of the compartment - Shape s1 = new Line2D.Double(compartment.getX(), compartment.getHeight(), compartment.getX(), 0); - Shape s3 = new Line2D.Double(compartment.getX() + compartment.getThickness(), compartment.getHeight(), compartment.getX(), 0); - Area a1 = new Area(new Rectangle2D.Double(compartment.getX(), 0.0, compartment.getWidth(), compartment.getHeight())); + // create shape of the compartment + Shape s1 = new Line2D.Double(compartment.getX(), compartment.getHeight(), compartment.getX(), 0); + Shape s3 = new Line2D.Double(compartment.getX() + compartment.getThickness(), compartment.getHeight(), + compartment.getX(), 0); + Area a1 = new Area( + new Rectangle2D.Double(compartment.getX(), 0.0, compartment.getWidth(), compartment.getHeight())); - Color c1 = compartment.getColor(); - Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); - if (c1.equals(Color.WHITE)) { - c1 = Color.BLACK; - } + Color c1 = compartment.getColor(); + Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); + if (c1.equals(Color.WHITE)) { + c1 = Color.BLACK; + } - // fill the background - boolean fill = !isTransparent(compartment, params); - if (fill) { - graphics.setColor(c1); - } else { - Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); - graphics.setColor(bgAlphaColor); - } - graphics.fill(s1); + // fill the background + boolean fill = !isTransparent(compartment, params); + if (fill) { + graphics.setColor(c1); + } else { + Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); + graphics.setColor(bgAlphaColor); + } + graphics.fill(s1); - // create borders - graphics.setColor(c1); - graphics.setStroke(LineType.SOLID_BOLD.getStroke()); - graphics.draw(s1); - graphics.setStroke(LineType.SOLID.getStroke()); - graphics.draw(s3); - graphics.setColor(c2); - if (fill) { - graphics.fill(a1); - } - // restore color and line type - graphics.setColor(oldColor); - graphics.setStroke(oldStroke); + // create borders + graphics.setColor(c1); + graphics.setStroke(LineType.SOLID_BOLD.getStroke()); + graphics.draw(s1); + graphics.setStroke(LineType.SOLID.getStroke()); + graphics.draw(s3); + graphics.setColor(c2); + if (fill) { + graphics.fill(a1); + } + // restore color and line type + graphics.setColor(oldColor); + graphics.setStroke(oldStroke); - // three lines below are only temporary fix... - double x = compartment.getNamePoint().getX() - compartment.getX(); - double y = compartment.getNamePoint().getY(); - compartment.getNamePoint().setLocation(x, y); + // three lines below are only temporary fix... + double x = compartment.getNamePoint().getX() - compartment.getX(); + double y = compartment.getNamePoint().getY(); + compartment.getNamePoint().setLocation(x, y); - // draw description - if (fill) { - Point2D tmpPoint = compartment.getNamePoint(); - compartment.setNamePoint(compartment.getCenter()); - drawText(compartment, graphics, params); - compartment.setNamePoint(tmpPoint); - } - x += compartment.getX(); - compartment.getNamePoint().setLocation(x, y); - } + // draw description + if (fill) { + Point2D tmpPoint = compartment.getNamePoint(); + compartment.setNamePoint(compartment.getCenter()); + drawText(compartment, graphics, params); + compartment.setNamePoint(tmpPoint); + } + x += compartment.getX(); + compartment.getNamePoint().setLocation(x, y); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/SquareCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/SquareCompartmentConverter.java index 28a135e7ac..f7b4fb6127 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/SquareCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/SquareCompartmentConverter.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Point2D; -import java.awt.geom.RoundRectangle2D; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -26,90 +22,92 @@ import lcsb.mapviewer.model.map.species.Species; * */ public class SquareCompartmentConverter extends CompartmentConverter<SquareCompartment> { - /** - * How big is the arc in the corner of rectangle that represents square - * compartment. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 20; - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(SquareCompartmentConverter.class.getName()); + /** + * How big is the arc in the corner of rectangle that represents square + * compartment. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 20; + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(SquareCompartmentConverter.class.getName()); - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public SquareCompartmentConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public SquareCompartmentConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - /** - * Returns shape representing compartment. - * - * @param compartment - * compartment for which we are looking for a {@link Shape} - * @return {@link Shape} object that represents compartment - */ - private Shape getShape(final Compartment compartment) { - return new RoundRectangle2D.Double( - compartment.getX(), compartment.getY(), compartment.getWidth(), compartment.getHeight(), RECTANGLE_CORNER_ARC_SIZE, RECTANGLE_CORNER_ARC_SIZE); - } + /** + * Returns shape representing compartment. + * + * @param compartment + * compartment for which we are looking for a {@link Shape} + * @return {@link Shape} object that represents compartment + */ + private Shape getShape(final Compartment compartment) { + return new RoundRectangle2D.Double( + compartment.getX(), compartment.getY(), compartment.getWidth(), compartment.getHeight(), + RECTANGLE_CORNER_ARC_SIZE, RECTANGLE_CORNER_ARC_SIZE); + } - @Override - protected void drawImpl(final SquareCompartment compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - // keep the old values of color and line type - Color oldColor = graphics.getColor(); - Stroke oldStroke = graphics.getStroke(); + @Override + protected void drawImpl(final SquareCompartment compartment, final Graphics2D graphics, final ConverterParams params) + throws DrawingException { + // keep the old values of color and line type + Color oldColor = graphics.getColor(); + Stroke oldStroke = graphics.getStroke(); - // create shape of the compartment - Shape s1 = getShape(compartment); - compartment.increaseBorder(-compartment.getThickness()); - Shape s3 = getShape(compartment); - compartment.increaseBorder(compartment.getThickness()); + // create shape of the compartment + Shape s1 = getShape(compartment); + compartment.increaseBorder(-compartment.getThickness()); + Shape s3 = getShape(compartment); + compartment.increaseBorder(compartment.getThickness()); - Color c1 = compartment.getColor(); - Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); - if (c1.equals(Color.WHITE)) { - c1 = Color.BLACK; - } + Color c1 = compartment.getColor(); + Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); + if (c1.equals(Color.WHITE)) { + c1 = Color.BLACK; + } - Area a1 = new Area(s1); - a1.subtract(new Area(s3)); + Area a1 = new Area(s1); + a1.subtract(new Area(s3)); - // fill the background - boolean fill = !isTransparent(compartment, params); - if (fill) { - graphics.setColor(c1); - } else { - Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); - graphics.setColor(bgAlphaColor); - } - graphics.fill(s1); + // fill the background + boolean fill = !isTransparent(compartment, params); + if (fill) { + graphics.setColor(c1); + } else { + Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); + graphics.setColor(bgAlphaColor); + } + graphics.fill(s1); - // create borders - graphics.setColor(c1); - graphics.setStroke(LineType.SOLID_BOLD.getStroke()); - graphics.draw(s1); - graphics.setStroke(LineType.SOLID.getStroke()); - graphics.draw(s3); - graphics.setColor(c2); - graphics.fill(a1); + // create borders + graphics.setColor(c1); + graphics.setStroke(LineType.SOLID_BOLD.getStroke()); + graphics.draw(s1); + graphics.setStroke(LineType.SOLID.getStroke()); + graphics.draw(s3); + graphics.setColor(c2); + graphics.fill(a1); - // restore color and line type - graphics.setColor(oldColor); - graphics.setStroke(oldStroke); + // restore color and line type + graphics.setColor(oldColor); + graphics.setStroke(oldStroke); - // draw description - if (fill) { - Point2D tmpPoint = compartment.getNamePoint(); - compartment.setNamePoint(compartment.getCenter()); - drawText(compartment, graphics, params); - compartment.setNamePoint(tmpPoint); - } - } + // draw description + if (fill) { + Point2D tmpPoint = compartment.getNamePoint(); + compartment.setNamePoint(compartment.getCenter()); + drawText(compartment, graphics, params); + compartment.setNamePoint(tmpPoint); + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/TopSquareCompartmentConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/TopSquareCompartmentConverter.java index fb9f79783f..f24d5b112a 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/TopSquareCompartmentConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/TopSquareCompartmentConverter.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -17,8 +14,6 @@ import lcsb.mapviewer.model.map.compartment.TopSquareCompartment; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.species.Species; -import org.apache.logging.log4j.*; - /** * Class responsible for drawing TopSquareCompartment on the {@link Graphics2D}. * @@ -27,68 +22,70 @@ import org.apache.logging.log4j.*; */ public class TopSquareCompartmentConverter extends CompartmentConverter<TopSquareCompartment> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(TopSquareCompartmentConverter.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(TopSquareCompartmentConverter.class.getName()); - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public TopSquareCompartmentConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public TopSquareCompartmentConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - @Override - protected void drawImpl(final TopSquareCompartment compartment, final Graphics2D graphics, final ConverterParams params) throws DrawingException { - Color oldColor = graphics.getColor(); - Stroke oldStroke = graphics.getStroke(); + @Override + protected void drawImpl(final TopSquareCompartment compartment, final Graphics2D graphics, + final ConverterParams params) throws DrawingException { + Color oldColor = graphics.getColor(); + Stroke oldStroke = graphics.getStroke(); - Shape s1 = new Line2D.Double(0, compartment.getHeight(), compartment.getWidth(), compartment.getHeight()); - Shape s3 = new Line2D.Double( - 0, compartment.getHeight() - compartment.getThickness(), compartment.getWidth(), compartment.getHeight() - compartment.getThickness()); - Area a1 = new Area(new Rectangle2D.Double(0.0, 0.0, compartment.getWidth(), compartment.getHeight())); + Shape s1 = new Line2D.Double(0, compartment.getHeight(), compartment.getWidth(), compartment.getHeight()); + Shape s3 = new Line2D.Double( + 0, compartment.getHeight() - compartment.getThickness(), compartment.getWidth(), + compartment.getHeight() - compartment.getThickness()); + Area a1 = new Area(new Rectangle2D.Double(0.0, 0.0, compartment.getWidth(), compartment.getHeight())); - Color c1 = compartment.getColor(); - Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); - if (c1.equals(Color.WHITE)) { - c1 = Color.BLACK; - } + Color c1 = compartment.getColor(); + Color c2 = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), HIGH_ALPHA_LEVEL); + if (c1.equals(Color.WHITE)) { + c1 = Color.BLACK; + } - // fill the background - boolean fill = !isTransparent(compartment, params); - if (fill) { - graphics.setColor(c1); - } else { - Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); - graphics.setColor(bgAlphaColor); - } - graphics.fill(s1); + // fill the background + boolean fill = !isTransparent(compartment, params); + if (fill) { + graphics.setColor(c1); + } else { + Color bgAlphaColor = new Color(c1.getRed(), c1.getGreen(), c1.getBlue(), getAlphaLevel()); + graphics.setColor(bgAlphaColor); + } + graphics.fill(s1); - graphics.setColor(c1); - graphics.setStroke(LineType.SOLID_BOLD.getStroke()); - graphics.draw(s1); - graphics.setStroke(LineType.SOLID.getStroke()); - graphics.draw(s3); - graphics.setColor(c2); - if (fill) { - graphics.fill(a1); - } + graphics.setColor(c1); + graphics.setStroke(LineType.SOLID_BOLD.getStroke()); + graphics.draw(s1); + graphics.setStroke(LineType.SOLID.getStroke()); + graphics.draw(s3); + graphics.setColor(c2); + if (fill) { + graphics.fill(a1); + } - // restore color and line type - graphics.setColor(oldColor); - graphics.setStroke(oldStroke); - // draw description - if (fill) { - Point2D tmpPoint = compartment.getNamePoint(); - compartment.setNamePoint(compartment.getCenter()); - drawText(compartment, graphics, params); - compartment.setNamePoint(tmpPoint); - } - } + // restore color and line type + graphics.setColor(oldColor); + graphics.setStroke(oldStroke); + // draw description + if (fill) { + Point2D tmpPoint = compartment.getNamePoint(); + compartment.setNamePoint(compartment.getCenter()); + drawText(compartment, graphics, params); + compartment.setNamePoint(tmpPoint); + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/package-info.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/package-info.java index cda3756654..157e0c61eb 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/package-info.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/package-info.java @@ -1,5 +1,5 @@ /** - * Provides classes that draws different implemention of - * {@link Compartment} on the {@link Graphics2D}. + * Provides classes that draws different implemention of {@link Compartment} on + * the {@link Graphics2D}. */ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/AntisenseRnaConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/AntisenseRnaConverter.java index df69b75fdd..1acd6b1f19 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/AntisenseRnaConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/AntisenseRnaConverter.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverter.java index 7d1ec5191d..5f523dfa78 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverter.java @@ -1,15 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -163,9 +158,14 @@ public class ComplexConverter extends SpeciesConverter<Complex> { } } + @Override + public PathIterator getBoundPathIterator(final Complex complex) { + return getAliasPath(complex).getPathIterator(new AffineTransform()); + } + /** * Returns the border of {@link Complex}. - * + * * @param complex * exact object for which we want to get a border * @return border of the {@link Complex} @@ -183,9 +183,4 @@ public class ComplexConverter extends SpeciesConverter<Complex> { path.closePath(); return path; } - - @Override - public PathIterator getBoundPathIterator(final Complex complex) { - return getAliasPath(complex).getPathIterator(new AffineTransform()); - } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DegradedConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DegradedConverter.java index 3d0c456e88..888cd469a5 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DegradedConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DegradedConverter.java @@ -1,15 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.Area; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.exception.InvalidStateException; @@ -26,110 +21,110 @@ import lcsb.mapviewer.model.map.species.Species; * */ public class DegradedConverter extends SpeciesConverter<Degraded> { - /** - * Part of height of the line used to cross degraded circle that goes behind - * this circle. - */ - private static final int CROSS_LINE_EXTENDED_LENGTH = 7; - - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(DegradedConverter.class.getName()); - - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public DegradedConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } - - @Override - protected void drawImpl(final Degraded degraded, final Graphics2D graphics, final ConverterParams params) { - double diameter = getDiameter(degraded); - double x = getXCoord(degraded, diameter); - double y = getYCoord(degraded); - Area a1 = new Area(new Ellipse2D.Double(x, y, diameter, diameter)); - - double lineX1 = degraded.getX() + degraded.getWidth() / 2 + CROSS_LINE_EXTENDED_LENGTH; - double lineY1 = degraded.getY(); - - double lineX2 = degraded.getX() + degraded.getWidth() / 2 - CROSS_LINE_EXTENDED_LENGTH; - double lineY2 = degraded.getY() + diameter + 2 * CROSS_LINE_EXTENDED_LENGTH; - - GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD, 2); - path.moveTo(lineX1, lineY1); - path.lineTo(lineX1 + 1, lineY1); - path.lineTo(lineX2 + 1, lineY2); - path.lineTo(lineX2, lineY2); - path.closePath(); - - a1.exclusiveOr(new Area(path)); - Color c = graphics.getColor(); - graphics.setColor(degraded.getColor()); - graphics.fill(a1); - graphics.setColor(c); - Stroke stroke = graphics.getStroke(); - graphics.setStroke(getBorderLine(degraded)); - graphics.draw(a1); - graphics.setStroke(stroke); - drawText(degraded, graphics, params); - } - - /** - * Returns transformed y coordinate for the {@link Degraded} bioentity. - * - * @param degraded - * {@link Degraded} to to which we are looking for y coordinate - * @return y coordinate of the alias - */ - private double getYCoord(final Degraded degraded) { - double y = degraded.getY() + CROSS_LINE_EXTENDED_LENGTH; - return y; - } - - /** - * Returns transformed x coordinate for the degraded alias. - * - * @param degraded - * object alias to to which we are looking for x coordinate - * @param diameter - * diameter of cross line used in this alias - * @return x coordinate of the {@link Degraded} bioentity. - */ - private double getXCoord(final Degraded degraded, final double diameter) { - double x = degraded.getX() + (degraded.getWidth() - diameter) / 2; - return x; - } - - /** - * Computes diameter of cross line for the degraded alias. - * - * @param degraded - * object alias to to which we are looking for diameter. - * @return diameter of the cross line - */ - private double getDiameter(final Degraded degraded) { - double diameter = Math.min(degraded.getWidth(), degraded.getHeight()) - 2 * CROSS_LINE_EXTENDED_LENGTH; - if (diameter < 0) { - logger.warn("Diameter cannot be negative..."); - diameter = 0; - } - return diameter; - } - - @Override - public String getText(Degraded degraded) { - return ""; - } - - @Override - public PathIterator getBoundPathIterator(Degraded degraded) { - throw new InvalidStateException("This class doesn't have bound"); - } + /** + * Part of height of the line used to cross degraded circle that goes behind + * this circle. + */ + private static final int CROSS_LINE_EXTENDED_LENGTH = 7; + + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(DegradedConverter.class.getName()); + + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public DegradedConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } + + @Override + protected void drawImpl(final Degraded degraded, final Graphics2D graphics, final ConverterParams params) { + double diameter = getDiameter(degraded); + double x = getXCoord(degraded, diameter); + double y = getYCoord(degraded); + Area a1 = new Area(new Ellipse2D.Double(x, y, diameter, diameter)); + + double lineX1 = degraded.getX() + degraded.getWidth() / 2 + CROSS_LINE_EXTENDED_LENGTH; + double lineY1 = degraded.getY(); + + double lineX2 = degraded.getX() + degraded.getWidth() / 2 - CROSS_LINE_EXTENDED_LENGTH; + double lineY2 = degraded.getY() + diameter + 2 * CROSS_LINE_EXTENDED_LENGTH; + + GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD, 2); + path.moveTo(lineX1, lineY1); + path.lineTo(lineX1 + 1, lineY1); + path.lineTo(lineX2 + 1, lineY2); + path.lineTo(lineX2, lineY2); + path.closePath(); + + a1.exclusiveOr(new Area(path)); + Color c = graphics.getColor(); + graphics.setColor(degraded.getColor()); + graphics.fill(a1); + graphics.setColor(c); + Stroke stroke = graphics.getStroke(); + graphics.setStroke(getBorderLine(degraded)); + graphics.draw(a1); + graphics.setStroke(stroke); + drawText(degraded, graphics, params); + } + + /** + * Returns transformed y coordinate for the {@link Degraded} bioentity. + * + * @param degraded + * {@link Degraded} to to which we are looking for y coordinate + * @return y coordinate of the alias + */ + private double getYCoord(final Degraded degraded) { + double y = degraded.getY() + CROSS_LINE_EXTENDED_LENGTH; + return y; + } + + /** + * Returns transformed x coordinate for the degraded alias. + * + * @param degraded + * object alias to to which we are looking for x coordinate + * @param diameter + * diameter of cross line used in this alias + * @return x coordinate of the {@link Degraded} bioentity. + */ + private double getXCoord(final Degraded degraded, final double diameter) { + double x = degraded.getX() + (degraded.getWidth() - diameter) / 2; + return x; + } + + /** + * Computes diameter of cross line for the degraded alias. + * + * @param degraded + * object alias to to which we are looking for diameter. + * @return diameter of the cross line + */ + private double getDiameter(final Degraded degraded) { + double diameter = Math.min(degraded.getWidth(), degraded.getHeight()) - 2 * CROSS_LINE_EXTENDED_LENGTH; + if (diameter < 0) { + logger.warn("Diameter cannot be negative..."); + diameter = 0; + } + return diameter; + } + + @Override + public String getText(Degraded degraded) { + return ""; + } + + @Override + public PathIterator getBoundPathIterator(Degraded degraded) { + throw new InvalidStateException("This class doesn't have bound"); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DrugConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DrugConverter.java index b737c0071d..3d59e03818 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DrugConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/DrugConverter.java @@ -1,16 +1,11 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.RoundRectangle2D; +import java.awt.*; +import java.awt.geom.*; import java.util.ArrayList; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -27,96 +22,98 @@ import lcsb.mapviewer.model.map.species.Species; */ public class DrugConverter extends SpeciesConverter<Drug> { - /** - * Distance between internal and external border of drug graphical - * representation. - */ - private static final int OFFSET_BETWEEN_BORDERS = 4; - - /** - * How big should be the arc in rectangle for drug representation. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 40; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(DrugConverter.class.getName()); - - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public DrugConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } - - /** - * Returns shape of the Drug . - * - * @param drug - * {@link Drug} for which we are looking for a border - * @return Shape object defining given alias - */ - private Shape getDrugShape(final Drug drug) { - return new RoundRectangle2D.Double(drug.getX(), drug.getY(), drug.getWidth(), drug.getHeight(), RECTANGLE_CORNER_ARC_SIZE, RECTANGLE_CORNER_ARC_SIZE); - } - - @Override - protected void drawImpl(Drug drug, final Graphics2D graphics, final ConverterParams params) { - Shape a1 = getDrugShape(drug); - double offset = OFFSET_BETWEEN_BORDERS; - Shape a2 = new RoundRectangle2D.Double( - drug.getX() + offset, drug.getY() + offset, drug.getWidth() - 2 * offset, drug.getHeight() - 2 * offset, RECTANGLE_CORNER_ARC_SIZE, - RECTANGLE_CORNER_ARC_SIZE); - Color c = graphics.getColor(); - graphics.setColor(drug.getColor()); - graphics.fill(a1); - graphics.setColor(c); - Stroke stroke = graphics.getStroke(); - graphics.setStroke(getBorderLine(drug)); - graphics.draw(a1); - graphics.draw(a2); - graphics.setStroke(stroke); - drawText(drug, graphics, params); - } - - /** - * Returns shape of the {@link Drug} as a list of points. - * - * @param drug - * {@link Drug} for which we are looking for a border - * @return list of points defining border of the given {@link Drug} - */ - protected ArrayList<Point2D> getDrugPoints(final Drug drug) { - ArrayList<Point2D> list = new ArrayList<Point2D>(); - - double x = drug.getX(); - double y = drug.getY(); - double width = drug.getWidth(); - double height = drug.getHeight(); - - // CHECKSTYLE:OFF - list.add(new Point2D.Double(x, y + height / 2)); - list.add(new Point2D.Double(x + width / 12, y)); - list.add(new Point2D.Double(x + width / 2, y)); - list.add(new Point2D.Double(x + width * 11 / 12, y)); - list.add(new Point2D.Double(x + width, y + height / 2)); - list.add(new Point2D.Double(x + width * 11 / 12, y + height)); - list.add(new Point2D.Double(x + width / 2, y + height)); - list.add(new Point2D.Double(x + width / 12, y + height)); - // CHECKSTYLE:ON - - return list; - } - - @Override - public PathIterator getBoundPathIterator(Drug drug) { - return getDrugShape(drug).getPathIterator(new AffineTransform()); - } + /** + * Distance between internal and external border of drug graphical + * representation. + */ + private static final int OFFSET_BETWEEN_BORDERS = 4; + + /** + * How big should be the arc in rectangle for drug representation. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 40; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(DrugConverter.class.getName()); + + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public DrugConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } + + /** + * Returns shape of the Drug . + * + * @param drug + * {@link Drug} for which we are looking for a border + * @return Shape object defining given alias + */ + private Shape getDrugShape(final Drug drug) { + return new RoundRectangle2D.Double(drug.getX(), drug.getY(), drug.getWidth(), drug.getHeight(), + RECTANGLE_CORNER_ARC_SIZE, RECTANGLE_CORNER_ARC_SIZE); + } + + @Override + protected void drawImpl(Drug drug, final Graphics2D graphics, final ConverterParams params) { + Shape a1 = getDrugShape(drug); + double offset = OFFSET_BETWEEN_BORDERS; + Shape a2 = new RoundRectangle2D.Double( + drug.getX() + offset, drug.getY() + offset, drug.getWidth() - 2 * offset, drug.getHeight() - 2 * offset, + RECTANGLE_CORNER_ARC_SIZE, + RECTANGLE_CORNER_ARC_SIZE); + Color c = graphics.getColor(); + graphics.setColor(drug.getColor()); + graphics.fill(a1); + graphics.setColor(c); + Stroke stroke = graphics.getStroke(); + graphics.setStroke(getBorderLine(drug)); + graphics.draw(a1); + graphics.draw(a2); + graphics.setStroke(stroke); + drawText(drug, graphics, params); + } + + /** + * Returns shape of the {@link Drug} as a list of points. + * + * @param drug + * {@link Drug} for which we are looking for a border + * @return list of points defining border of the given {@link Drug} + */ + protected ArrayList<Point2D> getDrugPoints(final Drug drug) { + ArrayList<Point2D> list = new ArrayList<Point2D>(); + + double x = drug.getX(); + double y = drug.getY(); + double width = drug.getWidth(); + double height = drug.getHeight(); + + // CHECKSTYLE:OFF + list.add(new Point2D.Double(x, y + height / 2)); + list.add(new Point2D.Double(x + width / 12, y)); + list.add(new Point2D.Double(x + width / 2, y)); + list.add(new Point2D.Double(x + width * 11 / 12, y)); + list.add(new Point2D.Double(x + width, y + height / 2)); + list.add(new Point2D.Double(x + width * 11 / 12, y + height)); + list.add(new Point2D.Double(x + width / 2, y + height)); + list.add(new Point2D.Double(x + width / 12, y + height)); + // CHECKSTYLE:ON + + return list; + } + + @Override + public PathIterator getBoundPathIterator(Drug drug) { + return getDrugShape(drug).getPathIterator(new AffineTransform()); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/GeneConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/GeneConverter.java index 434fd029f5..f14871e30a 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/GeneConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/GeneConverter.java @@ -1,14 +1,11 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.Stroke; +import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.PathIterator; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/IonConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/IonConverter.java index c8b7b82220..ffe8c75cfd 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/IonConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/IonConverter.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; +import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.PathIterator; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.exception.InvalidStateException; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/PhenotypeConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/PhenotypeConverter.java index 9523b1052e..a2ed8af2c6 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/PhenotypeConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/PhenotypeConverter.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -23,64 +19,64 @@ import lcsb.mapviewer.model.map.species.Phenotype; * */ public class PhenotypeConverter extends SpeciesConverter<Phenotype> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(PhenotypeConverter.class.getName()); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(PhenotypeConverter.class.getName()); - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing elements - * - */ - public PhenotypeConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing elements + * + */ + public PhenotypeConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } - @Override - protected void drawImpl(Phenotype phenotype, final Graphics2D graphics, final ConverterParams params) { - GeneralPath path = getPhenotypePath(phenotype); + @Override + protected void drawImpl(Phenotype phenotype, final Graphics2D graphics, final ConverterParams params) { + GeneralPath path = getPhenotypePath(phenotype); - Color c = graphics.getColor(); - graphics.setColor(phenotype.getColor()); - graphics.fill(path); - graphics.setColor(c); - Stroke stroke = graphics.getStroke(); - graphics.setStroke(getBorderLine(phenotype)); - graphics.draw(path); - graphics.setStroke(stroke); - drawText(phenotype, graphics, params); - } + Color c = graphics.getColor(); + graphics.setColor(phenotype.getColor()); + graphics.fill(path); + graphics.setColor(c); + Stroke stroke = graphics.getStroke(); + graphics.setStroke(getBorderLine(phenotype)); + graphics.draw(path); + graphics.setStroke(stroke); + drawText(phenotype, graphics, params); + } - /** - * Returns shape of the {@link Phenotype} as a {@link GeneralPath} object. - * - * @param phenotype - * {@link Phenotype} for which we are looking for a border - * @return {@link GeneralPath} object defining border of the given - * {@link Phenotype} - */ - private GeneralPath getPhenotypePath(final Phenotype phenotype) { - // CHECKSTYLE:OFF - GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD, 6); - path.moveTo(phenotype.getX() + phenotype.getWidth() / 6, phenotype.getY()); - path.lineTo(phenotype.getX() + phenotype.getWidth() * 5 / 6, phenotype.getY()); - path.lineTo(phenotype.getX() + phenotype.getWidth(), phenotype.getY() + phenotype.getHeight() / 2); - path.lineTo(phenotype.getX() + phenotype.getWidth() * 5 / 6, phenotype.getY() + phenotype.getHeight()); - path.lineTo(phenotype.getX() + phenotype.getWidth() / 6, phenotype.getY() + phenotype.getHeight()); - path.lineTo(phenotype.getX(), phenotype.getY() + phenotype.getHeight() / 2); - // CHECKSTYLE:ON - path.closePath(); - return path; - } + /** + * Returns shape of the {@link Phenotype} as a {@link GeneralPath} object. + * + * @param phenotype + * {@link Phenotype} for which we are looking for a border + * @return {@link GeneralPath} object defining border of the given + * {@link Phenotype} + */ + private GeneralPath getPhenotypePath(final Phenotype phenotype) { + // CHECKSTYLE:OFF + GeneralPath path = new GeneralPath(Path2D.WIND_EVEN_ODD, 6); + path.moveTo(phenotype.getX() + phenotype.getWidth() / 6, phenotype.getY()); + path.lineTo(phenotype.getX() + phenotype.getWidth() * 5 / 6, phenotype.getY()); + path.lineTo(phenotype.getX() + phenotype.getWidth(), phenotype.getY() + phenotype.getHeight() / 2); + path.lineTo(phenotype.getX() + phenotype.getWidth() * 5 / 6, phenotype.getY() + phenotype.getHeight()); + path.lineTo(phenotype.getX() + phenotype.getWidth() / 6, phenotype.getY() + phenotype.getHeight()); + path.lineTo(phenotype.getX(), phenotype.getY() + phenotype.getHeight() / 2); + // CHECKSTYLE:ON + path.closePath(); + return path; + } - @Override - public PathIterator getBoundPathIterator(Phenotype phenotype) { - return getPhenotypePath(phenotype).getPathIterator(new AffineTransform()); - } + @Override + public PathIterator getBoundPathIterator(Phenotype phenotype) { + return getPhenotypePath(phenotype).getPathIterator(new AffineTransform()); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ProteinConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ProteinConverter.java index 740c279f09..5f223086fb 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ProteinConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ProteinConverter.java @@ -1,31 +1,18 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.Area; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.RoundRectangle2D; +import java.awt.*; +import java.awt.geom.*; import java.util.ArrayList; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.graphics.ConverterParams; import lcsb.mapviewer.model.graphics.LineType; import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.TruncatedProtein; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.modelutils.map.ElementUtils; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/RnaConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/RnaConverter.java index 0d1976a6bd..0182f77db3 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/RnaConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/RnaConverter.java @@ -7,15 +7,11 @@ */ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; +import java.awt.*; +import java.awt.geom.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SBGNNucleicAcidFeatureConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SBGNNucleicAcidFeatureConverter.java index c62e51d3af..e5b42d58b5 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SBGNNucleicAcidFeatureConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SBGNNucleicAcidFeatureConverter.java @@ -1,12 +1,7 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.geom.GeneralPath; -import java.awt.geom.PathIterator; +import java.awt.*; +import java.awt.geom.*; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.converter.graphics.ConverterParams; @@ -23,110 +18,112 @@ import lcsb.mapviewer.model.map.species.Species; public class SBGNNucleicAcidFeatureConverter extends SpeciesConverter<Species> { - /** - * How big should be the arc in rectangle for nucleic acid feature - * representation. - */ - private static final int RECTANGLE_CORNER_ARC_SIZE = 5; - - /** - * Default constructor. - * - * @param colorExtractor - * Object that helps to convert {@link ColorSchema} values into - * colors when drawing {@link Species} - */ - public SBGNNucleicAcidFeatureConverter(ColorExtractor colorExtractor) { - super(colorExtractor); - } - - /** - * Returns shape of SBGN Nucleic acid feature. - * - * @param species - * {@link Species} for which the shape should be returned - * @return shape of the SBGN Nucleic acid feature for given alias - */ - private Shape getShape(final Species species) { - GeneralPath bottomRoundedRectangle = new GeneralPath(GeneralPath.WIND_EVEN_ODD); - double x = species.getX(), y = species.getY(), width = species.getWidth(), height = species.getHeight(); - - bottomRoundedRectangle.moveTo(x, y); - bottomRoundedRectangle.lineTo(x, y + height - RECTANGLE_CORNER_ARC_SIZE); - bottomRoundedRectangle.curveTo(x, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height); - bottomRoundedRectangle.lineTo(x + width - RECTANGLE_CORNER_ARC_SIZE, y + height); - bottomRoundedRectangle - .curveTo(x + width, y + height, x + width, y + height - RECTANGLE_CORNER_ARC_SIZE, x + width, y + height - RECTANGLE_CORNER_ARC_SIZE); - bottomRoundedRectangle.lineTo(x + width, y); - bottomRoundedRectangle.closePath(); - return bottomRoundedRectangle; - } - - @Override - protected void drawImpl(Species species, Graphics2D graphics, ConverterParams params) { - // Unit of information text - multimer cardinality - String unitOfInformationText = null; - if (species.getStatePrefix() != null && species.getStateLabel() != null) { - if (species.getStatePrefix().equals("free input")) { - unitOfInformationText = species.getStateLabel(); - } else { - unitOfInformationText = species.getStatePrefix() + ":" + species.getStateLabel(); - } - } - - int homodir = species.getHomodimer(); - - species.setWidth(species.getWidth() - SpeciesConverter.HOMODIMER_OFFSET * (species.getHomodimer() - 1)); - species.setHeight(species.getHeight() - SpeciesConverter.HOMODIMER_OFFSET * (species.getHomodimer() - 1)); - - species.setX(species.getX() + SpeciesConverter.HOMODIMER_OFFSET * homodir); - species.setY(species.getY() + SpeciesConverter.HOMODIMER_OFFSET * homodir); - - int glyphCount; - if (homodir > 1) { - glyphCount = 2; - } else { - glyphCount = 1; - } - for (int i = 0; i < glyphCount; i++) { - species.setX(species.getX() - SpeciesConverter.HOMODIMER_OFFSET); - species.setY(species.getY() - SpeciesConverter.HOMODIMER_OFFSET); - - Shape shape = getShape(species); - - Color c = graphics.getColor(); - graphics.setColor(species.getColor()); - graphics.fill(shape); - graphics.setColor(c); - - Stroke stroke = graphics.getStroke(); - graphics.setStroke(getBorderLine(species)); - graphics.draw(shape); - graphics.setStroke(stroke); - - if (i == 1) { - if (homodir > 1 && (unitOfInformationText == null || !unitOfInformationText.contains("N:"))) { - if (unitOfInformationText == null) { - unitOfInformationText = ""; - } else { - unitOfInformationText = unitOfInformationText.concat("; "); - } - unitOfInformationText = unitOfInformationText.concat("N:").concat(Integer.toString(homodir)); - } - } - - } - - drawUnitOfInformation(unitOfInformationText, species, graphics); - drawText(species, graphics, params); - - species.setWidth(species.getWidth() + SpeciesConverter.HOMODIMER_OFFSET * (homodir - 1)); - species.setHeight(species.getHeight() + SpeciesConverter.HOMODIMER_OFFSET * (homodir - 1)); - } - - @Override - protected PathIterator getBoundPathIterator(Species species) { - return getShape(species).getPathIterator(new AffineTransform()); - } + /** + * How big should be the arc in rectangle for nucleic acid feature + * representation. + */ + private static final int RECTANGLE_CORNER_ARC_SIZE = 5; + + /** + * Default constructor. + * + * @param colorExtractor + * Object that helps to convert {@link ColorSchema} values into colors + * when drawing {@link Species} + */ + public SBGNNucleicAcidFeatureConverter(ColorExtractor colorExtractor) { + super(colorExtractor); + } + + /** + * Returns shape of SBGN Nucleic acid feature. + * + * @param species + * {@link Species} for which the shape should be returned + * @return shape of the SBGN Nucleic acid feature for given alias + */ + private Shape getShape(final Species species) { + GeneralPath bottomRoundedRectangle = new GeneralPath(GeneralPath.WIND_EVEN_ODD); + double x = species.getX(), y = species.getY(), width = species.getWidth(), height = species.getHeight(); + + bottomRoundedRectangle.moveTo(x, y); + bottomRoundedRectangle.lineTo(x, y + height - RECTANGLE_CORNER_ARC_SIZE); + bottomRoundedRectangle.curveTo(x, y + height, x + RECTANGLE_CORNER_ARC_SIZE, y + height, + x + RECTANGLE_CORNER_ARC_SIZE, y + height); + bottomRoundedRectangle.lineTo(x + width - RECTANGLE_CORNER_ARC_SIZE, y + height); + bottomRoundedRectangle + .curveTo(x + width, y + height, x + width, y + height - RECTANGLE_CORNER_ARC_SIZE, x + width, + y + height - RECTANGLE_CORNER_ARC_SIZE); + bottomRoundedRectangle.lineTo(x + width, y); + bottomRoundedRectangle.closePath(); + return bottomRoundedRectangle; + } + + @Override + protected void drawImpl(Species species, Graphics2D graphics, ConverterParams params) { + // Unit of information text - multimer cardinality + String unitOfInformationText = null; + if (species.getStatePrefix() != null && species.getStateLabel() != null) { + if (species.getStatePrefix().equals("free input")) { + unitOfInformationText = species.getStateLabel(); + } else { + unitOfInformationText = species.getStatePrefix() + ":" + species.getStateLabel(); + } + } + + int homodir = species.getHomodimer(); + + species.setWidth(species.getWidth() - SpeciesConverter.HOMODIMER_OFFSET * (species.getHomodimer() - 1)); + species.setHeight(species.getHeight() - SpeciesConverter.HOMODIMER_OFFSET * (species.getHomodimer() - 1)); + + species.setX(species.getX() + SpeciesConverter.HOMODIMER_OFFSET * homodir); + species.setY(species.getY() + SpeciesConverter.HOMODIMER_OFFSET * homodir); + + int glyphCount; + if (homodir > 1) { + glyphCount = 2; + } else { + glyphCount = 1; + } + for (int i = 0; i < glyphCount; i++) { + species.setX(species.getX() - SpeciesConverter.HOMODIMER_OFFSET); + species.setY(species.getY() - SpeciesConverter.HOMODIMER_OFFSET); + + Shape shape = getShape(species); + + Color c = graphics.getColor(); + graphics.setColor(species.getColor()); + graphics.fill(shape); + graphics.setColor(c); + + Stroke stroke = graphics.getStroke(); + graphics.setStroke(getBorderLine(species)); + graphics.draw(shape); + graphics.setStroke(stroke); + + if (i == 1) { + if (homodir > 1 && (unitOfInformationText == null || !unitOfInformationText.contains("N:"))) { + if (unitOfInformationText == null) { + unitOfInformationText = ""; + } else { + unitOfInformationText = unitOfInformationText.concat("; "); + } + unitOfInformationText = unitOfInformationText.concat("N:").concat(Integer.toString(homodir)); + } + } + + } + + drawUnitOfInformation(unitOfInformationText, species, graphics); + drawText(species, graphics, params); + + species.setWidth(species.getWidth() + SpeciesConverter.HOMODIMER_OFFSET * (homodir - 1)); + species.setHeight(species.getHeight() + SpeciesConverter.HOMODIMER_OFFSET * (homodir - 1)); + } + + @Override + protected PathIterator getBoundPathIterator(Species species) { + return getShape(species).getPathIterator(new AffineTransform()); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SimpleMoleculeConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SimpleMoleculeConverter.java index 3f1ef8a8e6..a72c5318ea 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SimpleMoleculeConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SimpleMoleculeConverter.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; +import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.PathIterator; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.exception.InvalidStateException; @@ -42,7 +40,8 @@ public class SimpleMoleculeConverter extends SpeciesConverter<SimpleMolecule> { } @Override - protected void drawImpl(final SimpleMolecule simpleMolecule, final Graphics2D graphics, final ConverterParams params) { + protected void drawImpl(final SimpleMolecule simpleMolecule, final Graphics2D graphics, + final ConverterParams params) { int homodir; if (params.isSbgnFormat()) { // If the SBGN display mode is set, multimer is shown as two stacked diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverter.java index 393a369d95..eec1afd1cb 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverter.java @@ -1,15 +1,7 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.Shape; -import java.awt.Stroke; -import java.awt.geom.Ellipse2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; import java.util.List; import org.apache.logging.log4j.LogManager; @@ -22,22 +14,11 @@ import lcsb.mapviewer.converter.graphics.ConverterParams; import lcsb.mapviewer.converter.graphics.DrawingException; import lcsb.mapviewer.converter.graphics.bioEntity.element.ElementConverter; import lcsb.mapviewer.converter.graphics.geometry.ArrowTransformation; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.AbstractRegionModification; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.field.*; /** * This class defines basics used for drawing {@link Species} (node in the graph @@ -50,93 +31,76 @@ import lcsb.mapviewer.model.map.species.field.TranscriptionSite; */ public abstract class SpeciesConverter<T extends Species> extends ElementConverter<T> { + /** + * Length of the arrow for transcription site visualization. + */ + public static final int TRANSCRIPTION_SITE_ARROW_LENGTH = 8; + /** + * Angle of the arrow for transcription site visualization. + */ + public static final double TRANSCRIPTION_SITE_ARROW_ANGLE = 3 * Math.PI / 4; + /** + * What is the distance between homodimer aliases when homodimer>1. + */ + public static final int HOMODIMER_OFFSET = 6; /** * Default font size for the modifier description. */ protected static final int DEFAULT_SPECIES_MODIFIER_FONT_SIZE = 10; - /** * Default diameter of the modification residues. */ protected static final int DEFAULT_MODIFICATION_DIAMETER = 15; - /** * How far from the original shape should the activity border be drawn. */ protected static final int ACTIVITY_BORDER_DISTANCE = 5; - /** * Default species font size. */ protected static final int DEFAULT_SPECIES_FONT_SIZE = 12; - /** * Height of the ellipse that contain structural state description. */ private static final int STRUCTURAL_STATE_HEIGHT = 20; - /** * Height of the rectangle that contains unit of information. */ private static final int UNIT_OF_INFORMATION_HEIGHT = 20; - /** * Size of the margin in the structural state description. */ private static final int TEXT_MARGIN_FOR_STRUCTURAL_STATE_DESC = 40; - /** * Size of the margin in the unit of information description. */ private static final int TEXT_MARGIN_FOR_UNIT_OF_INFORMATION_DESC = 20; - /** * Minimum width of the structural state ellipse. */ private static final int MIN_STRUCTURAL_STATE_WIDTH = 60; - /** * Minimum width of the unit of information rectangle. */ private static final int MIN_UNIT_OF_INFORMATION_WIDTH = 40; - - /** - * Length of the arrow for transcription site visualization. - */ - public static final int TRANSCRIPTION_SITE_ARROW_LENGTH = 8; - - /** - * Angle of the arrow for transcription site visualization. - */ - public static final double TRANSCRIPTION_SITE_ARROW_ANGLE = 3 * Math.PI / 4; - /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(SpeciesConverter.class.getName()); - /** * Graphical helper object with line transformation functions. */ private LineTransformation lineTransformation = new LineTransformation(); private ArrowTransformation arrowTransformation = new ArrowTransformation(); - /** * Default font used to draw structural state of the species. */ private Font structuralFont = null; - /** * Default font used to draw unit of information of the species. */ private Font unitOfInformationFont = null; - - /** - * What is the distance between homodimer aliases when homodimer>1. - */ - public static final int HOMODIMER_OFFSET = 6; - /** * Object that helps to convert {@link ColorSchema} values into colors. */ @@ -203,29 +167,9 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert return name; } - @Override - public void drawText(final T species, final Graphics2D graphics, final ConverterParams params) { - String text = getText(species); - Font oldFont = graphics.getFont(); - Font font = getFont(species, params); - graphics.setColor(Color.BLACK); - graphics.setFont(font); - - Point2D point = species.getCenter(); - if (species instanceof Complex) { - if (((Complex) species).getElements().size() > 0) { - if (isTransparent(species, params)) { - point.setLocation(point.getX(), species.getY() + species.getHeight() - graphics.getFontMetrics().getAscent()); - } - } - } - drawText(point, text, graphics, true, true); - graphics.setFont(oldFont); - } - /** * Return width of the text. - * + * * @param text * width of this text will be computed * @param graphics @@ -251,7 +195,7 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert /** * Returns text height. - * + * * @param text * height of this text will be computed * @param graphics @@ -276,7 +220,7 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert * This method draws a string on graphics using current font. The coordinates of * the text is given as a point. Both parameters centered described if text * should be automatically centered horizontally and vertically. - * + * * @param point * where the text should be drawn * @param text @@ -311,7 +255,7 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert /** * Returns line style used for drawing alias border. - * + * * @param species * {@link Species} to be drawn * @return style of the line used to draw {@link Species} @@ -334,7 +278,7 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert /** * Returns border of the {@link Species} as {@link PathIterator}. - * + * * @param species * {@link Species} for which we are looking for a border * @return {@link PathIterator} object defining given {@link Species} @@ -389,7 +333,7 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert /** * Draws structural state description of the alias (ellipse in the top part of * the alias). - * + * * @param text * state description text * @param species @@ -434,7 +378,7 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert /** * Draws unit of information for the {@link Species} (rectangle in the top part * of the alias). - * + * * @param text * unit of information text * @param species @@ -505,6 +449,26 @@ public abstract class SpeciesConverter<T extends Species> extends ElementConvert graphics.setColor(oldColor); } + @Override + public void drawText(final T species, final Graphics2D graphics, final ConverterParams params) { + String text = getText(species); + Font oldFont = graphics.getFont(); + Font font = getFont(species, params); + graphics.setColor(Color.BLACK); + graphics.setFont(font); + + Point2D point = species.getCenter(); + if (species instanceof Complex) { + if (((Complex) species).getElements().size() > 0) { + if (isTransparent(species, params)) { + point.setLocation(point.getX(), species.getY() + species.getHeight() - graphics.getFontMetrics().getAscent()); + } + } + } + drawText(point, text, graphics, true, true); + graphics.setFont(oldFont); + } + /** * This method draws modification of the alias. If drawEmptyModification is set * to false then modification is not drawn if empty. If drawDescription is set diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/UnknownConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/UnknownConverter.java index 1bd3793542..0dd8e7577f 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/UnknownConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/UnknownConverter.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.Stroke; +import java.awt.*; import java.awt.geom.Ellipse2D; import java.awt.geom.PathIterator; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.exception.InvalidStateException; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverter.java index 7ef5183bd3..e5785c8222 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverter.java @@ -1,13 +1,7 @@ package lcsb.mapviewer.converter.graphics.bioEntity.reaction; -import java.awt.Color; -import java.awt.Font; -import java.awt.Graphics2D; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.*; +import java.awt.geom.*; import java.util.ArrayList; import java.util.List; @@ -22,17 +16,10 @@ import lcsb.mapviewer.converter.graphics.ConverterParams; import lcsb.mapviewer.converter.graphics.DrawingException; import lcsb.mapviewer.converter.graphics.bioEntity.BioEntityConverter; import lcsb.mapviewer.converter.graphics.geometry.ArrowTransformation; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.layout.GenericColorSchema; -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.*; import lcsb.mapviewer.model.map.reaction.type.ReactionRect; /** @@ -43,50 +30,44 @@ import lcsb.mapviewer.model.map.reaction.type.ReactionRect; */ public class ReactionConverter extends BioEntityConverter<Reaction> { - /** - * When drawing operator this value defines radius of the joining operator - * circle. - */ - private static final int DEFAULT_OPERATOR_RADIUS = 6; - /** * Size of the rectangle drawn on the central line of the reaction. */ public static final double RECT_SIZE = 10; - /** * Default font size of reaction description. */ public static final int DESCRIPTION_FONT_SIZE = 10; - /** * Radius multiplier for bigger logic operators circles in SBGN view. */ public static final double SBGN_RADIUS_MULTIPLIER = 2.5; - /** * {@link ColorSchema} used for coloring reactions where we have more than one * layout. */ public static final ColorSchema DEFAULT_COLOR_SCHEMA = new GenericColorSchema(); - + /** + * When drawing operator this value defines radius of the joining operator + * circle. + */ + private static final int DEFAULT_OPERATOR_RADIUS = 6; /** * Line width of #DEFAULT_COLOR_SCHEMA used for coloring reactions where we have * more than one layout. */ private static final double DEFAULT_COLOR_SCHEMA_LINE_WIDTH = 3.0; - - static { - DEFAULT_COLOR_SCHEMA.setColor(Color.BLACK); - DEFAULT_COLOR_SCHEMA.setLineWidth(DEFAULT_COLOR_SCHEMA_LINE_WIDTH); - } - /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(ReactionConverter.class.getName()); + static { + DEFAULT_COLOR_SCHEMA.setColor(Color.BLACK); + DEFAULT_COLOR_SCHEMA.setLineWidth(DEFAULT_COLOR_SCHEMA_LINE_WIDTH); + } + /** * Font used for drawing reaction description on the map. */ @@ -140,19 +121,21 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { Point2D startPoint = line.getPoints().get(line.getPoints().size() / 2 - 1); Point2D endPoint = line.getPoints().get(line.getPoints().size() / 2); if (startPoint.distance(endPoint) > RECT_SIZE) { - Point2D rectStartPoint = pointTransformation.getPointOnLine(startPoint, endPoint, 0.5 - RECT_SIZE/(2*startPoint.distance(endPoint))); - Point2D rectEndPoint = pointTransformation.getPointOnLine(startPoint, endPoint, 0.5 + RECT_SIZE/(2*startPoint.distance(endPoint))); + Point2D rectStartPoint = pointTransformation.getPointOnLine(startPoint, endPoint, + 0.5 - RECT_SIZE / (2 * startPoint.distance(endPoint))); + Point2D rectEndPoint = pointTransformation.getPointOnLine(startPoint, endPoint, + 0.5 + RECT_SIZE / (2 * startPoint.distance(endPoint))); PolylineData preRectangleLine = new PolylineData(); preRectangleLine.addPoint(startPoint); preRectangleLine.addPoint(rectStartPoint); - + PolylineData postRectangleLine = new PolylineData(); postRectangleLine.addPoint(rectEndPoint); postRectangleLine.addPoint(endPoint); - + arrowTransformation.drawLine(preRectangleLine, graphics); arrowTransformation.drawLine(postRectangleLine, graphics); - + startPoint = rectStartPoint; endPoint = rectEndPoint; } @@ -299,9 +282,13 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } } + @Override + public void drawText(Reaction bioEntity, Graphics2D graphics, ConverterParams params) throws DrawingException { + } + /** * Modify reaction with data from {@link ColorSchema}. - * + * * @param reaction * reaction to modify * @param colorSchema @@ -326,7 +313,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { /** * Draw modifier on the graphics2d. - * + * * @param graphics * where we want to draw the object * @param modifier @@ -339,7 +326,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { /** * Draw operator on the graphics2d. - * + * * @param graphics * where we want to draw the object * @param operator @@ -386,7 +373,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { /** * Draw product on the graphics2D. - * + * * @param graphics * where we want to draw the object * @param product @@ -398,7 +385,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { /** * Draw reactant on the graphics2D. - * + * * @param graphics * where the reactant should be drawn * @param reactant @@ -409,7 +396,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @return {@link #descFont} */ protected Font getDescFont() { @@ -417,7 +404,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @param descFont * new {@link #descFont} value */ @@ -426,7 +413,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @return {@link #lineTransformation} */ protected LineTransformation getLineTransformation() { @@ -434,7 +421,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @param lineTransformation * new {@link #lineTransformation} */ @@ -443,7 +430,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @return {@link #arrowTransformation} */ protected ArrowTransformation getArrowTransformation() { @@ -451,7 +438,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @param arrowTransformation * new {@link #arrowTransformation} */ @@ -460,7 +447,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @return {@link #pointTransformation} */ protected PointTransformation getPointTransformation() { @@ -468,7 +455,7 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { } /** - * + * * @param pointTransformation * new {@link #pointTransformation} */ @@ -476,8 +463,4 @@ public class ReactionConverter extends BioEntityConverter<Reaction> { this.pointTransformation = pointTransformation; } - @Override - public void drawText(Reaction bioEntity, Graphics2D graphics, ConverterParams params) throws DrawingException { - } - } \ No newline at end of file diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/package-info.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/package-info.java index 679fb7d63c..185e64decf 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/package-info.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/package-info.java @@ -4,4 +4,3 @@ * {@link java.awt.Graphics2D Graphics2D} object. */ package lcsb.mapviewer.converter.graphics.bioEntity.reaction; - diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformation.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformation.java index e7af708f14..4c52c29168 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformation.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformation.java @@ -1,23 +1,16 @@ package lcsb.mapviewer.converter.graphics.geometry; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; +import java.awt.*; +import java.awt.geom.*; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.geometry.PointTransformation; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; /** * Class containing basic function for drawing arrows. @@ -301,9 +294,9 @@ public class ArrowTransformation { /** * This method creates a General Path that describes triangle end of an arrow. - * The parameters determine position of segment line (line), the length of - * arrow end (len) and angle of an arrow. The open field determines if triangle - * should be closed or not. + * The parameters determine position of segment line (line), the length of arrow + * end (len) and angle of an arrow. The open field determines if triangle should + * be closed or not. * * @param line * line to which we want to add arrow end diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/FontFinder.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/FontFinder.java index 07d1aac5b1..d49999491e 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/FontFinder.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/FontFinder.java @@ -1,14 +1,14 @@ package lcsb.mapviewer.converter.graphics.geometry; -import java.awt.Font; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.List; -import lcsb.mapviewer.common.exception.InvalidArgumentException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.*; +import lcsb.mapviewer.common.exception.InvalidArgumentException; /** * This is utility class that helps to find optimal font to fit text into @@ -18,230 +18,232 @@ import org.apache.logging.log4j.*; * */ public final class FontFinder { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(FontFinder.class); - - /** - * Constructor that prevents class from instantiate. - */ - protected FontFinder() { - - } - - /** - * Methods looks for the biggest font size that allows to fit text into - * rectangle, but is not bigger then initialFontSze. IMPORTANT: it's not - * optimal, so don't set initialFontSize into infinity :). - * - * @param initialFontSize - * maximum font size that we consider - * @param fontName - * name of the font that we use - * @param graphics - * what is the graphics implementation that we use - * @param border - * border of the rectangle where we want to place our text - * @param text - * text to draw - * @return max font size that allows to draw the text into borders (but not - * bigger then initialFontSize) - * @throws RectangleTooSmallException - * if the border is too small to draw text - */ - public static double findMaxFontSize(double initialFontSize, String fontName, Graphics2D graphics, Rectangle2D border, String text) - throws RectangleTooSmallException { - if (border.getWidth() <= 0 || border.getHeight() <= 0) { - throw new RectangleTooSmallException("Size of the rectangle must be grater then 0.0"); - } - int result = (int) initialFontSize; - if (result <= 0) { - throw new InvalidArgumentException("initialFontSize must be at least 1.0"); - } - Font oldFont = graphics.getFont(); - graphics.setFont(new Font(fontName, 0, result)); - while (!textFits(graphics, border, text)) { - result--; - if (result <= 0) { - throw new RectangleTooSmallException("Cannot fit text into the border."); - } - graphics.setFont(new Font(fontName, 0, result)); - } - - graphics.setFont(oldFont); - return result; - } - - /** - * Check if the font in graphics allows to draw text in the rectangle. - * - * @param graphics - * implementation of the graphics (with font property) - * @param border - * border of the text in which we want put text - * @param text - * text that we want to draw - * @return true if the text can be drawn in the border, false othrerwise - */ - private static boolean textFits(Graphics2D graphics, Rectangle2D border, String text) { - double width = border.getWidth(); - double height = border.getHeight(); - - int lines = 1; - int index = 0; - StringBuilder line = new StringBuilder(); - while (index < text.length()) { - StringBuilder word = new StringBuilder(); - while (index < text.length()) { - if (text.charAt(index) == ' ' || text.charAt(index) == '\t' || text.charAt(index) == '\n') { - break; - } else { - word.append(text.charAt(index)); - index++; - } - } - if (!lineFits(graphics, width, line.toString() + word.toString())) { - if (line.length() == 0) { - return false; - } - lines++; - if (index == text.length() || text.charAt(index) == '\n') { - line = new StringBuilder(); - lines++; - } else { - line = word; - line.append(text.charAt(index)); - } - } else if (index < text.length()) { - line.append(word.toString()); - if (text.charAt(index) == '\n') { - line = new StringBuilder(); - lines++; - } else { - line.append(text.charAt(index)); - } - } - index++; - } - - return lines * (graphics.getFontMetrics().getHeight()) <= height; - } - - /** - * Check if width of the text line is not bigger then required. - * - * @param graphics - * font property - * @param width - * max width of the text - * @param text - * text that we want to check - * @return true if width of the text line is not bigger then required, false - * otherwise - */ - private static boolean lineFits(Graphics2D graphics, double width, String text) { - return width >= graphics.getFontMetrics().stringWidth(text); - } - - /** - * Writes centered text in rectangle using fontSize given as a parameter. - * - * @param fontSize - * font size - * @param fontName - * font name - * @param graphics - * where we want to write a text - * @param border - * what are the borders - * @param text - * what text we want to write - * @param center - * should the text be centered - */ - public static void drawText(int fontSize, String fontName, Graphics2D graphics, Rectangle2D border, String text, boolean center) { - Font oldFont = graphics.getFont(); - graphics.setFont(new Font(fontName, 0, fontSize)); - - double width = border.getWidth(); - - List<String> lines = new ArrayList<String>(); - int index = 0; - StringBuilder line = new StringBuilder(); - while (index < text.length()) { - StringBuilder word = new StringBuilder(); - while (index < text.length()) { - if (text.charAt(index) == ' ' || text.charAt(index) == '\t' || text.charAt(index) == '\n') { - break; - } else { - word.append(text.charAt(index)); - index++; - } - } - if (!lineFits(graphics, width, line.toString() + word.toString())) { - if (line.length() == 0) { - throw new InvalidArgumentException("Font too big."); - } - lines.add(line.toString()); - if (index == text.length() || text.charAt(index) == '\n') { - line = new StringBuilder(); - lines.add(word.toString()); - } else { - line = word; - line.append(text.charAt(index)); - } - } else { - line.append(word.toString()); - if (index < text.length()) { - if (text.charAt(index) == '\n') { - lines.add(line.toString()); - line = new StringBuilder(); - } else { - line.append(text.charAt(index)); - } - } - } - index++; - } - lines.add(line.toString()); - - double lineHeight = graphics.getFontMetrics().getHeight(); - double y = (int) (border.getCenterY() - lineHeight * lines.size() / 2.0 + graphics.getFontMetrics().getAscent()); - // if text is not centerd then lets start from left top corner - if (!center) { - y = border.getY() + lineHeight / 2; - } - - for (String string : lines) { - double textWidth = graphics.getFontMetrics().stringWidth(string); - if (center) { - graphics.drawString(string, (int) (border.getCenterX() - textWidth / 2), (int) y); - } else { - graphics.drawString(string, (int) border.getX(), (int) y); - } - y += lineHeight; - } - - graphics.setFont(oldFont); - } - - /** - * Writes centered text in rectangle using fontSize given as a parameter. - * - * @param fontSize - * font size - * @param fontName - * font name - * @param graphics - * where we want to write a text - * @param border - * what are the borders - * @param text - * what text we want to write - */ - public static void drawText(int fontSize, String fontName, Graphics2D graphics, Rectangle2D border, String text) { - drawText(fontSize, fontName, graphics, border, text, true); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(FontFinder.class); + + /** + * Constructor that prevents class from instantiate. + */ + protected FontFinder() { + + } + + /** + * Methods looks for the biggest font size that allows to fit text into + * rectangle, but is not bigger then initialFontSze. IMPORTANT: it's not + * optimal, so don't set initialFontSize into infinity :). + * + * @param initialFontSize + * maximum font size that we consider + * @param fontName + * name of the font that we use + * @param graphics + * what is the graphics implementation that we use + * @param border + * border of the rectangle where we want to place our text + * @param text + * text to draw + * @return max font size that allows to draw the text into borders (but not + * bigger then initialFontSize) + * @throws RectangleTooSmallException + * if the border is too small to draw text + */ + public static double findMaxFontSize(double initialFontSize, String fontName, Graphics2D graphics, Rectangle2D border, + String text) + throws RectangleTooSmallException { + if (border.getWidth() <= 0 || border.getHeight() <= 0) { + throw new RectangleTooSmallException("Size of the rectangle must be grater then 0.0"); + } + int result = (int) initialFontSize; + if (result <= 0) { + throw new InvalidArgumentException("initialFontSize must be at least 1.0"); + } + Font oldFont = graphics.getFont(); + graphics.setFont(new Font(fontName, 0, result)); + while (!textFits(graphics, border, text)) { + result--; + if (result <= 0) { + throw new RectangleTooSmallException("Cannot fit text into the border."); + } + graphics.setFont(new Font(fontName, 0, result)); + } + + graphics.setFont(oldFont); + return result; + } + + /** + * Check if the font in graphics allows to draw text in the rectangle. + * + * @param graphics + * implementation of the graphics (with font property) + * @param border + * border of the text in which we want put text + * @param text + * text that we want to draw + * @return true if the text can be drawn in the border, false othrerwise + */ + private static boolean textFits(Graphics2D graphics, Rectangle2D border, String text) { + double width = border.getWidth(); + double height = border.getHeight(); + + int lines = 1; + int index = 0; + StringBuilder line = new StringBuilder(); + while (index < text.length()) { + StringBuilder word = new StringBuilder(); + while (index < text.length()) { + if (text.charAt(index) == ' ' || text.charAt(index) == '\t' || text.charAt(index) == '\n') { + break; + } else { + word.append(text.charAt(index)); + index++; + } + } + if (!lineFits(graphics, width, line.toString() + word.toString())) { + if (line.length() == 0) { + return false; + } + lines++; + if (index == text.length() || text.charAt(index) == '\n') { + line = new StringBuilder(); + lines++; + } else { + line = word; + line.append(text.charAt(index)); + } + } else if (index < text.length()) { + line.append(word.toString()); + if (text.charAt(index) == '\n') { + line = new StringBuilder(); + lines++; + } else { + line.append(text.charAt(index)); + } + } + index++; + } + + return lines * (graphics.getFontMetrics().getHeight()) <= height; + } + + /** + * Check if width of the text line is not bigger then required. + * + * @param graphics + * font property + * @param width + * max width of the text + * @param text + * text that we want to check + * @return true if width of the text line is not bigger then required, false + * otherwise + */ + private static boolean lineFits(Graphics2D graphics, double width, String text) { + return width >= graphics.getFontMetrics().stringWidth(text); + } + + /** + * Writes centered text in rectangle using fontSize given as a parameter. + * + * @param fontSize + * font size + * @param fontName + * font name + * @param graphics + * where we want to write a text + * @param border + * what are the borders + * @param text + * what text we want to write + * @param center + * should the text be centered + */ + public static void drawText(int fontSize, String fontName, Graphics2D graphics, Rectangle2D border, String text, + boolean center) { + Font oldFont = graphics.getFont(); + graphics.setFont(new Font(fontName, 0, fontSize)); + + double width = border.getWidth(); + + List<String> lines = new ArrayList<String>(); + int index = 0; + StringBuilder line = new StringBuilder(); + while (index < text.length()) { + StringBuilder word = new StringBuilder(); + while (index < text.length()) { + if (text.charAt(index) == ' ' || text.charAt(index) == '\t' || text.charAt(index) == '\n') { + break; + } else { + word.append(text.charAt(index)); + index++; + } + } + if (!lineFits(graphics, width, line.toString() + word.toString())) { + if (line.length() == 0) { + throw new InvalidArgumentException("Font too big."); + } + lines.add(line.toString()); + if (index == text.length() || text.charAt(index) == '\n') { + line = new StringBuilder(); + lines.add(word.toString()); + } else { + line = word; + line.append(text.charAt(index)); + } + } else { + line.append(word.toString()); + if (index < text.length()) { + if (text.charAt(index) == '\n') { + lines.add(line.toString()); + line = new StringBuilder(); + } else { + line.append(text.charAt(index)); + } + } + } + index++; + } + lines.add(line.toString()); + + double lineHeight = graphics.getFontMetrics().getHeight(); + double y = (int) (border.getCenterY() - lineHeight * lines.size() / 2.0 + graphics.getFontMetrics().getAscent()); + // if text is not centerd then lets start from left top corner + if (!center) { + y = border.getY() + lineHeight / 2; + } + + for (String string : lines) { + double textWidth = graphics.getFontMetrics().stringWidth(string); + if (center) { + graphics.drawString(string, (int) (border.getCenterX() - textWidth / 2), (int) y); + } else { + graphics.drawString(string, (int) border.getX(), (int) y); + } + y += lineHeight; + } + + graphics.setFont(oldFont); + } + + /** + * Writes centered text in rectangle using fontSize given as a parameter. + * + * @param fontSize + * font size + * @param fontName + * font name + * @param graphics + * where we want to write a text + * @param border + * what are the borders + * @param text + * what text we want to write + */ + public static void drawText(int fontSize, String fontName, Graphics2D graphics, Rectangle2D border, String text) { + drawText(fontSize, fontName, graphics, border, text, true); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/RectangleTooSmallException.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/RectangleTooSmallException.java index e9618b89bb..4b97186c13 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/RectangleTooSmallException.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/RectangleTooSmallException.java @@ -9,18 +9,18 @@ package lcsb.mapviewer.converter.graphics.geometry; */ public class RectangleTooSmallException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with text message. - * - * @param message - * string message for this exception - */ - public RectangleTooSmallException(String message) { - super(message); - } + /** + * Default constructor with text message. + * + * @param message + * string message for this exception + */ + public RectangleTooSmallException(String message) { + super(message); + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/package-info.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/package-info.java index 4ca2ad7a80..2f5d349063 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/package-info.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/geometry/package-info.java @@ -3,4 +3,3 @@ * */ package lcsb.mapviewer.converter.graphics.geometry; - diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerConverter.java index aafbe66929..fbba074aa8 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerConverter.java @@ -1,14 +1,12 @@ package lcsb.mapviewer.converter.graphics.layer; -import java.awt.Graphics2D; +import java.awt.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.layout.graphics.*; /** * This class allows to draw layer on Graphics2D. diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerLineConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerLineConverter.java index 5ec1818d22..c89d1d9876 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerLineConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerLineConverter.java @@ -1,9 +1,9 @@ package lcsb.mapviewer.converter.graphics.layer; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.converter.graphics.geometry.ArrowTransformation; import lcsb.mapviewer.model.graphics.PolylineData; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerOvalConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerOvalConverter.java index 3ab35e7117..2cfc3360a9 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerOvalConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerOvalConverter.java @@ -1,10 +1,10 @@ package lcsb.mapviewer.converter.graphics.layer; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Ellipse2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.layout.graphics.LayerOval; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerRectConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerRectConverter.java index 5f8a26d202..757a9e0906 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerRectConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerRectConverter.java @@ -1,10 +1,10 @@ package lcsb.mapviewer.converter.graphics.layer; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Rectangle2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.layout.graphics.LayerRect; diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerTextConverter.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerTextConverter.java index 1f7d1958c5..66908cb1c9 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerTextConverter.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/LayerTextConverter.java @@ -1,10 +1,10 @@ package lcsb.mapviewer.converter.graphics.layer; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Rectangle2D; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.layout.graphics.LayerText; @@ -16,17 +16,15 @@ import lcsb.mapviewer.model.map.layout.graphics.LayerText; */ public class LayerTextConverter { + /** + * Color used for text frames. + */ + private static final Color FRAME_COLOR = Color.LIGHT_GRAY; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(LayerTextConverter.class.getName()); - - /** - * Color used for text frames. - */ - private static final Color FRAME_COLOR = Color.LIGHT_GRAY; - /** * Should the border around text be visible. */ diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/package-info.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/package-info.java index 62859860b8..2def339c01 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/package-info.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/layer/package-info.java @@ -3,4 +3,3 @@ * Graphics2D. */ package lcsb.mapviewer.converter.graphics.layer; - diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/package-info.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/package-info.java index 405d155a7b..a159255963 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/package-info.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/package-info.java @@ -8,9 +8,9 @@ * AbstractImageGenerator} is recommended. There are two implementation of this * class: * <ul> - * <li> {@link lcsb.mapviewer.converter.graphics.NormalImageGenerator + * <li>{@link lcsb.mapviewer.converter.graphics.NormalImageGenerator * NormalImageGenerator} - allows to generate images in PNG and JPG format.</li> - * <li> {@link lcsb.mapviewer.converter.graphics.SvgImageGenerator + * <li>{@link lcsb.mapviewer.converter.graphics.SvgImageGenerator * SvgImageGenerator} - allows to generate images in SVG format.</li> * </ul> * It is crucial to remember that too big maps will create very big files which @@ -24,4 +24,3 @@ * */ package lcsb.mapviewer.converter.graphics; - diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/PlaceFinder.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/PlaceFinder.java index e2961fbbf5..d4ec37f45d 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/PlaceFinder.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/PlaceFinder.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.converter.graphics.placefinder; import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.SemanticZoomLevelMatcher; import lcsb.mapviewer.model.map.compartment.Compartment; @@ -24,459 +20,456 @@ import lcsb.mapviewer.model.map.species.Element; */ public class PlaceFinder { - /** - * Class that allows to check if element is visible (or transparent) when - * drawing. It's used to filter out invisible elements when drawing - * semantic/hierarchy view. - */ - private SemanticZoomLevelMatcher zoomLevelMatcher = new SemanticZoomLevelMatcher(); - - /** - * Represents small part of the map (enclosed by cuting lines) where something - * can be put. Contains borders (height, weight, location etc). Informatin if - * it can be used or no and range (magic field that describes how much to the - * bottom rectangle can be extended). - * - * @author Piotr Gawron - * - */ - private class Field { - /** - * Border of the field. - */ - private Rectangle2D border; - /** - * Can the field be used for something or is occupied? - */ - private boolean available = true; - /** - * How many fields to the bottom are free (how much could we extend empty - * rectangle. - */ - private int range = -1; - - /** - * @return the border - * @see #border - */ - Rectangle2D getBorder() { - return border; - } - - /** - * @param border - * the border to set - * @see #border - */ - void setBorder(Rectangle2D border) { - this.border = border; - } - - /** - * @return the available - * @see #available - */ - public boolean isAvailable() { - return available; - } - - /** - * @param available - * the available to set - * @see #available - */ - public void setAvailable(boolean available) { - this.available = available; - } - - /** - * @return the range - * @see #range - */ - public int getRange() { - return range; - } - - /** - * @param range - * the range to set - * @see #range - */ - public void setRange(int range) { - this.range = range; - } - } - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(PlaceFinder.class.getName()); - /** - * Whole surface is split into rectangular regions. The lines that cut the - * surface correspond to borders of aliases that overlap current alias. This - * matrix defines which of these regions can be used for description. - */ - private Field[][] matrix; - - /** - * List of {@link Compartment compartment aliases} that split surface into - * regions. - */ - private List<Compartment> aliases; - - /** - * Alias for which computation is done. - */ - private Element mainAlias; - - /** - * Left boundary of the rectangle in which we want to fit our description. - */ - private double leftBound; - /** - * Right boundary of the rectangle in which we want to fit our description. - */ - private double rightBound; - /** - * Top boundary of the rectangle in which we want to fit our description. - */ - private double upBound; - /** - * Bottom boundary of the rectangle in which we want to fit our description. - */ - private double bottomBound; - - /** - * Model for which this {@link PlaceFinder} was created. - */ - private Model model; - - /** - * Map with aliases that should be considered when looking for a place to put - * text. - */ - private Map<Element, Map<Integer, List<Compartment>>> otherAliases = new HashMap<>(); - - /** - * Default constructor for place finder in a model. - * - * @param model - * model - * - */ - public PlaceFinder(Model model) { - this.model = model; - } - - /** - * Finds the biggest rectangle. - * - * @return the biggest rectangle - */ - private Rectangle2D findRectangle() { - Rectangle2D biggestRectangle = new Rectangle2D.Double(); - Rectangle2D temporaryRectangle = null; - for (int y = 0; y < getSizeY(); y++) { - for (int x = 0; x < getSizeX(); x++) { - temporaryRectangle = computeRectangleMaxArea(x, y); - double newArea = temporaryRectangle.getWidth() * temporaryRectangle.getHeight(); - double oldArea = biggestRectangle.getWidth() * biggestRectangle.getHeight(); - if (newArea > oldArea) { - biggestRectangle = temporaryRectangle; - } - } - } - - return biggestRectangle; - } - - /** - * Computes the biggest rectangle that starts in the region on the position - * [x,y]. - * - * @param x - * x index of the region - * @param y - * y index of the region - * @return the biggest rectangle that starts in the region on the given - * position - */ - private Rectangle2D computeRectangleMaxArea(int x, int y) { - Rectangle2D result = new Rectangle2D.Double(); - int possibleMaximumOfHeight = matrix[x][y].getRange(); - for (int k = x; k >= 0 && matrix[k][y].isAvailable(); k--) { - if (matrix[k][y].getRange() < possibleMaximumOfHeight) { - possibleMaximumOfHeight = matrix[k][y].getRange(); - } - Rectangle2D temporary = computeRectangle(x, y, k, possibleMaximumOfHeight); - double newArea = temporary.getWidth() * temporary.getHeight(); - double oldArea = result.getWidth() * result.getHeight(); - if (newArea > oldArea) { - result = temporary; - } - } - return result; - } - - /** - * Computes rectangle in region range [k..x][y..y+height]. - * - * @param x - * end x coordinate - * @param y - * start y coordinate - * @param k - * start x coordinate - * @param height - * height in y coordinate - * @return rectangle in region range - */ - private Rectangle2D computeRectangle(int x, int y, int k, int height) { - double resX = matrix[k][y].getBorder().getX(); - double resY = matrix[k][y].getBorder().getY(); - double resWidth = matrix[x][y + height - 1].getBorder().getX() - resX + matrix[x][y + height - 1].getBorder().getWidth(); - double resHeight = matrix[x][y + height - 1].getBorder().getY() - resY + matrix[x][y + height - 1].getBorder().getHeight(); - - return new Rectangle2D.Double(resX, resY, resWidth, resHeight); - } - - /** - * Computes how deep in y axis can regions be extended from starting x,y - * region. - */ - private void findRanges() { - for (int i = 0; i < getSizeX(); i++) { - for (int j = 0; j < getSizeY(); j++) { - if (!matrix[i][j].isAvailable()) { - int k = j; - int temporaryRange = 0; - while (k >= 0 && matrix[i][k].getRange() == -1) { - matrix[i][k--].setRange(temporaryRange++); - } - } - } - if (matrix[i][getSizeY() - 1].isAvailable()) { - int k = getSizeY() - 1; - int temporaryRange = 1; - while (k >= 0 && matrix[i][k].getRange() == -1) { - matrix[i][k--].setRange(temporaryRange++); - } - } - - } - } - - /** - * Disables regions for all aliases. - */ - private void fillMatrixWithAliases() { - for (Element alias : aliases) { - if (alias != mainAlias) { - fillMatrixWithAlias(alias); - } - } - } - - /** - * Disable regions for given alias. - * - * @param alias - * alias that should disable regions - */ - private void fillMatrixWithAlias(Element alias) { - Double a, b, c, d; - - a = alias.getX(); - b = alias.getX() + alias.getWidth(); - c = alias.getY() + alias.getHeight(); - d = alias.getY(); - - fillWithPoints(a, b, c, d); - } - - /** - * Disable regions between given coordinates. - * - * @param x - * starting x coordinate - * @param xw - * ending x coordinate - * @param yh - * ending y coordinate - * @param y - * starting y coordinate - */ - private void fillWithPoints(Double x, Double xw, Double yh, Double y) { - Integer widthStart = 0; - Integer widthEnd = matrix.length; - Integer heightStart = 0; - Integer heightEnd = matrix[0].length; - - for (int i = 0; i < matrix.length; i++) { - if (matrix[i][0].getBorder().getX() <= x) { - widthStart = i; - } - if (matrix[i][0].getBorder().getX() <= xw) { - widthEnd = i; - } - } - if (matrix[matrix.length - 1][0].getBorder().getX() + matrix[matrix.length - 1][0].getBorder().getWidth() <= xw) { - widthEnd = matrix.length; - } - for (int i = 0; i < matrix[0].length; i++) { - if (matrix[0][i].getBorder().getY() <= y) { - heightStart = i; - } - if (matrix[0][i].getBorder().getY() <= yh) { - heightEnd = i; - } - } - if (matrix[0][matrix[0].length - 1].getBorder().getY() + matrix[0][matrix[0].length - 1].getBorder().getHeight() <= yh) { - heightEnd = matrix[0].length; - } - - for (int i = widthStart; i < widthEnd; i++) { - for (int j = heightStart; j < heightEnd; j++) { - matrix[i][j].setAvailable(false); - } - } - } - - /** - * This method looks for a place to put description of the {@link Compartment} - * on the map. - * - * @param compartment - * {@link Compartment} for which we try to determine text position - * @param level - * level at which we will visualize element - * @return bounds where text could be put - */ - public Rectangle2D getRetangle(Compartment compartment, int level) { - Map<Integer, List<Compartment>> lists = otherAliases.get(compartment); - if (lists == null) { - lists = new HashMap<>(); - otherAliases.put(compartment, lists); - } - List<Compartment> list = lists.get(level); - if (list == null) { - list = new ArrayList<Compartment>(); - for (Compartment compAlias : model.getCompartments()) { - if (zoomLevelMatcher.isVisible(level, compAlias.getVisibilityLevel()) && !zoomLevelMatcher.isTransparent(level, compAlias.getTransparencyLevel())) { - if (compAlias.cross(compartment) && compAlias.getSize() <= compartment.getSize()) { - list.add(compAlias); - } - } - } - lists.put(level, list); - } - - this.mainAlias = compartment; - this.aliases = list; - - leftBound = compartment.getX(); - rightBound = (compartment.getX() + compartment.getWidth()); - upBound = compartment.getY(); - bottomBound = (compartment.getY() + compartment.getHeight()); - - createMatrix(); - - fillMatrixWithAliases(); - - findRanges(); // 2*O(n^2) - - return findRectangle(); - } - - /** - * Create empty matrix with fields. - * - * @see #matrix - */ - protected void createMatrix() { - Set<Double> xs = new TreeSet<Double>(); - Set<Double> ys = new TreeSet<Double>(); - List<Double> widths = new ArrayList<Double>(); - List<Double> xCoordsOfBegginingOfRectangle = new ArrayList<Double>(); - List<Double> heights = new ArrayList<Double>(); - List<Double> yCoordsOfBegginingOfRectangle = new ArrayList<Double>(); - - for (Element alias : aliases) { - double x1 = alias.getX(); - double x2 = alias.getX() + alias.getWidth(); - double y1 = alias.getY(); - double y2 = alias.getY() + alias.getHeight(); - if (x1 >= leftBound && x1 <= rightBound) { - xs.add(x1); - } - if (x2 >= leftBound && x2 <= rightBound) { - xs.add(x2); - } - - if (y1 >= upBound && y1 <= bottomBound) { - ys.add(y1); - } - if (y2 >= upBound && y2 <= bottomBound) { - ys.add(y2); - } - } - Double previous = null; - for (Double width : xs) { - if (previous != null) { - widths.add(width - previous); - } - xCoordsOfBegginingOfRectangle.add(width); - previous = width; - } - previous = null; - for (Double height : ys) { - if (previous != null) { - heights.add(height - previous); - } - yCoordsOfBegginingOfRectangle.add(height); - previous = height; - } - - matrix = new Field[xs.size() - 1][ys.size() - 1]; - - for (int i = 0; i < getSizeX(); i++) { - for (int j = 0; j < getSizeY(); j++) { - Field field = new Field(); - xCoordsOfBegginingOfRectangle.get(i); - yCoordsOfBegginingOfRectangle.get(j); - widths.get(i); - heights.get(j); - field.setBorder(new Rectangle2D.Double(xCoordsOfBegginingOfRectangle.get(i), yCoordsOfBegginingOfRectangle.get(j), widths.get(i), heights.get(j))); - matrix[i][j] = field; - } - } - } - - /** - * - * @return {@link #model} - */ - public Model getModel() { - return model; - } - - /** - * Returns width of the {@link #matrix}. - * - * @return width of the {@link #matrix} - */ - private int getSizeX() { - return matrix.length; - } - - /** - * Returns height of the {@link #matrix}. - * - * @return height of the {@link #matrix} - */ - private int getSizeY() { - return matrix[0].length; - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(PlaceFinder.class.getName()); + /** + * Class that allows to check if element is visible (or transparent) when + * drawing. It's used to filter out invisible elements when drawing + * semantic/hierarchy view. + */ + private SemanticZoomLevelMatcher zoomLevelMatcher = new SemanticZoomLevelMatcher(); + /** + * Whole surface is split into rectangular regions. The lines that cut the + * surface correspond to borders of aliases that overlap current alias. This + * matrix defines which of these regions can be used for description. + */ + private Field[][] matrix; + /** + * List of {@link Compartment compartment aliases} that split surface into + * regions. + */ + private List<Compartment> aliases; + /** + * Alias for which computation is done. + */ + private Element mainAlias; + /** + * Left boundary of the rectangle in which we want to fit our description. + */ + private double leftBound; + /** + * Right boundary of the rectangle in which we want to fit our description. + */ + private double rightBound; + /** + * Top boundary of the rectangle in which we want to fit our description. + */ + private double upBound; + /** + * Bottom boundary of the rectangle in which we want to fit our description. + */ + private double bottomBound; + /** + * Model for which this {@link PlaceFinder} was created. + */ + private Model model; + /** + * Map with aliases that should be considered when looking for a place to put + * text. + */ + private Map<Element, Map<Integer, List<Compartment>>> otherAliases = new HashMap<>(); + + /** + * Default constructor for place finder in a model. + * + * @param model + * model + * + */ + public PlaceFinder(Model model) { + this.model = model; + } + + /** + * Finds the biggest rectangle. + * + * @return the biggest rectangle + */ + private Rectangle2D findRectangle() { + Rectangle2D biggestRectangle = new Rectangle2D.Double(); + Rectangle2D temporaryRectangle = null; + for (int y = 0; y < getSizeY(); y++) { + for (int x = 0; x < getSizeX(); x++) { + temporaryRectangle = computeRectangleMaxArea(x, y); + double newArea = temporaryRectangle.getWidth() * temporaryRectangle.getHeight(); + double oldArea = biggestRectangle.getWidth() * biggestRectangle.getHeight(); + if (newArea > oldArea) { + biggestRectangle = temporaryRectangle; + } + } + } + + return biggestRectangle; + } + + /** + * Computes the biggest rectangle that starts in the region on the position + * [x,y]. + * + * @param x + * x index of the region + * @param y + * y index of the region + * @return the biggest rectangle that starts in the region on the given position + */ + private Rectangle2D computeRectangleMaxArea(int x, int y) { + Rectangle2D result = new Rectangle2D.Double(); + int possibleMaximumOfHeight = matrix[x][y].getRange(); + for (int k = x; k >= 0 && matrix[k][y].isAvailable(); k--) { + if (matrix[k][y].getRange() < possibleMaximumOfHeight) { + possibleMaximumOfHeight = matrix[k][y].getRange(); + } + Rectangle2D temporary = computeRectangle(x, y, k, possibleMaximumOfHeight); + double newArea = temporary.getWidth() * temporary.getHeight(); + double oldArea = result.getWidth() * result.getHeight(); + if (newArea > oldArea) { + result = temporary; + } + } + return result; + } + + /** + * Computes rectangle in region range [k..x][y..y+height]. + * + * @param x + * end x coordinate + * @param y + * start y coordinate + * @param k + * start x coordinate + * @param height + * height in y coordinate + * @return rectangle in region range + */ + private Rectangle2D computeRectangle(int x, int y, int k, int height) { + double resX = matrix[k][y].getBorder().getX(); + double resY = matrix[k][y].getBorder().getY(); + double resWidth = matrix[x][y + height - 1].getBorder().getX() - resX + + matrix[x][y + height - 1].getBorder().getWidth(); + double resHeight = matrix[x][y + height - 1].getBorder().getY() - resY + + matrix[x][y + height - 1].getBorder().getHeight(); + + return new Rectangle2D.Double(resX, resY, resWidth, resHeight); + } + + /** + * Computes how deep in y axis can regions be extended from starting x,y region. + */ + private void findRanges() { + for (int i = 0; i < getSizeX(); i++) { + for (int j = 0; j < getSizeY(); j++) { + if (!matrix[i][j].isAvailable()) { + int k = j; + int temporaryRange = 0; + while (k >= 0 && matrix[i][k].getRange() == -1) { + matrix[i][k--].setRange(temporaryRange++); + } + } + } + if (matrix[i][getSizeY() - 1].isAvailable()) { + int k = getSizeY() - 1; + int temporaryRange = 1; + while (k >= 0 && matrix[i][k].getRange() == -1) { + matrix[i][k--].setRange(temporaryRange++); + } + } + + } + } + + /** + * Disables regions for all aliases. + */ + private void fillMatrixWithAliases() { + for (Element alias : aliases) { + if (alias != mainAlias) { + fillMatrixWithAlias(alias); + } + } + } + + /** + * Disable regions for given alias. + * + * @param alias + * alias that should disable regions + */ + private void fillMatrixWithAlias(Element alias) { + Double a, b, c, d; + + a = alias.getX(); + b = alias.getX() + alias.getWidth(); + c = alias.getY() + alias.getHeight(); + d = alias.getY(); + + fillWithPoints(a, b, c, d); + } + + /** + * Disable regions between given coordinates. + * + * @param x + * starting x coordinate + * @param xw + * ending x coordinate + * @param yh + * ending y coordinate + * @param y + * starting y coordinate + */ + private void fillWithPoints(Double x, Double xw, Double yh, Double y) { + Integer widthStart = 0; + Integer widthEnd = matrix.length; + Integer heightStart = 0; + Integer heightEnd = matrix[0].length; + + for (int i = 0; i < matrix.length; i++) { + if (matrix[i][0].getBorder().getX() <= x) { + widthStart = i; + } + if (matrix[i][0].getBorder().getX() <= xw) { + widthEnd = i; + } + } + if (matrix[matrix.length - 1][0].getBorder().getX() + matrix[matrix.length - 1][0].getBorder().getWidth() <= xw) { + widthEnd = matrix.length; + } + for (int i = 0; i < matrix[0].length; i++) { + if (matrix[0][i].getBorder().getY() <= y) { + heightStart = i; + } + if (matrix[0][i].getBorder().getY() <= yh) { + heightEnd = i; + } + } + if (matrix[0][matrix[0].length - 1].getBorder().getY() + + matrix[0][matrix[0].length - 1].getBorder().getHeight() <= yh) { + heightEnd = matrix[0].length; + } + + for (int i = widthStart; i < widthEnd; i++) { + for (int j = heightStart; j < heightEnd; j++) { + matrix[i][j].setAvailable(false); + } + } + } + + /** + * This method looks for a place to put description of the {@link Compartment} + * on the map. + * + * @param compartment + * {@link Compartment} for which we try to determine text position + * @param level + * level at which we will visualize element + * @return bounds where text could be put + */ + public Rectangle2D getRetangle(Compartment compartment, int level) { + Map<Integer, List<Compartment>> lists = otherAliases.get(compartment); + if (lists == null) { + lists = new HashMap<>(); + otherAliases.put(compartment, lists); + } + List<Compartment> list = lists.get(level); + if (list == null) { + list = new ArrayList<Compartment>(); + for (Compartment compAlias : model.getCompartments()) { + if (zoomLevelMatcher.isVisible(level, compAlias.getVisibilityLevel()) + && !zoomLevelMatcher.isTransparent(level, compAlias.getTransparencyLevel())) { + if (compAlias.cross(compartment) && compAlias.getSize() <= compartment.getSize()) { + list.add(compAlias); + } + } + } + lists.put(level, list); + } + + this.mainAlias = compartment; + this.aliases = list; + + leftBound = compartment.getX(); + rightBound = (compartment.getX() + compartment.getWidth()); + upBound = compartment.getY(); + bottomBound = (compartment.getY() + compartment.getHeight()); + + createMatrix(); + + fillMatrixWithAliases(); + + findRanges(); // 2*O(n^2) + + return findRectangle(); + } + + /** + * Create empty matrix with fields. + * + * @see #matrix + */ + protected void createMatrix() { + Set<Double> xs = new TreeSet<Double>(); + Set<Double> ys = new TreeSet<Double>(); + List<Double> widths = new ArrayList<Double>(); + List<Double> xCoordsOfBegginingOfRectangle = new ArrayList<Double>(); + List<Double> heights = new ArrayList<Double>(); + List<Double> yCoordsOfBegginingOfRectangle = new ArrayList<Double>(); + + for (Element alias : aliases) { + double x1 = alias.getX(); + double x2 = alias.getX() + alias.getWidth(); + double y1 = alias.getY(); + double y2 = alias.getY() + alias.getHeight(); + if (x1 >= leftBound && x1 <= rightBound) { + xs.add(x1); + } + if (x2 >= leftBound && x2 <= rightBound) { + xs.add(x2); + } + + if (y1 >= upBound && y1 <= bottomBound) { + ys.add(y1); + } + if (y2 >= upBound && y2 <= bottomBound) { + ys.add(y2); + } + } + Double previous = null; + for (Double width : xs) { + if (previous != null) { + widths.add(width - previous); + } + xCoordsOfBegginingOfRectangle.add(width); + previous = width; + } + previous = null; + for (Double height : ys) { + if (previous != null) { + heights.add(height - previous); + } + yCoordsOfBegginingOfRectangle.add(height); + previous = height; + } + + matrix = new Field[xs.size() - 1][ys.size() - 1]; + + for (int i = 0; i < getSizeX(); i++) { + for (int j = 0; j < getSizeY(); j++) { + Field field = new Field(); + xCoordsOfBegginingOfRectangle.get(i); + yCoordsOfBegginingOfRectangle.get(j); + widths.get(i); + heights.get(j); + field.setBorder(new Rectangle2D.Double(xCoordsOfBegginingOfRectangle.get(i), + yCoordsOfBegginingOfRectangle.get(j), widths.get(i), heights.get(j))); + matrix[i][j] = field; + } + } + } + + /** + * + * @return {@link #model} + */ + public Model getModel() { + return model; + } + + /** + * Returns width of the {@link #matrix}. + * + * @return width of the {@link #matrix} + */ + private int getSizeX() { + return matrix.length; + } + + /** + * Returns height of the {@link #matrix}. + * + * @return height of the {@link #matrix} + */ + private int getSizeY() { + return matrix[0].length; + } + + /** + * Represents small part of the map (enclosed by cuting lines) where something + * can be put. Contains borders (height, weight, location etc). Informatin if it + * can be used or no and range (magic field that describes how much to the + * bottom rectangle can be extended). + * + * @author Piotr Gawron + * + */ + private class Field { + /** + * Border of the field. + */ + private Rectangle2D border; + /** + * Can the field be used for something or is occupied? + */ + private boolean available = true; + /** + * How many fields to the bottom are free (how much could we extend empty + * rectangle. + */ + private int range = -1; + + /** + * @return the border + * @see #border + */ + Rectangle2D getBorder() { + return border; + } + + /** + * @param border + * the border to set + * @see #border + */ + void setBorder(Rectangle2D border) { + this.border = border; + } + + /** + * @return the available + * @see #available + */ + public boolean isAvailable() { + return available; + } + + /** + * @param available + * the available to set + * @see #available + */ + public void setAvailable(boolean available) { + this.available = available; + } + + /** + * @return the range + * @see #range + */ + public int getRange() { + return range; + } + + /** + * @param range + * the range to set + * @see #range + */ + public void setRange(int range) { + this.range = range; + } + } } diff --git a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/package-info.java b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/package-info.java index 8968ad062e..678984743c 100644 --- a/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/package-info.java +++ b/converter-graphics/src/main/java/lcsb/mapviewer/converter/graphics/placefinder/package-info.java @@ -3,4 +3,3 @@ * among many overlapping rectangles. */ package lcsb.mapviewer.converter.graphics.placefinder; - diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AbstractImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AbstractImageGeneratorTest.java index 18164cfa01..2ea7cfcd77 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AbstractImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AbstractImageGeneratorTest.java @@ -4,13 +4,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.awt.Graphics2D; +import java.awt.*; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.model.map.layout.graphics.Layer; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AllGraphicsTests.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AllGraphicsTests.java index 3d6271639f..d526090d6f 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AllGraphicsTests.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/AllGraphicsTests.java @@ -10,16 +10,16 @@ import lcsb.mapviewer.converter.graphics.placefinder.AllPlaceFinderTest; @RunWith(Suite.class) @SuiteClasses({ - AbstractImageGeneratorTest.class, - AllBioEntityTests.class, - AllGeometryTests.class, - AllPlaceFinderTest.class, - ConverterTest.class, - ImageGeneratorsTest.class, - MapGeneratorTest.class, - NormalImageGeneratorTest.class, - PdfImageGeneratorTest.class, - SvgImageGeneratorTest.class + AbstractImageGeneratorTest.class, + AllBioEntityTests.class, + AllGeometryTests.class, + AllPlaceFinderTest.class, + ConverterTest.class, + ImageGeneratorsTest.class, + MapGeneratorTest.class, + NormalImageGeneratorTest.class, + PdfImageGeneratorTest.class, + SvgImageGeneratorTest.class }) public class AllGraphicsTests { diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java index 7631445290..5cbfae2e29 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/GraphicsTestFunctions.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.converter.graphics; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.when; import java.awt.*; import java.awt.geom.Point2D; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java index 70ab35b83a..c86497984e 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/ImageGeneratorsTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; import org.junit.*; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java index 691dce81bf..472f5be2d3 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/MapGeneratorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.File; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java index 00307235fc..61e529e794 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/NormalImageGeneratorTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.graphics; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfFontMapperTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfFontMapperTest.java index ce988d264e..af04bd96ed 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfFontMapperTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfFontMapperTest.java @@ -3,7 +3,7 @@ package lcsb.mapviewer.converter.graphics; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import java.awt.Font; +import java.awt.*; import org.junit.Test; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java index 5d1a0f1d0b..6ca76d4d91 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/PdfImageGeneratorTest.java @@ -1,11 +1,12 @@ package lcsb.mapviewer.converter.graphics; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.File; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java index 1557f4b872..d6ad4e15a0 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/SvgImageGeneratorTest.java @@ -4,9 +4,7 @@ import static org.junit.Assert.assertTrue; import java.io.ByteArrayOutputStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; @@ -24,14 +22,14 @@ public class SvgImageGeneratorTest extends GraphicsTestFunctions { @Test public void testSaveToFile() throws Exception { - Model model = createCompartmentModel(); + Model model = createCompartmentModel(); - SvgImageGenerator sig = new SvgImageGenerator(new AbstractImageGenerator.Params().model(model)); + SvgImageGenerator sig = new SvgImageGenerator(new AbstractImageGenerator.Params().model(model)); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - sig.saveToOutputStream(output); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + sig.saveToOutputStream(output); - assertTrue(output.toString().contains("viewBox")); + assertTrue(output.toString().contains("viewBox")); } private Model createCompartmentModel() { diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImplTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImplTest.java index 84b9cdc5c0..69bf1f7d0e 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImplTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/BioEntityConverterImplTest.java @@ -1,14 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Image; +import java.awt.*; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; @@ -16,10 +12,7 @@ import java.awt.image.ImageObserver; import java.io.File; import java.nio.file.Files; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.commands.ColorExtractor; @@ -29,10 +22,7 @@ import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.layout.graphics.Glyph; import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.reaction.Modifier; -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.*; import lcsb.mapviewer.model.map.species.GenericProtein; public class BioEntityConverterImplTest extends GraphicsTestFunctions { diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java index 7b04cd3b36..5f0c137114 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/compartment/PathwayCompartmentConverterTest.java @@ -1,9 +1,8 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; import org.junit.Test; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java index 1e97a005a4..acd62dd972 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/ComplexConverterTest.java @@ -1,9 +1,9 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.image.BufferedImage; import org.apache.logging.log4j.LogManager; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java index f8cc62d449..051b9670fe 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/element/species/SpeciesConverterTest.java @@ -1,8 +1,10 @@ package lcsb.mapviewer.converter.graphics.bioEntity.element.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.awt.*; import java.awt.geom.Point2D; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverterTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverterTest.java index aedacee988..237da54fe4 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverterTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/bioEntity/reaction/ReactionConverterTest.java @@ -1,28 +1,20 @@ package lcsb.mapviewer.converter.graphics.bioEntity.reaction; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; +import java.awt.*; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.Arrays; +import java.util.*; import java.util.List; import javax.imageio.ImageIO; import org.apache.commons.io.output.ByteArrayOutputStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.InOrder; import org.mockito.Mockito; @@ -34,13 +26,7 @@ import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.layout.GenericColorSchema; import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.OrOperator; -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.SplitOperator; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.ReactionRect; import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; import lcsb.mapviewer.model.map.species.GenericProtein; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java index ed479adf11..e3c0ad0918 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/ArrowTransformationTest.java @@ -1,9 +1,8 @@ package lcsb.mapviewer.converter.graphics.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; -import java.awt.Color; -import java.awt.Graphics2D; +import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java index 4e2b9ac0d4..3b069c197f 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/geometry/FontFinderTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.graphics.geometry; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.*; import java.awt.geom.Rectangle2D; diff --git a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/placefinder/AllPlaceFinderTest.java b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/placefinder/AllPlaceFinderTest.java index d06da1242e..ca7a275e2b 100644 --- a/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/placefinder/AllPlaceFinderTest.java +++ b/converter-graphics/src/test/java/lcsb/mapviewer/converter/graphics/placefinder/AllPlaceFinderTest.java @@ -7,7 +7,8 @@ import java.awt.geom.Rectangle2D; import java.io.IOException; import java.util.Arrays; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; @@ -17,131 +18,130 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; public class AllPlaceFinderTest { - Logger logger = LogManager.getLogger(AllPlaceFinderTest.class); - final String out = "map_images/testOutput"; - final String folder = "testFiles/placeFinderFiles/"; - - int id = 10; - - @Test - public void oneEmptyCompartments() throws InvalidXmlSchemaException, IOException { - String actual = null; - Model model = new ModelFullIndexed(null); - model.addElement(createCompartmentAlias(94.0, 70.0, 355.0, 173.0)); - - for (Compartment alias : model.getCompartments()) { - PlaceFinder pf = new PlaceFinder(model); - actual = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())).toString(); - } - String expected = ""; - Rectangle2D result = model.getCompartments().get(0).getBorder(); - expected = result.toString(); - assertEquals(expected, actual); - } - - @Test - public void twoSeparatedCompartments() throws InvalidXmlSchemaException, IOException { - String actual = null; - Model model = new ModelFullIndexed(null); - model.addElement(createCompartmentAlias(70.0, 81.0, 229.0, 213.0)); - model.addElement(createCompartmentAlias(332.0, 66.0, 188.0, 255.0)); - - String expected = ""; - for (Compartment alias : model.getCompartments()) { - PlaceFinder pf = new PlaceFinder(model); - actual = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())).toString(); - Rectangle2D result = alias.getBorder(); - expected = result.toString(); - assertEquals(expected, actual); - } - } - - @Test - public void twoIntersectingCompartments() throws InvalidXmlSchemaException, IOException { - Model model = new ModelFullIndexed(null); - Compartment alias = createCompartmentAlias(87.0, 56.0, 235.0, 219.0); - model.addElement(alias); - Compartment alias2 = createCompartmentAlias(227.0, 17.0, 290.0, 317.0); - model.addElement(alias2); - - PlaceFinder pf = new PlaceFinder(model); - Rectangle2D rect = pf.getRetangle(alias2, Integer.valueOf(alias.getVisibilityLevel())); - double actual = rect.getWidth() * rect.getHeight(); - double expected = alias2.getWidth() * alias2.getHeight(); - assertTrue(actual < expected); - } - - @Test - public void oneCompartmentCompletlyOverlapSecondOne() throws InvalidXmlSchemaException, IOException { - Model model = new ModelFullIndexed(null); - model.addElement(createCompartmentAlias(45.0, 38.0, 174.0, 169.0)); - model.addElement(createCompartmentAlias(118.0, 85.0, 60.0, 68.0)); - double actual = 0.0; - for (Compartment alias : model.getCompartments()) { - PlaceFinder pf = new PlaceFinder(model); - Rectangle2D rect = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())); - actual = rect.getWidth() * rect.getHeight(); - assertTrue(actual > 0); - } - } - - @Test - public void perfectOverlapingOfThreeCompartments() throws InvalidXmlSchemaException, IOException { - Model model = new ModelFullIndexed(null); - model.addElement(createCompartmentAlias(226.0, 70.0, 138.0, 112.0)); - model.addElement(createCompartmentAlias(163.0, 70.0, 138.0, 112.0)); - model.addElement(createCompartmentAlias(88.0, 70.0, 138.0, 112.0)); - double actual = 0.0; - Rectangle2D result = null; - for (Compartment alias : model.getCompartments()) { - PlaceFinder pf = new PlaceFinder(model); - Rectangle2D rect = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())); - actual += rect.getWidth() * rect.getHeight(); - } - result = model.getCompartments().get(0).getBorder(); - assertEquals(result.getWidth() * result.getHeight(), actual, 0.01); - } - - boolean equals(boolean[][] a, boolean[][] b) { - int ax = a.length; - int bx = b.length; - // logger.debug("Length of second table is " + bx); - boolean tru = false; - if (ax == bx) { - tru = true; - for (int i = 0; i < ax; i++) { - if (!Arrays.equals(a[i], b[i])) { - tru = false; - } - } - } - return tru; - } - - private Compartment createCompartmentAlias(double x, double y, double width, double height) { - Compartment result = new SquareCompartment("" + id++); - result.setX(x); - result.setY(y); - result.setWidth(width); - result.setHeight(height); - result.setTransparencyLevel("10"); - result.setVisibilityLevel("9"); - - return result; - } - - @Test - public void problematic() throws InvalidXmlSchemaException, IOException { - Model model = new ModelFullIndexed(null); - model.addElement(createCompartmentAlias(4521.0, 0.0, 10000.0, 6000.0)); - model.addElement(createCompartmentAlias(4828.0, 0.0, 5172.0, 6000.0)); - double actual = 0.0; - for (Compartment alias : model.getCompartments()) { - PlaceFinder pf = new PlaceFinder(model); - Rectangle2D rect = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())); - actual = rect.getWidth() * rect.getHeight(); - assertTrue(actual > 0); - } - } + final String out = "map_images/testOutput"; + final String folder = "testFiles/placeFinderFiles/"; + Logger logger = LogManager.getLogger(AllPlaceFinderTest.class); + int id = 10; + + @Test + public void oneEmptyCompartments() throws InvalidXmlSchemaException, IOException { + String actual = null; + Model model = new ModelFullIndexed(null); + model.addElement(createCompartmentAlias(94.0, 70.0, 355.0, 173.0)); + + for (Compartment alias : model.getCompartments()) { + PlaceFinder pf = new PlaceFinder(model); + actual = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())).toString(); + } + String expected = ""; + Rectangle2D result = model.getCompartments().get(0).getBorder(); + expected = result.toString(); + assertEquals(expected, actual); + } + + @Test + public void twoSeparatedCompartments() throws InvalidXmlSchemaException, IOException { + String actual = null; + Model model = new ModelFullIndexed(null); + model.addElement(createCompartmentAlias(70.0, 81.0, 229.0, 213.0)); + model.addElement(createCompartmentAlias(332.0, 66.0, 188.0, 255.0)); + + String expected = ""; + for (Compartment alias : model.getCompartments()) { + PlaceFinder pf = new PlaceFinder(model); + actual = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())).toString(); + Rectangle2D result = alias.getBorder(); + expected = result.toString(); + assertEquals(expected, actual); + } + } + + @Test + public void twoIntersectingCompartments() throws InvalidXmlSchemaException, IOException { + Model model = new ModelFullIndexed(null); + Compartment alias = createCompartmentAlias(87.0, 56.0, 235.0, 219.0); + model.addElement(alias); + Compartment alias2 = createCompartmentAlias(227.0, 17.0, 290.0, 317.0); + model.addElement(alias2); + + PlaceFinder pf = new PlaceFinder(model); + Rectangle2D rect = pf.getRetangle(alias2, Integer.valueOf(alias.getVisibilityLevel())); + double actual = rect.getWidth() * rect.getHeight(); + double expected = alias2.getWidth() * alias2.getHeight(); + assertTrue(actual < expected); + } + + @Test + public void oneCompartmentCompletlyOverlapSecondOne() throws InvalidXmlSchemaException, IOException { + Model model = new ModelFullIndexed(null); + model.addElement(createCompartmentAlias(45.0, 38.0, 174.0, 169.0)); + model.addElement(createCompartmentAlias(118.0, 85.0, 60.0, 68.0)); + double actual = 0.0; + for (Compartment alias : model.getCompartments()) { + PlaceFinder pf = new PlaceFinder(model); + Rectangle2D rect = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())); + actual = rect.getWidth() * rect.getHeight(); + assertTrue(actual > 0); + } + } + + @Test + public void perfectOverlapingOfThreeCompartments() throws InvalidXmlSchemaException, IOException { + Model model = new ModelFullIndexed(null); + model.addElement(createCompartmentAlias(226.0, 70.0, 138.0, 112.0)); + model.addElement(createCompartmentAlias(163.0, 70.0, 138.0, 112.0)); + model.addElement(createCompartmentAlias(88.0, 70.0, 138.0, 112.0)); + double actual = 0.0; + Rectangle2D result = null; + for (Compartment alias : model.getCompartments()) { + PlaceFinder pf = new PlaceFinder(model); + Rectangle2D rect = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())); + actual += rect.getWidth() * rect.getHeight(); + } + result = model.getCompartments().get(0).getBorder(); + assertEquals(result.getWidth() * result.getHeight(), actual, 0.01); + } + + boolean equals(boolean[][] a, boolean[][] b) { + int ax = a.length; + int bx = b.length; + // logger.debug("Length of second table is " + bx); + boolean tru = false; + if (ax == bx) { + tru = true; + for (int i = 0; i < ax; i++) { + if (!Arrays.equals(a[i], b[i])) { + tru = false; + } + } + } + return tru; + } + + private Compartment createCompartmentAlias(double x, double y, double width, double height) { + Compartment result = new SquareCompartment("" + id++); + result.setX(x); + result.setY(y); + result.setWidth(width); + result.setHeight(height); + result.setTransparencyLevel("10"); + result.setVisibilityLevel("9"); + + return result; + } + + @Test + public void problematic() throws InvalidXmlSchemaException, IOException { + Model model = new ModelFullIndexed(null); + model.addElement(createCompartmentAlias(4521.0, 0.0, 10000.0, 6000.0)); + model.addElement(createCompartmentAlias(4828.0, 0.0, 5172.0, 6000.0)); + double actual = 0.0; + for (Compartment alias : model.getCompartments()) { + PlaceFinder pf = new PlaceFinder(model); + Rectangle2D rect = pf.getRetangle(alias, Integer.valueOf(alias.getVisibilityLevel())); + actual = rect.getWidth() * rect.getHeight(); + assertTrue(actual > 0); + } + } } diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporter.java index c834d312ae..fc092330c4 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporter.java @@ -1,35 +1,19 @@ package lcsb.mapviewer.converter.model.sbml; -import java.awt.Color; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.awt.*; +import java.util.*; import javax.xml.stream.XMLStreamException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.Model; import org.sbml.jsbml.ext.SBasePlugin; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.Layout; -import org.sbml.jsbml.ext.layout.LayoutModelPlugin; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.layout.Point; import org.sbml.jsbml.ext.multi.MultiModelPlugin; -import org.sbml.jsbml.ext.render.ColorDefinition; -import org.sbml.jsbml.ext.render.Ellipse; -import org.sbml.jsbml.ext.render.LineEnding; -import org.sbml.jsbml.ext.render.LocalRenderInformation; -import org.sbml.jsbml.ext.render.LocalStyle; +import org.sbml.jsbml.ext.render.*; import org.sbml.jsbml.ext.render.Polygon; -import org.sbml.jsbml.ext.render.RenderConstants; -import org.sbml.jsbml.ext.render.RenderGraphicalObjectPlugin; -import org.sbml.jsbml.ext.render.RenderGroup; -import org.sbml.jsbml.ext.render.RenderLayoutPlugin; -import org.sbml.jsbml.ext.render.RenderPoint; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidStateException; @@ -44,27 +28,21 @@ public abstract class SbmlBioEntityExporter<T extends BioEntity, S extends org.s * Default class logger. */ private static Logger logger = LogManager.getLogger(SbmlBioEntityExporter.class); - + protected Map<String, S> sbmlElementByElementNameAndCompartmentName = new HashMap<>(); + Map<String, AbstractReferenceGlyph> sbmlGlyphByElementId = new HashMap<>(); /** * SBML Layout used when exporting map. */ private Layout layout; - /** * Map that we are exporting. */ private lcsb.mapviewer.model.map.model.Model minervaModel; - /** * SBML model to which we are exporting. */ private Model sbmlModel; - private Map<String, S> sbmlElementByElementId = new HashMap<>(); - Map<String, AbstractReferenceGlyph> sbmlGlyphByElementId = new HashMap<>(); - - protected Map<String, S> sbmlElementByElementNameAndCompartmentName = new HashMap<>(); - private int idCounter = 0; private Set<SbmlExtension> sbmlExtensions = new HashSet<>(); @@ -417,12 +395,12 @@ public abstract class SbmlBioEntityExporter<T extends BioEntity, S extends org.s return style; } - public void setProvideDefaults(boolean provideDefaults) { - this.provideDefaults = provideDefaults; - } - protected boolean isProvideDefaults() { return provideDefaults; } + public void setProvideDefaults(boolean provideDefaults) { + this.provideDefaults = provideDefaults; + } + } 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 4b6d452cf1..294eb975e2 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 @@ -1,26 +1,17 @@ package lcsb.mapviewer.converter.model.sbml; -import java.awt.Color; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.HashSet; +import java.awt.*; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.AbstractNamedSBase; import org.sbml.jsbml.Annotation; import org.sbml.jsbml.ext.SBasePlugin; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.Layout; -import org.sbml.jsbml.ext.layout.LayoutModelPlugin; -import org.sbml.jsbml.ext.layout.TextGlyph; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.multi.MultiModelPlugin; -import org.sbml.jsbml.ext.render.LocalRenderInformation; -import org.sbml.jsbml.ext.render.LocalStyle; -import org.sbml.jsbml.ext.render.RenderLayoutPlugin; +import org.sbml.jsbml.ext.render.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.XmlParser; @@ -60,10 +51,11 @@ public class SbmlBioEntityParser { * Counter for identifiers that cannot be inferred from SBML. */ private int idCounter = 0; + private Map<String, List<TextGlyph>> textGlyphByElementId = null; /** * Default constructor. - * + * * @param sbmlModel * SBML model that we are parsing * @param minervaModel @@ -164,7 +156,7 @@ public class SbmlBioEntityParser { /** * Returns {@link LocalStyle} from the layout data identified by glyph id. - * + * * @param glyph * * @return {@link LocalStyle} from the layout data @@ -193,8 +185,6 @@ public class SbmlBioEntityParser { return null; } - private Map<String, List<TextGlyph>> textGlyphByElementId = null; - /** * Returns list of {@link TextGlyph} that describes * {@link AbstractReferenceGlyph}. diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementExporter.java index 0ce8175cd4..953741acf6 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementExporter.java @@ -2,12 +2,10 @@ package lcsb.mapviewer.converter.model.sbml; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.Model; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.Point; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.render.ColorDefinition; import org.sbml.jsbml.ext.render.LocalStyle; @@ -27,15 +25,6 @@ public abstract class SbmlElementExporter<T extends Element, S extends org.sbml. super(sbmlModel, minervaModel, sbmlExtensions); } - @Override - protected LocalStyle createStyle(T element) { - LocalStyle result = super.createStyle(element); - ColorDefinition color = getColorDefinition(element.getColor()); - result.getGroup().setFill(color.getId()); - result.getGroup().setFontSize(element.getFontSize().shortValue()); - - return result; - } protected void assignLayoutToGlyph(T element, AbstractReferenceGlyph speciesGlyph) { BoundingBox boundingBox = new BoundingBox(); @@ -46,7 +35,6 @@ public abstract class SbmlElementExporter<T extends Element, S extends org.sbml. boundingBox.setDimensions(dimensions); speciesGlyph.setBoundingBox(boundingBox); - if (isExtensionEnabled(SbmlExtension.RENDER)) { LocalStyle style = createStyle(element); @@ -55,4 +43,14 @@ public abstract class SbmlElementExporter<T extends Element, S extends org.sbml. } + @Override + protected LocalStyle createStyle(T element) { + LocalStyle result = super.createStyle(element); + ColorDefinition color = getColorDefinition(element.getColor()); + result.getGroup().setFill(color.getId()); + result.getGroup().setFontSize(element.getFontSize().shortValue()); + + return result; + } + } diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java index 0cf6bf8e43..e4fe38ff9a 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java @@ -1,14 +1,11 @@ package lcsb.mapviewer.converter.model.sbml; -import java.awt.Color; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; +import java.awt.*; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.Model; import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; @@ -20,6 +17,8 @@ import lcsb.mapviewer.model.map.species.Element; public abstract class SbmlElementParser<T extends org.sbml.jsbml.Symbol> extends SbmlBioEntityParser { + Map<String, Element> elementBySbmlId = new HashMap<>(); + Map<String, String> sbmlIdByElementId = new HashMap<>(); /** * Default class logger. */ @@ -43,10 +42,6 @@ public abstract class SbmlElementParser<T extends org.sbml.jsbml.Symbol> extends protected abstract ListOf<T> getSbmlElementList(); - Map<String, Element> elementBySbmlId = new HashMap<>(); - - Map<String, String> sbmlIdByElementId = new HashMap<>(); - public Element getAnyElementBySbmlElementId(String id) { return elementBySbmlId.get(id); } 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 6aa238ac2f..c86d28e26e 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 @@ -1,21 +1,15 @@ package lcsb.mapviewer.converter.model.sbml; import java.io.UnsupportedEncodingException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +import java.util.*; import javax.xml.stream.XMLStreamException; import org.apache.commons.io.output.ByteArrayOutputStream; -import org.apache.logging.log4j.*; -import org.sbml.jsbml.Model; -import org.sbml.jsbml.SBMLDocument; -import org.sbml.jsbml.SBMLWriter; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.Layout; -import org.sbml.jsbml.ext.layout.LayoutModelPlugin; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.sbml.jsbml.*; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.multi.MultiModelPlugin; import org.sbml.jsbml.ext.render.GlobalRenderInformation; import org.sbml.jsbml.ext.render.RenderLayoutPlugin; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionExporter.java index 516e58830e..3058a3e326 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionExporter.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.ASTNode; import org.sbml.jsbml.FunctionDefinition; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionParser.java index 325afcb84d..68863c51ab 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlFunctionParser.java @@ -1,15 +1,14 @@ package lcsb.mapviewer.converter.model.sbml; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import lcsb.mapviewer.common.XmlParser; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.Model; import org.w3c.dom.Node; +import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.model.map.kinetics.SbmlFunction; @@ -21,14 +20,16 @@ public class SbmlFunctionParser extends SbmlBioEntityParser { super(sbmlModel, minervaModel); } - protected SbmlFunction parse(org.sbml.jsbml.FunctionDefinition unitDefinition, Model sbmlModel) throws InvalidInputDataExecption { + protected SbmlFunction parse(org.sbml.jsbml.FunctionDefinition unitDefinition, Model sbmlModel) + throws InvalidInputDataExecption { try { SbmlFunction result = new SbmlFunction(unitDefinition.getId()); result.setName(unitDefinition.getName()); Node node = XmlParser.getXmlDocumentFromString(unitDefinition.getMath().toMathML()); Node mathDefinition = XmlParser.getNode("math", node); String definition = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">" - + XmlParser.nodeToString(mathDefinition).replace(" xmlns=\"http://www.w3.org/1998/Math/MathML\"", "") + "</math>"; + + XmlParser.nodeToString(mathDefinition).replace(" xmlns=\"http://www.w3.org/1998/Math/MathML\"", "") + + "</math>"; result.setDefinition(definition); result.setArguments(parseArgumentsFromMath(mathDefinition, result.getFunctionId())); return result; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterExporter.java index 684910f667..c42d0d9ff8 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterExporter.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.Parameter; import lcsb.mapviewer.model.map.kinetics.SbmlParameter; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterParser.java index 836a91d667..b49323025e 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParameterParser.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.model.sbml; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.logging.log4j.*; -import org.sbml.jsbml.ListOf; -import org.sbml.jsbml.Model; -import org.sbml.jsbml.QuantityWithUnit; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.sbml.jsbml.*; import lcsb.mapviewer.model.map.kinetics.SbmlParameter; 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 12344d5b78..1e47dc8e3b 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 @@ -121,6 +121,32 @@ public class SbmlParser extends Converter { } } + @Override + public String model2String(Model model) throws ConverterException { + try { + SbmlExporter sbmlExporter = new SbmlExporter(); + sbmlExporter.setProvideDefaults(provideDefaults); + return sbmlExporter.toXml(model); + } catch (InconsistentModelException e) { + throw new ConverterException(e); + } + } + + @Override + public String getCommonName() { + return "SBML"; + } + + @Override + public MimeType getMimeType() { + return MimeType.SBML; + } + + @Override + public String getFileExtension() { + return "xml"; + } + private void addComplexRelationsBasedOnCoordinates(Model model) { for (Element element : model.getElements()) { if (element instanceof Species) { @@ -258,32 +284,6 @@ public class SbmlParser extends Converter { } } - @Override - public String model2String(Model model) throws ConverterException { - try { - SbmlExporter sbmlExporter = new SbmlExporter(); - sbmlExporter.setProvideDefaults(provideDefaults); - return sbmlExporter.toXml(model); - } catch (InconsistentModelException e) { - throw new ConverterException(e); - } - } - - @Override - public String getCommonName() { - return "SBML"; - } - - @Override - public MimeType getMimeType() { - return MimeType.SBML; - } - - @Override - public String getFileExtension() { - return "xml"; - } - public void setProvideDefaults(boolean b) { this.provideDefaults = b; } diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentExporter.java index 6fdcc5da88..d4d47b95c9 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentExporter.java @@ -1,26 +1,14 @@ package lcsb.mapviewer.converter.model.sbml.compartment; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.Model; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.CompartmentGlyph; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.TextGlyph; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.multi.MultiCompartmentPlugin; -import org.sbml.jsbml.ext.render.Ellipse; -import org.sbml.jsbml.ext.render.HTextAnchor; -import org.sbml.jsbml.ext.render.LocalRenderInformation; -import org.sbml.jsbml.ext.render.LocalStyle; -import org.sbml.jsbml.ext.render.Rectangle; -import org.sbml.jsbml.ext.render.RenderGroup; -import org.sbml.jsbml.ext.render.VTextAnchor; +import org.sbml.jsbml.ext.render.*; import lcsb.mapviewer.converter.model.sbml.SbmlElementExporter; import lcsb.mapviewer.converter.model.sbml.SbmlExtension; @@ -40,6 +28,23 @@ public class SbmlCompartmentExporter extends SbmlElementExporter<Compartment, or super(sbmlModel, minervaModel, sbmlExtensions); } + @Override + protected List<Compartment> getElementList() { + List<Compartment> result = new ArrayList<>(); + result.addAll(getMinervaModel().getCompartments()); + boolean defaultFound = false; + for (Compartment compartment : result) { + if (compartment.getElementId().equals("default")) { + defaultFound = true; + } + } + if (!defaultFound) { + Compartment defaultCompartment = new Compartment("default"); + result.add(defaultCompartment); + } + return result; + } + @Override public org.sbml.jsbml.Compartment createSbmlElement(Compartment element) throws InconsistentModelException { org.sbml.jsbml.Compartment result; @@ -61,20 +66,21 @@ public class SbmlCompartmentExporter extends SbmlElementExporter<Compartment, or } @Override - protected List<Compartment> getElementList() { - List<Compartment> result = new ArrayList<>(); - result.addAll(getMinervaModel().getCompartments()); - boolean defaultFound = false; - for (Compartment compartment : result) { - if (compartment.getElementId().equals("default")) { - defaultFound = true; - } + public org.sbml.jsbml.Compartment getSbmlElement(Compartment element) throws InconsistentModelException { + String mapKey = getSbmlIdKey(element); + if (element == null && sbmlElementByElementNameAndCompartmentName.get(mapKey) == null) { + org.sbml.jsbml.Compartment sbmlElement = createSbmlElement(element); + sbmlElementByElementNameAndCompartmentName.put(mapKey, sbmlElement); } - if (!defaultFound) { - Compartment defaultCompartment = new Compartment("default"); - result.add(defaultCompartment); + return super.getSbmlElement(element); + } + + @Override + protected String getSbmlIdKey(Compartment compartment) { + if (compartment == null || compartment.getElementId().equals("default")) { + return "default"; } - return result; + return compartment.getName(); } @Override @@ -86,14 +92,6 @@ public class SbmlCompartmentExporter extends SbmlElementExporter<Compartment, or return result; } - @Override - protected String getSbmlIdKey(Compartment compartment) { - if (compartment == null || compartment.getElementId().equals("default")) { - return "default"; - } - return compartment.getName(); - } - @Override protected LocalStyle createStyle(Compartment element) { LocalStyle style = super.createStyle(element); @@ -166,14 +164,4 @@ public class SbmlCompartmentExporter extends SbmlElementExporter<Compartment, or } } - @Override - public org.sbml.jsbml.Compartment getSbmlElement(Compartment element) throws InconsistentModelException { - String mapKey = getSbmlIdKey(element); - if (element == null && sbmlElementByElementNameAndCompartmentName.get(mapKey) == null) { - org.sbml.jsbml.Compartment sbmlElement = createSbmlElement(element); - sbmlElementByElementNameAndCompartmentName.put(mapKey, sbmlElement); - } - return super.getSbmlElement(element); - } - } diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParser.java index 13f0932d32..a15250b941 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParser.java @@ -1,17 +1,16 @@ package lcsb.mapviewer.converter.model.sbml.compartment; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.Model; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.CompartmentGlyph; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.TextGlyph; import org.sbml.jsbml.ext.render.LocalStyle; import lcsb.mapviewer.commands.layout.ApplySimpleLayoutModelCommand; @@ -33,17 +32,6 @@ public class SbmlCompartmentParser extends SbmlElementParser<org.sbml.jsbml.Comp super(sbmlModel, minervaModel); } - @Override - protected Compartment parse(org.sbml.jsbml.Compartment compartment) - throws InvalidInputDataExecption { - if (compartment.getId().equals("default")) { - return null; - } - Compartment result = new SquareCompartment(compartment.getId()); - assignBioEntityData(compartment, result); - return result; - } - @Override protected ListOf<org.sbml.jsbml.Compartment> getSbmlElementList() { return getSbmlModel().getListOfCompartments(); @@ -88,6 +76,14 @@ public class SbmlCompartmentParser extends SbmlElementParser<org.sbml.jsbml.Comp return result; } + @Override + protected void applyStyleToElement(Element elementWithLayout, LocalStyle style) { + if (!style.getGroup().isSetFill() && style.getGroup().isSetStroke()) { + Color backgroundColor = getColorByColorDefinition(style.getGroup().getStroke()); + elementWithLayout.setColor(backgroundColor); + } + } + @Override protected List<Pair<String, AbstractReferenceGlyph>> getGlyphs() { List<Pair<String, AbstractReferenceGlyph>> result = new ArrayList<>(); @@ -100,11 +96,14 @@ public class SbmlCompartmentParser extends SbmlElementParser<org.sbml.jsbml.Comp } @Override - protected void applyStyleToElement(Element elementWithLayout, LocalStyle style) { - if (!style.getGroup().isSetFill() && style.getGroup().isSetStroke()) { - Color backgroundColor = getColorByColorDefinition(style.getGroup().getStroke()); - elementWithLayout.setColor(backgroundColor); + protected Compartment parse(org.sbml.jsbml.Compartment compartment) + throws InvalidInputDataExecption { + if (compartment.getId().equals("default")) { + return null; } + Compartment result = new SquareCompartment(compartment.getId()); + assignBioEntityData(compartment, result); + return result; } } diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/BioEntityFeature.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/BioEntityFeature.java index 63d464554f..aa9fe4416c 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/BioEntityFeature.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/BioEntityFeature.java @@ -1,14 +1,13 @@ package lcsb.mapviewer.converter.model.sbml.extension.multi; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Protein; +import lcsb.mapviewer.model.map.species.*; public enum BioEntityFeature { STRUCTURAL_STATE("Structural state", "", new Class<?>[] { Protein.class, Complex.class }, "minerva_structural_state_"), - POSITION_TO_COMPARTMENT("Position to compartment", MultiPackageNamingUtils.NULL_REPRESENTATION, new Class<?>[] { Element.class }, + POSITION_TO_COMPARTMENT("Position to compartment", MultiPackageNamingUtils.NULL_REPRESENTATION, + new Class<?>[] { Element.class }, "minerva_position_to_compartment_"), SYNONYM("Synonym", null, new Class<?>[] { Element.class }, diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/MultiPackageNamingUtils.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/MultiPackageNamingUtils.java index 8dc5e8e95b..1fa4c03645 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/MultiPackageNamingUtils.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/extension/multi/MultiPackageNamingUtils.java @@ -1,14 +1,12 @@ package lcsb.mapviewer.converter.model.sbml.extension.multi; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.ext.multi.MultiSpeciesType; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.field.*; /** * Class responsible for providing identifiers of structures inside multi @@ -18,17 +16,15 @@ import lcsb.mapviewer.model.map.species.field.TranscriptionSite; * */ public final class MultiPackageNamingUtils { - + + public static final String NULL_REPRESENTATION = "NULL"; + private static final String MINERVA_MODIFICATION_TYPE_PREFIX = "minerva_modification_type_"; /** * Default logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(MultiPackageNamingUtils.class); - private static final String MINERVA_MODIFICATION_TYPE_PREFIX = "minerva_modification_type_"; - - public static final String NULL_REPRESENTATION = "NULL"; - /** * Returns id of the {@link MultiSpeciesType} for a given minerva class. * diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermModifierType.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermModifierType.java index e0ebcd078a..7a18f3918b 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermModifierType.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermModifierType.java @@ -3,15 +3,10 @@ package lcsb.mapviewer.converter.model.sbml.reaction; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.modifier.Trigger; -import lcsb.mapviewer.model.map.modifier.UnknownCatalysis; -import lcsb.mapviewer.model.map.modifier.UnknownInhibition; +import lcsb.mapviewer.model.map.modifier.*; import lcsb.mapviewer.model.map.reaction.Modifier; public enum SBOTermModifierType { @@ -25,8 +20,8 @@ public enum SBOTermModifierType { ; private static Logger logger = LogManager.getLogger(SBOTermModifierType.class); - private List<String> sboTerms = new ArrayList<>(); Class<? extends Modifier> clazz; + private List<String> sboTerms = new ArrayList<>(); private SBOTermModifierType(Class<? extends Modifier> clazz, String[] inputSboTerms) { this.clazz = clazz; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermReactionType.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermReactionType.java index 8336f16ed7..f64c954cc0 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermReactionType.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SBOTermReactionType.java @@ -3,35 +3,11 @@ package lcsb.mapviewer.converter.model.sbml.reaction; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.type.CatalysisReaction; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.InhibitionReaction; -import lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction; -import lcsb.mapviewer.model.map.reaction.type.ModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.PhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction; -import lcsb.mapviewer.model.map.reaction.type.TranslationReaction; -import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.reaction.type.TriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownCatalysisReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownInhibitionReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; +import lcsb.mapviewer.model.map.reaction.type.*; public enum SBOTermReactionType { CATALYSIS(CatalysisReaction.class, new String[] { "SBO:0000013" }), @@ -63,8 +39,8 @@ public enum SBOTermReactionType { ; private static Logger logger = LogManager.getLogger(SBOTermReactionType.class); - private List<String> sboTerms = new ArrayList<>(); Class<? extends Reaction> clazz; + private List<String> sboTerms = new ArrayList<>(); private SBOTermReactionType(Class<? extends Reaction> clazz, String[] inputSboTerms) { this.clazz = clazz; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporter.java index 2139ddfb9f..4bf203532d 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporter.java @@ -1,37 +1,17 @@ package lcsb.mapviewer.converter.model.sbml.reaction; -import java.awt.BasicStroke; -import java.awt.Stroke; +import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; +import java.util.*; import java.util.List; -import java.util.Map; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.sbml.jsbml.ASTNode; -import org.sbml.jsbml.KineticLaw; -import org.sbml.jsbml.LocalParameter; -import org.sbml.jsbml.Model; -import org.sbml.jsbml.SimpleSpeciesReference; -import org.sbml.jsbml.Species; -import org.sbml.jsbml.SpeciesReference; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.Curve; -import org.sbml.jsbml.ext.layout.CurveSegment; -import org.sbml.jsbml.ext.layout.LineSegment; +import org.sbml.jsbml.*; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.ReactionGlyph; -import org.sbml.jsbml.ext.layout.SpeciesReferenceGlyph; -import org.sbml.jsbml.ext.layout.SpeciesReferenceRole; -import org.sbml.jsbml.ext.render.ColorDefinition; -import org.sbml.jsbml.ext.render.LocalRenderInformation; -import org.sbml.jsbml.ext.render.LocalStyle; -import org.sbml.jsbml.ext.render.RenderGroup; +import org.sbml.jsbml.ext.render.*; import org.w3c.dom.Node; import lcsb.mapviewer.common.Configuration; @@ -47,12 +27,8 @@ import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; import lcsb.mapviewer.model.map.kinetics.SbmlParameter; import lcsb.mapviewer.model.map.modifier.Inhibition; import lcsb.mapviewer.model.map.modifier.Trigger; -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.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -77,46 +53,6 @@ public class SbmlReactionExporter extends SbmlBioEntityExporter<Reaction, org.sb this.compartmentExporter = compartmentExporter; } - @Override - public org.sbml.jsbml.Reaction createSbmlElement(Reaction reaction) throws InconsistentModelException { - String reactionId = getReactionId(reaction); - org.sbml.jsbml.Reaction result = super.getSbmlElementByElementId(reactionId); - if (result != null) { - return result; - } - result = getSbmlModel().createReaction(reactionId); - result.setReversible(reaction.isReversible()); - String sboTerm = SBOTermReactionType.getTermByType(reaction.getClass()); - if (sboTerm != null) { - result.setSBOTerm(sboTerm); - } - for (Product product : reaction.getProducts()) { - Species sbmlSymbol = speciesExporter.getSbmlElementByElementId(product.getElement().getElementId()); - SpeciesReference speciesReference = result.createProduct(sbmlSymbol); - speciesReference.setConstant(false); - speciesReferenceByReactionNode.put(product, speciesReference); - } - for (Reactant reactant : reaction.getReactants()) { - Species sbmlSymbol = speciesExporter.getSbmlElementByElementId(reactant.getElement().getElementId()); - SpeciesReference speciesReference = result.createReactant(sbmlSymbol); - speciesReference.setConstant(false); - speciesReferenceByReactionNode.put(reactant, speciesReference); - } - for (Modifier modifier : reaction.getModifiers()) { - Species sbmlSymbol = speciesExporter.getSbmlElementByElementId(modifier.getElement().getElementId()); - SimpleSpeciesReference speciesReference = result.createModifier(sbmlSymbol); - speciesReferenceByReactionNode.put(modifier, speciesReference); - String term = SBOTermModifierType.getTermByType(modifier.getClass()); - if (term != null) { - speciesReference.setSBOTerm(term); - } - } - if (reaction.getKinetics() != null) { - result.setKineticLaw(createKineticLaw(reaction)); - } - return result; - } - private KineticLaw createKineticLaw(Reaction reaction) throws InconsistentModelException { SbmlKinetics kinetics = reaction.getKinetics(); KineticLaw result = new KineticLaw(); @@ -171,27 +107,53 @@ public class SbmlReactionExporter extends SbmlBioEntityExporter<Reaction, org.sb } @Override - protected AbstractReferenceGlyph createElementGlyph(String sbmlElementId, String glyphId) { - int separatorIndex = glyphId.indexOf("__"); - if (separatorIndex > 0) { - glyphId = glyphId.substring(separatorIndex + 2); + protected Collection<Reaction> getElementList() { + return getMinervaModel().getReactions(); + } + + @Override + public org.sbml.jsbml.Reaction createSbmlElement(Reaction reaction) throws InconsistentModelException { + String reactionId = getReactionId(reaction); + org.sbml.jsbml.Reaction result = super.getSbmlElementByElementId(reactionId); + if (result != null) { + return result; } - ReactionGlyph reactionGlyph; - try { - // handle case when input data cannot doesn't come from SBML parser and contains - // "__" that mess up identifier uniqueness - reactionGlyph = getLayout().createReactionGlyph(glyphId, sbmlElementId); - } catch (IllegalArgumentException e) { - glyphId += "_" + getNextId(); - reactionGlyph = getLayout().createReactionGlyph(glyphId, sbmlElementId); + result = getSbmlModel().createReaction(reactionId); + result.setReversible(reaction.isReversible()); + String sboTerm = SBOTermReactionType.getTermByType(reaction.getClass()); + if (sboTerm != null) { + result.setSBOTerm(sboTerm); } - - return reactionGlyph; + for (Product product : reaction.getProducts()) { + Species sbmlSymbol = speciesExporter.getSbmlElementByElementId(product.getElement().getElementId()); + SpeciesReference speciesReference = result.createProduct(sbmlSymbol); + speciesReference.setConstant(false); + speciesReferenceByReactionNode.put(product, speciesReference); + } + for (Reactant reactant : reaction.getReactants()) { + Species sbmlSymbol = speciesExporter.getSbmlElementByElementId(reactant.getElement().getElementId()); + SpeciesReference speciesReference = result.createReactant(sbmlSymbol); + speciesReference.setConstant(false); + speciesReferenceByReactionNode.put(reactant, speciesReference); + } + for (Modifier modifier : reaction.getModifiers()) { + Species sbmlSymbol = speciesExporter.getSbmlElementByElementId(modifier.getElement().getElementId()); + SimpleSpeciesReference speciesReference = result.createModifier(sbmlSymbol); + speciesReferenceByReactionNode.put(modifier, speciesReference); + String term = SBOTermModifierType.getTermByType(modifier.getClass()); + if (term != null) { + speciesReference.setSBOTerm(term); + } + } + if (reaction.getKinetics() != null) { + result.setKineticLaw(createKineticLaw(reaction)); + } + return result; } @Override - protected Collection<Reaction> getElementList() { - return getMinervaModel().getReactions(); + protected String getSbmlIdKey(Reaction element) { + return element.getClass().getSimpleName() + "\n" + element.getElementId(); } @Override @@ -226,7 +188,6 @@ public class SbmlReactionExporter extends SbmlBioEntityExporter<Reaction, org.sb reactionGlyph.getCurve().addCurveSegment(new LineSegment(curve.getCurveSegment(i))); } - boolean firstProduct = true; for (Product product : reaction.getProducts()) { SpeciesReferenceGlyph productGlyph = createNodeGlyph(reactionGlyph, product); @@ -283,6 +244,30 @@ public class SbmlReactionExporter extends SbmlBioEntityExporter<Reaction, org.sb removeColinearPoints(reactionGlyph); } + @Override + protected AbstractReferenceGlyph createElementGlyph(String sbmlElementId, String glyphId) { + int separatorIndex = glyphId.indexOf("__"); + if (separatorIndex > 0) { + glyphId = glyphId.substring(separatorIndex + 2); + } + ReactionGlyph reactionGlyph; + try { + // handle case when input data cannot doesn't come from SBML parser and contains + // "__" that mess up identifier uniqueness + reactionGlyph = getLayout().createReactionGlyph(glyphId, sbmlElementId); + } catch (IllegalArgumentException e) { + glyphId += "_" + getNextId(); + reactionGlyph = getLayout().createReactionGlyph(glyphId, sbmlElementId); + } + + return reactionGlyph; + } + + @Override + protected LocalStyle createStyle(Reaction reaction) { + return createStyle(reaction.getLine()); + } + private void removeColinearPoints(ReactionGlyph glyph) { PolylineData line = createLine(glyph.getCurve()); line = PolylineDataFactory.removeCollinearPoints(line); @@ -318,11 +303,6 @@ public class SbmlReactionExporter extends SbmlBioEntityExporter<Reaction, org.sb return style; } - @Override - protected LocalStyle createStyle(Reaction reaction) { - return createStyle(reaction.getLine()); - } - private List<Short> strokeToArray(Stroke stroke) { if (stroke instanceof BasicStroke) { BasicStroke basicStroke = (BasicStroke) stroke; @@ -383,9 +363,4 @@ public class SbmlReactionExporter extends SbmlBioEntityExporter<Reaction, org.sb return curve; } - @Override - protected String getSbmlIdKey(Reaction element) { - return element.getClass().getSimpleName() + "\n" + element.getElementId(); - } - } diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParser.java index cddeb2fdd8..a5349c461f 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParser.java @@ -1,41 +1,23 @@ package lcsb.mapviewer.converter.model.sbml.reaction; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.sbml.jsbml.KineticLaw; -import org.sbml.jsbml.ListOf; -import org.sbml.jsbml.LocalParameter; -import org.sbml.jsbml.Model; -import org.sbml.jsbml.ModifierSpeciesReference; -import org.sbml.jsbml.SpeciesReference; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.Curve; -import org.sbml.jsbml.ext.layout.CurveSegment; -import org.sbml.jsbml.ext.layout.LineSegment; +import org.sbml.jsbml.*; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.ReactionGlyph; -import org.sbml.jsbml.ext.layout.SpeciesGlyph; -import org.sbml.jsbml.ext.layout.SpeciesReferenceGlyph; import org.sbml.jsbml.ext.render.LocalStyle; import org.sbml.jsbml.ext.render.RenderGroup; import org.w3c.dom.Node; import lcsb.mapviewer.common.Configuration; 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.common.exception.*; import lcsb.mapviewer.common.geometry.PointTransformation; import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.converter.model.celldesigner.geometry.ReactionCellDesignerConverter; @@ -44,31 +26,14 @@ import lcsb.mapviewer.converter.model.sbml.SbmlBioEntityParser; import lcsb.mapviewer.converter.model.sbml.SbmlParameterParser; import lcsb.mapviewer.converter.model.sbml.compartment.SbmlCompartmentParser; import lcsb.mapviewer.converter.model.sbml.species.SbmlSpeciesParser; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.model.map.kinetics.SbmlArgument; import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; +import lcsb.mapviewer.model.map.modifier.*; import lcsb.mapviewer.model.map.modifier.Trigger; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -import lcsb.mapviewer.model.map.reaction.DissociationOperator; -import lcsb.mapviewer.model.map.reaction.InvalidReactionParticipantNumberException; -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.*; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.TruncationOperator; -import lcsb.mapviewer.model.map.reaction.type.DissociationReaction; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/ElementColorEnum.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/ElementColorEnum.java index 60d94fd7ff..44009c56f6 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/ElementColorEnum.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/ElementColorEnum.java @@ -1,25 +1,11 @@ package lcsb.mapviewer.converter.model.sbml.species; -import java.awt.Color; +import java.awt.*; import lcsb.mapviewer.common.geometry.ColorParser; import lcsb.mapviewer.model.map.compartment.OvalCompartment; import lcsb.mapviewer.model.map.compartment.SquareCompartment; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.TruncatedProtein; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; public enum ElementColorEnum { ANTISENSE_RNA(AntisenseRna.class, "#ff6666"), @@ -41,11 +27,10 @@ public enum ElementColorEnum { UNKNOWN(Unknown.class, "#cccccc"), ; + ColorParser colorParser = new ColorParser(); private Class<? extends Element> clazz; private Color color; - ColorParser colorParser = new ColorParser(); - private ElementColorEnum(Class<? extends Element> clazz, String color) { this.clazz = clazz; if (color != null) { diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SBOTermSpeciesType.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SBOTermSpeciesType.java index 1be4927e69..7c63e65aa6 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SBOTermSpeciesType.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SBOTermSpeciesType.java @@ -3,23 +3,10 @@ package lcsb.mapviewer.converter.model.sbml.species; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.TruncatedProtein; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; public enum SBOTermSpeciesType { ANTISENSE_RNA(AntisenseRna.class, new String[] { "SBO:0000334" }), @@ -39,8 +26,8 @@ public enum SBOTermSpeciesType { ; private static Logger logger = LogManager.getLogger(SBOTermSpeciesType.class); - private List<String> sboTerms = new ArrayList<>(); Class<? extends Species> clazz; + private List<String> sboTerms = new ArrayList<>(); private SBOTermSpeciesType(Class<? extends Species> clazz, String[] inputSboTerms) { this.clazz = clazz; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporter.java index 0dd1cf3936..36598c25f6 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporter.java @@ -1,37 +1,18 @@ package lcsb.mapviewer.converter.model.sbml.species; -import java.awt.Color; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; +import java.awt.*; +import java.util.*; import java.util.List; -import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.Model; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.BoundingBox; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.GeneralGlyph; +import org.sbml.jsbml.ext.layout.*; import org.sbml.jsbml.ext.layout.Point; -import org.sbml.jsbml.ext.layout.ReferenceGlyph; -import org.sbml.jsbml.ext.layout.TextGlyph; -import org.sbml.jsbml.ext.multi.MultiModelPlugin; -import org.sbml.jsbml.ext.multi.MultiSpeciesPlugin; -import org.sbml.jsbml.ext.multi.MultiSpeciesType; -import org.sbml.jsbml.ext.multi.PossibleSpeciesFeatureValue; -import org.sbml.jsbml.ext.multi.SpeciesFeature; -import org.sbml.jsbml.ext.multi.SpeciesFeatureType; -import org.sbml.jsbml.ext.multi.SpeciesFeatureValue; -import org.sbml.jsbml.ext.render.Ellipse; -import org.sbml.jsbml.ext.render.HTextAnchor; -import org.sbml.jsbml.ext.render.LocalRenderInformation; -import org.sbml.jsbml.ext.render.LocalStyle; +import org.sbml.jsbml.ext.multi.*; +import org.sbml.jsbml.ext.render.*; import org.sbml.jsbml.ext.render.Rectangle; -import org.sbml.jsbml.ext.render.RenderGroup; -import org.sbml.jsbml.ext.render.VTextAnchor; import lcsb.mapviewer.converter.model.sbml.SbmlElementExporter; import lcsb.mapviewer.converter.model.sbml.SbmlExtension; @@ -40,25 +21,8 @@ import lcsb.mapviewer.converter.model.sbml.extension.multi.BioEntityFeature; import lcsb.mapviewer.converter.model.sbml.extension.multi.MultiPackageNamingUtils; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Chemical; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -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.model.map.species.field.AbstractRegionModification; -import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.jsbml.Species> { @@ -70,6 +34,8 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j private static Logger logger = LogManager.getLogger(SbmlSpeciesExporter.class); private SbmlCompartmentExporter compartmentExporter; + private int modificationResidueCounter = 0; + private Map<String, String> modificationResidueIds = new HashMap<>(); public SbmlSpeciesExporter(Model sbmlModel, lcsb.mapviewer.model.map.model.Model minervaModel, @@ -79,32 +45,6 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j this.compartmentExporter = compartmentExporter; } - @Override - public org.sbml.jsbml.Species createSbmlElement(Species element) throws InconsistentModelException { - org.sbml.jsbml.Species result = getSbmlModel().createSpecies("species_" + (getNextId())); - result.setSBOTerm(SBOTermSpeciesType.getTermByType(element.getClass())); - result.setCompartment(compartmentExporter.getSbmlElement(element.getCompartment())); - if (element.getInitialAmount() != null) { - result.setInitialAmount(element.getInitialAmount()); - } - if (element.getInitialConcentration() != null) { - result.setInitialConcentration(element.getInitialConcentration()); - } - if (element.hasOnlySubstanceUnits() != null) { - result.setHasOnlySubstanceUnits(element.hasOnlySubstanceUnits()); - } - if (element.getBoundaryCondition() != null) { - result.setBoundaryCondition(element.getBoundaryCondition()); - } - if (element.getConstant() != null) { - result.setConstant(element.getConstant()); - } - if (isExtensionEnabled(SbmlExtension.MULTI)) { - assignMultiExtensionData(element, result); - } - return result; - } - private void assignMultiExtensionData(Species element, org.sbml.jsbml.Species result) { MultiSpeciesPlugin multiExtension = new MultiSpeciesPlugin(result); MultiSpeciesType speciesType = getMultiSpeciesType(element); @@ -380,14 +320,34 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j } @Override - protected AbstractReferenceGlyph createElementGlyph(String sbmlElementId, String glyphId) { - AbstractReferenceGlyph speciesGlyph = getLayout().createSpeciesGlyph(glyphId, sbmlElementId); - return speciesGlyph; + protected List<Species> getElementList() { + return getMinervaModel().getSpeciesList(); } @Override - protected List<Species> getElementList() { - return getMinervaModel().getSpeciesList(); + public org.sbml.jsbml.Species createSbmlElement(Species element) throws InconsistentModelException { + org.sbml.jsbml.Species result = getSbmlModel().createSpecies("species_" + (getNextId())); + result.setSBOTerm(SBOTermSpeciesType.getTermByType(element.getClass())); + result.setCompartment(compartmentExporter.getSbmlElement(element.getCompartment())); + if (element.getInitialAmount() != null) { + result.setInitialAmount(element.getInitialAmount()); + } + if (element.getInitialConcentration() != null) { + result.setInitialConcentration(element.getInitialConcentration()); + } + if (element.hasOnlySubstanceUnits() != null) { + result.setHasOnlySubstanceUnits(element.hasOnlySubstanceUnits()); + } + if (element.getBoundaryCondition() != null) { + result.setBoundaryCondition(element.getBoundaryCondition()); + } + if (element.getConstant() != null) { + result.setConstant(element.getConstant()); + } + if (isExtensionEnabled(SbmlExtension.MULTI)) { + assignMultiExtensionData(element, result); + } + return result; } @Override @@ -449,6 +409,12 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j return result; } + @Override + protected AbstractReferenceGlyph createElementGlyph(String sbmlElementId, String glyphId) { + AbstractReferenceGlyph speciesGlyph = getLayout().createSpeciesGlyph(glyphId, sbmlElementId); + return speciesGlyph; + } + @Override protected LocalStyle createStyle(Species element) { LocalStyle style = super.createStyle(element); @@ -486,6 +452,34 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j return style; } + @Override + protected void assignLayoutToGlyph(Species element, AbstractReferenceGlyph speciesGlyph) { + super.assignLayoutToGlyph(element, speciesGlyph); + if (isExtensionEnabled(SbmlExtension.MULTI)) { + if (element instanceof SpeciesWithModificationResidue) { + for (ModificationResidue mr : ((SpeciesWithModificationResidue) element).getModificationResidues()) { + createModificationGlyph(mr, speciesGlyph); + } + } + } + TextGlyph textGlyph = getLayout().createTextGlyph("text_" + element.getElementId(), element.getName()); + textGlyph + .setBoundingBox(createBoundingBox(element.getX(), element.getY(), element.getZ() + 1, element.getWidth(), + element.getHeight())); + textGlyph.setReference(speciesGlyph.getId()); + + if (isExtensionEnabled(SbmlExtension.RENDER)) { + LocalRenderInformation renderInformation = getRenderInformation(getRenderPlugin()); + LocalStyle style = new LocalStyle(); + style.getIDList().add(textGlyph.getId()); + style.setGroup(new RenderGroup()); + style.getGroup().setVTextAnchor(VTextAnchor.MIDDLE); + style.getGroup().setTextAnchor(HTextAnchor.MIDDLE); + renderInformation.addLocalStyle(style); + } + + } + @SuppressWarnings("unchecked") private MultiSpeciesType createSpeciesTypeForClass(MultiModelPlugin multiPlugin, Class<? extends Element> clazz) { MultiSpeciesType speciesType = new MultiSpeciesType(); @@ -533,34 +527,6 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j return result; } - @Override - protected void assignLayoutToGlyph(Species element, AbstractReferenceGlyph speciesGlyph) { - super.assignLayoutToGlyph(element, speciesGlyph); - if (isExtensionEnabled(SbmlExtension.MULTI)) { - if (element instanceof SpeciesWithModificationResidue) { - for (ModificationResidue mr : ((SpeciesWithModificationResidue) element).getModificationResidues()) { - createModificationGlyph(mr, speciesGlyph); - } - } - } - TextGlyph textGlyph = getLayout().createTextGlyph("text_" + element.getElementId(), element.getName()); - textGlyph - .setBoundingBox(createBoundingBox(element.getX(), element.getY(), element.getZ() + 1, element.getWidth(), - element.getHeight())); - textGlyph.setReference(speciesGlyph.getId()); - - if (isExtensionEnabled(SbmlExtension.RENDER)) { - LocalRenderInformation renderInformation = getRenderInformation(getRenderPlugin()); - LocalStyle style = new LocalStyle(); - style.getIDList().add(textGlyph.getId()); - style.setGroup(new RenderGroup()); - style.getGroup().setVTextAnchor(VTextAnchor.MIDDLE); - style.getGroup().setTextAnchor(HTextAnchor.MIDDLE); - renderInformation.addLocalStyle(style); - } - - } - private void createModificationGlyph(ModificationResidue mr, AbstractReferenceGlyph speciesGlyph) { org.sbml.jsbml.Species sbmlSpecies = getSbmlModel().getSpecies(speciesGlyph.getReference()); @@ -610,9 +576,6 @@ public class SbmlSpeciesExporter extends SbmlElementExporter<Species, org.sbml.j return boundingBox; } - private int modificationResidueCounter = 0; - private Map<String, String> modificationResidueIds = new HashMap<>(); - private String getModificationResidueUniqueId(ModificationResidue mr) { SpeciesWithModificationResidue species = (SpeciesWithModificationResidue) mr.getSpecies(); String modificationId = "mod" + species.getModificationResidues().indexOf(mr); diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParser.java index 2cc9689aef..e7d30390f9 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParser.java @@ -5,25 +5,12 @@ import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.Model; -import org.sbml.jsbml.ext.layout.AbstractReferenceGlyph; -import org.sbml.jsbml.ext.layout.CompartmentGlyph; -import org.sbml.jsbml.ext.layout.GeneralGlyph; -import org.sbml.jsbml.ext.layout.GraphicalObject; -import org.sbml.jsbml.ext.layout.ReferenceGlyph; -import org.sbml.jsbml.ext.layout.SpeciesGlyph; -import org.sbml.jsbml.ext.multi.MultiModelPlugin; -import org.sbml.jsbml.ext.multi.MultiSpeciesPlugin; -import org.sbml.jsbml.ext.multi.MultiSpeciesType; -import org.sbml.jsbml.ext.multi.OutwardBindingSite; -import org.sbml.jsbml.ext.multi.PossibleSpeciesFeatureValue; -import org.sbml.jsbml.ext.multi.SpeciesFeature; -import org.sbml.jsbml.ext.multi.SpeciesFeatureType; -import org.sbml.jsbml.ext.multi.SpeciesFeatureValue; -import org.sbml.jsbml.ext.multi.SpeciesTypeInstance; -import org.sbml.jsbml.ext.multi.SubListOfSpeciesFeature; +import org.sbml.jsbml.ext.layout.*; +import org.sbml.jsbml.ext.multi.*; import org.sbml.jsbml.ext.render.LocalStyle; import lcsb.mapviewer.common.Pair; @@ -33,81 +20,19 @@ import lcsb.mapviewer.converter.model.sbml.SbmlElementParser; import lcsb.mapviewer.converter.model.sbml.extension.multi.BioEntityFeature; import lcsb.mapviewer.converter.model.sbml.extension.multi.MultiPackageNamingUtils; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; -import lcsb.mapviewer.model.map.species.field.AbstractRegionModification; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.PositionToCompartment; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.SpeciesWithBindingRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithCodingRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationSite; -import lcsb.mapviewer.model.map.species.field.SpeciesWithProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.SpeciesWithRegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithResidue; -import lcsb.mapviewer.model.map.species.field.SpeciesWithTranscriptionSite; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; import lcsb.mapviewer.modelutils.map.ElementUtils; public class SbmlSpeciesParser extends SbmlElementParser<org.sbml.jsbml.Species> { - Logger logger = LogManager.getLogger(SbmlSpeciesParser.class); - private static String ARTIFITIAL_SINK_ID = "sbml_artifitial_sink"; private static String ARTIFITIAL_SOURCE_ID = "sbml_artifitial_source"; + Logger logger = LogManager.getLogger(SbmlSpeciesParser.class); public SbmlSpeciesParser(Model model, lcsb.mapviewer.model.map.model.Model minervaModel) { super(model, minervaModel); } - @SuppressWarnings("deprecation") - @Override - protected Species parse(org.sbml.jsbml.Species species) throws InvalidInputDataExecption { - String sboTerm = extractSBOTermFromSpecies(species); - Class<? extends Species> clazz = SBOTermSpeciesType.getTypeSBOTerm(sboTerm); - try { - Species result = clazz.getConstructor(String.class).newInstance(species.getId()); - if (!Double.isNaN(species.getInitialAmount())) { - result.setInitialAmount(species.getInitialAmount()); - } - if (!Double.isNaN(species.getInitialConcentration())) { - result.setInitialConcentration(species.getInitialConcentration()); - } - if (species.isSetHasOnlySubstanceUnits()) { - result.setOnlySubstanceUnits(species.hasOnlySubstanceUnits()); - } - if (species.isSetBoundaryCondition()) { - result.setBoundaryCondition(species.getBoundaryCondition()); - } - if (species.isSetConstant()) { - result.setConstant(species.getConstant()); - } - if (species.isSetCharge()) { - result.setCharge(species.getCharge()); - } - assignBioEntityData(species, result); - if (getLayout() == null) { - assignCompartment(result, species.getCompartment()); - } - if (getMultiPlugin() != null) { - assignMultiData(species, result); - } - return result; - } catch (SecurityException | NoSuchMethodException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - throw new InvalidStateException(e); - } - } - private void assignMultiData(org.sbml.jsbml.Species sbmlSpecies, Species minervaElement) { String warnPrefix = new ElementUtils().getElementTag(minervaElement); MultiModelPlugin multiPlugin = getMultiPlugin(); @@ -360,28 +285,6 @@ public class SbmlSpeciesParser extends SbmlElementParser<org.sbml.jsbml.Species> return sboTerm; } - @Override - public List<Element> mergeLayout(List<? extends Element> elements) - throws InvalidInputDataExecption { - List<Element> result = super.mergeLayout(elements); - - for (Element element : result) { - String compartmentId = null; - if (getLayout().getSpeciesGlyph(element.getElementId()) != null) { - compartmentId = ((org.sbml.jsbml.Species) getLayout().getSpeciesGlyph(element.getElementId()) - .getSpeciesInstance()).getCompartment(); - } else { - if (!element.getElementId().equals(ARTIFITIAL_SINK_ID) - && !element.getElementId().equals(ARTIFITIAL_SOURCE_ID)) { - compartmentId = getSbmlModel().getSpecies(element.getElementId()).getCompartment(); - } - } - assignCompartment(element, compartmentId); - assignModificationResiduesLayout(element); - } - return result; - } - private void assignModificationResiduesLayout(Element element) { if (element instanceof SpeciesWithModificationResidue) { for (ModificationResidue mr : ((SpeciesWithModificationResidue) element).getModificationResidues()) { @@ -454,10 +357,23 @@ public class SbmlSpeciesParser extends SbmlElementParser<org.sbml.jsbml.Species> } @Override - protected List<Pair<String, AbstractReferenceGlyph>> getGlyphs() { - List<Pair<String, AbstractReferenceGlyph>> result = new ArrayList<>(); - for (SpeciesGlyph glyph : getLayout().getListOfSpeciesGlyphs()) { - result.add(new Pair<String, AbstractReferenceGlyph>(glyph.getSpecies(), glyph)); + public List<Element> mergeLayout(List<? extends Element> elements) + throws InvalidInputDataExecption { + List<Element> result = super.mergeLayout(elements); + + for (Element element : result) { + String compartmentId = null; + if (getLayout().getSpeciesGlyph(element.getElementId()) != null) { + compartmentId = ((org.sbml.jsbml.Species) getLayout().getSpeciesGlyph(element.getElementId()) + .getSpeciesInstance()).getCompartment(); + } else { + if (!element.getElementId().equals(ARTIFITIAL_SINK_ID) + && !element.getElementId().equals(ARTIFITIAL_SOURCE_ID)) { + compartmentId = getSbmlModel().getSpecies(element.getElementId()).getCompartment(); + } + } + assignCompartment(element, compartmentId); + assignModificationResiduesLayout(element); } return result; } @@ -471,6 +387,54 @@ public class SbmlSpeciesParser extends SbmlElementParser<org.sbml.jsbml.Species> } } + @Override + protected List<Pair<String, AbstractReferenceGlyph>> getGlyphs() { + List<Pair<String, AbstractReferenceGlyph>> result = new ArrayList<>(); + for (SpeciesGlyph glyph : getLayout().getListOfSpeciesGlyphs()) { + result.add(new Pair<String, AbstractReferenceGlyph>(glyph.getSpecies(), glyph)); + } + return result; + } + + @SuppressWarnings("deprecation") + @Override + protected Species parse(org.sbml.jsbml.Species species) throws InvalidInputDataExecption { + String sboTerm = extractSBOTermFromSpecies(species); + Class<? extends Species> clazz = SBOTermSpeciesType.getTypeSBOTerm(sboTerm); + try { + Species result = clazz.getConstructor(String.class).newInstance(species.getId()); + if (!Double.isNaN(species.getInitialAmount())) { + result.setInitialAmount(species.getInitialAmount()); + } + if (!Double.isNaN(species.getInitialConcentration())) { + result.setInitialConcentration(species.getInitialConcentration()); + } + if (species.isSetHasOnlySubstanceUnits()) { + result.setOnlySubstanceUnits(species.hasOnlySubstanceUnits()); + } + if (species.isSetBoundaryCondition()) { + result.setBoundaryCondition(species.getBoundaryCondition()); + } + if (species.isSetConstant()) { + result.setConstant(species.getConstant()); + } + if (species.isSetCharge()) { + result.setCharge(species.getCharge()); + } + assignBioEntityData(species, result); + if (getLayout() == null) { + assignCompartment(result, species.getCompartment()); + } + if (getMultiPlugin() != null) { + assignMultiData(species, result); + } + return result; + } catch (SecurityException | NoSuchMethodException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + throw new InvalidStateException(e); + } + } + public Species getArtifitialInput() { Species result = getMinervaModel().getElementByElementId(ARTIFITIAL_SOURCE_ID); if (result == null) { diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitExporter.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitExporter.java index 862d14cb43..7697a49a1b 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitExporter.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitExporter.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml.units; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.Unit; import org.sbml.jsbml.UnitDefinition; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitsParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitsParser.java index 22301f7a12..2f08458469 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitsParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/SbmlUnitsParser.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.converter.model.sbml.units; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.apache.logging.log4j.*; -import org.sbml.jsbml.ListOf; -import org.sbml.jsbml.Model; -import org.sbml.jsbml.Unit; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.sbml.jsbml.*; import lcsb.mapviewer.converter.model.sbml.SbmlBioEntityParser; import lcsb.mapviewer.model.map.kinetics.SbmlUnit; diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/UnitMapping.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/UnitMapping.java index 4a75ac6ea5..aa896136fa 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/UnitMapping.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/units/UnitMapping.java @@ -86,6 +86,7 @@ public enum UnitMapping { } throw new InvalidArgumentException("Unknown sbml unit type: " + unitType); } + public static SbmlUnitType kindToUnitType(Kind kind) { for (UnitMapping mapping : UnitMapping.values()) { if (mapping.sbmlUnitType == kind) { diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java index 414011212d..f8ead7384e 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CellDesignerToMultiExportTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.*; import java.nio.file.*; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java index 10e04d311f..06c9f46030 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/CopasiImportTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.nio.file.*; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java index 015e5fe987..93dcd2667c 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExport.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.*; import java.util.ArrayList; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java index 0d05998028..fb1a3ebf48 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToLayoutTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.*; import java.util.ArrayList; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java index af722e4bb0..599bdc249d 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ElementPropertiesExportToMultiTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.*; import java.util.*; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java index 2b46babbaf..524ac55de4 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.*; import java.nio.file.*; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java index 4c56a69dfc..c554d42155 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/GenericSbmlToXmlParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.File; import java.io.IOException; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java index 13afe4a261..e7a310b610 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/MultiParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.*; import java.nio.file.*; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java index 19c2ee4938..5a37355f88 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/ReactionPropertiesExportToMultiTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; import java.io.*; @@ -26,9 +26,8 @@ import lcsb.mapviewer.model.map.species.Ion; public class ReactionPropertiesExportToMultiTest extends SbmlTestFunctions { static Logger logger = LogManager.getLogger(ReactionPropertiesExportToMultiTest.class.getName()); - - private Model model; private static String reactionId = "reactionId"; + private Model model; public ReactionPropertiesExportToMultiTest(String propertyName, Model model) { this.model = model; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporterTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporterTest.java index a349808eb9..feb38b8a57 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporterTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlBioEntityExporterTest.java @@ -1,10 +1,8 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.junit.Test; import org.mockito.Mockito; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java index 0d44c40bd7..42baf131e2 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterFromCellDesignerTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java index 0cdda07e16..08b779a2df 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlExporterTest.java @@ -2,12 +2,13 @@ package lcsb.mapviewer.converter.model.sbml; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.io.File; import java.lang.reflect.Modifier; import java.util.*; +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java index 06f0468308..7db1fbe543 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/SbmlTestFunctions.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.converter.model.sbml; -import java.awt.Desktop; +import java.awt.*; import java.awt.geom.Point2D; import java.io.*; import java.nio.file.Files; @@ -26,23 +26,37 @@ import lcsb.mapviewer.model.map.species.GenericProtein; public class SbmlTestFunctions { + private static int identifierCounter = 0; @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - + SbmlParser parser = new SbmlParser(); + SbmlExporter exporter; @SuppressWarnings("unused") private Logger logger = Logger.getLogger(SbmlTestFunctions.class); - private MinervaLoggerAppender appender; - private static int identifierCounter = 0; - - SbmlParser parser = new SbmlParser(); - SbmlExporter exporter; - public SbmlTestFunctions() { exporter = new SbmlExporter(); } + protected static GenericProtein createProtein() { + GenericProtein result = new GenericProtein("sa" + (identifierCounter++)); + result.setName("SNCA"); + result.setX(10); + result.setWidth(10); + result.setY(10); + result.setHeight(10); + result.setZ(123); + return result; + } + + protected static Compartment createCompartment() { + Compartment result = new Compartment("c" + (identifierCounter++)); + result.setZ(124); + + return result; + } + @Before public final void _setUp() throws Exception { MinervaLoggerAppender.unregisterLogEventStorage(appender); @@ -70,24 +84,6 @@ public class SbmlTestFunctions { } - protected static GenericProtein createProtein() { - GenericProtein result = new GenericProtein("sa" + (identifierCounter++)); - result.setName("SNCA"); - result.setX(10); - result.setWidth(10); - result.setY(10); - result.setHeight(10); - result.setZ(123); - return result; - } - - protected static Compartment createCompartment() { - Compartment result = new Compartment("c" + (identifierCounter++)); - result.setZ(124); - - return result; - } - protected Reaction createReaction(Element p1, Element p2) { Reaction reaction = new StateTransitionReaction("r" + (identifierCounter++)); Reactant reactant = new Reactant(p1); diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParserTest.java index 7c4274409b..a44f7d3da7 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/compartment/SbmlCompartmentParserTest.java @@ -5,7 +5,8 @@ import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; import java.io.FileNotFoundException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.common.Configuration; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExportArrowType.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExportArrowType.java index c0b35fb270..315d4169cb 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExportArrowType.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExportArrowType.java @@ -21,27 +21,13 @@ import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.converter.model.celldesigner.reaction.ReactionLineData; -import lcsb.mapviewer.converter.model.sbml.SbmlExporter; -import lcsb.mapviewer.converter.model.sbml.SbmlParser; -import lcsb.mapviewer.converter.model.sbml.SbmlTestFunctions; +import lcsb.mapviewer.converter.model.sbml.*; import lcsb.mapviewer.model.graphics.PolylineData; 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.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -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.ReactionComparator; -import lcsb.mapviewer.model.map.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.TruncationOperator; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.SimpleReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TruncationReaction; -import lcsb.mapviewer.model.map.reaction.type.TwoProductReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TwoReactantReactionInterface; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.model.map.species.Ion; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -55,6 +41,11 @@ public class SbmlReactionExportArrowType extends SbmlTestFunctions { SbmlParser parser = new SbmlParser(); SbmlExporter exporter = new SbmlExporter(); + Model modelToBeTested; + + public SbmlReactionExportArrowType(String name, Model model) { + modelToBeTested = model; + } @Parameters(name = "{index} : {0}") public static Collection<Object[]> data() throws Exception { @@ -160,12 +151,6 @@ public class SbmlReactionExportArrowType extends SbmlTestFunctions { return result; } - Model modelToBeTested; - - public SbmlReactionExportArrowType(String name, Model model) { - modelToBeTested = model; - } - @Test public void test() throws Exception { try { diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporterTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporterTest.java index 278166360e..040d60e417 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporterTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionExporterTest.java @@ -7,9 +7,7 @@ import java.util.Arrays; import org.junit.Test; import org.sbml.jsbml.Model; import org.sbml.jsbml.SBMLDocument; -import org.sbml.jsbml.ext.layout.Dimensions; -import org.sbml.jsbml.ext.layout.Layout; -import org.sbml.jsbml.ext.layout.LayoutModelPlugin; +import org.sbml.jsbml.ext.layout.*; import lcsb.mapviewer.converter.model.sbml.SbmlBioEntityExporter; import lcsb.mapviewer.converter.model.sbml.SbmlExtension; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java index 2294c84bce..138226d0ac 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/reaction/SbmlReactionParserExtractCurveTest.java @@ -29,6 +29,7 @@ public class SbmlReactionParserExtractCurveTest extends SbmlTestFunctions { private int length; private SbmlReactionParser sbmlReactionParser; + private Curve curve; public SbmlReactionParserExtractCurveTest(String name, ReactionGlyph reactionGlyph, int length) { this.glyph = reactionGlyph; @@ -37,18 +38,6 @@ public class SbmlReactionParserExtractCurveTest extends SbmlTestFunctions { sbmlReactionParser = new SbmlReactionParser(new Model(3, 2), null, null, null); } - private Curve curve; - - @Before - public final void setUp() throws Exception { - curve = new Curve(glyph.getCurve()); - } - - @After - public final void tearDown() throws Exception { - glyph.setCurve(curve); - } - @Parameters(name = "{0}") public static Collection<Object[]> data() throws IOException { Collection<Object[]> data = new ArrayList<>(); @@ -79,6 +68,16 @@ public class SbmlReactionParserExtractCurveTest extends SbmlTestFunctions { return result; } + @Before + public final void setUp() throws Exception { + curve = new Curve(glyph.getCurve()); + } + + @After + public final void tearDown() throws Exception { + glyph.setCurve(curve); + } + @Test public void testCenterLine() throws Exception { Reaction reaction = createReaction(createProtein(), createProtein()); diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporterTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporterTest.java index 642f06ed56..190972f434 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporterTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesExporterTest.java @@ -6,21 +6,18 @@ import static org.junit.Assert.assertFalse; import java.util.Arrays; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.sbml.jsbml.SBMLDocument; -import lcsb.mapviewer.converter.model.sbml.SbmlExporter; -import lcsb.mapviewer.converter.model.sbml.SbmlExtension; -import lcsb.mapviewer.converter.model.sbml.SbmlTestFunctions; +import lcsb.mapviewer.converter.model.sbml.*; import lcsb.mapviewer.converter.model.sbml.compartment.SbmlCompartmentExporter; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.compartment.Compartment; 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.model.map.species.*; public class SbmlSpeciesExporterTest extends SbmlTestFunctions { @@ -28,7 +25,6 @@ public class SbmlSpeciesExporterTest extends SbmlTestFunctions { org.sbml.jsbml.Model sbmlModel; - @Test public void testOneElementWithTwoAliases() throws InconsistentModelException { Element protein1 = createProtein(); diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java index 953cd375d4..46380cbe56 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java @@ -5,7 +5,8 @@ import static org.junit.Assert.assertTrue; import java.io.FileNotFoundException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.common.geometry.ColorParser; @@ -13,21 +14,7 @@ import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; import lcsb.mapviewer.converter.model.sbml.SbmlParser; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.IonChannelProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.ReceptorProtein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; public class SbmlSpeciesParserTest { Logger logger = LogManager.getLogger(SbmlSpeciesParserTest.class); @@ -150,8 +137,9 @@ public class SbmlSpeciesParserTest { public void testParseInitialAmount() throws Exception { Model model = parser.createModel(new ConverterParams().filename("testFiles/small/initial_amount.xml")); Species element = model.getElementByElementId("s1"); - assertEquals((Double)1.0, element.getInitialAmount()); + assertEquals((Double) 1.0, element.getInitialAmount()); } + @Test public void testParseHasOnlySubstanceUnits() throws Exception { Model model = parser.createModel(new ConverterParams().filename("testFiles/small/has_only_substance_units.xml")); diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverter.java b/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverter.java index 2fbbc1f860..e1a45aa32e 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverter.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverter.java @@ -1,43 +1,25 @@ package lcsb.mapviewer.converter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.lang.reflect.Modifier; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.common.exception.InvalidClassException; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.zip.GlyphZipEntryFile; -import lcsb.mapviewer.converter.zip.ImageZipEntryFile; -import lcsb.mapviewer.converter.zip.LayoutZipEntryFile; -import lcsb.mapviewer.converter.zip.ModelZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFile; +import lcsb.mapviewer.converter.zip.*; import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.model.*; 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.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; /** * This class allows to create complex {@link Model} that contains submaps. It's diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverterParams.java b/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverterParams.java index fb5dc23bfb..4a37d60987 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverterParams.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ComplexZipConverterParams.java @@ -1,16 +1,12 @@ package lcsb.mapviewer.converter; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.io.*; +import java.util.*; import java.util.zip.ZipFile; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.converter.zip.ZipEntryFile; import lcsb.mapviewer.model.cache.UploadedFileEntry; diff --git a/converter/src/main/java/lcsb/mapviewer/converter/Converter.java b/converter/src/main/java/lcsb/mapviewer/converter/Converter.java index 96c1cd7176..77bdcd8045 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/Converter.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/Converter.java @@ -4,10 +4,11 @@ import java.io.*; import java.nio.charset.StandardCharsets; import java.util.UUID; +import org.apache.commons.io.FileUtils; + import lcsb.mapviewer.common.MimeType; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.model.Model; -import org.apache.commons.io.FileUtils; /** * Interface used for reading data from file and putting it into {@link Model} @@ -18,86 +19,93 @@ import org.apache.commons.io.FileUtils; */ public abstract class Converter { - /** - * Parse input source and transforms it into a model object. - * - * @param params - * input params used for reading data - * @return model obtained from input source - * @throws InvalidInputDataExecption - * thrown when input parameters are invalid - */ - public abstract Model createModel(ConverterParams params) throws InvalidInputDataExecption, ConverterException; + /** + * Parse input source and transforms it into a model object. + * + * @param params + * input params used for reading data + * @return model obtained from input source + * @throws InvalidInputDataExecption + * thrown when input parameters are invalid + */ + public abstract Model createModel(ConverterParams params) throws InvalidInputDataExecption, ConverterException; - /** - * Generate String representation of the model. Traditionally often XML but can be any other format as well. - * - * @param model The MINERVA ${@link Model} to be serialized - * @return The translated Model - */ - public abstract String model2String(Model model) throws InconsistentModelException, ConverterException; + /** + * Generate String representation of the model. Traditionally often XML but can + * be any other format as well. + * + * @param model + * The MINERVA ${@link Model} to be serialized + * @return The translated Model + */ + public abstract String model2String(Model model) throws InconsistentModelException, ConverterException; - /** - * Returns a common name of data format used in the converter. - * - * @return common name of data format used in the converter - */ - public abstract String getCommonName(); + /** + * Returns a common name of data format used in the converter. + * + * @return common name of data format used in the converter + */ + public abstract String getCommonName(); - /** - * Returns {@link MimeType} of the exported data. - * - * @return {@link MimeType} of the exported data - */ - public abstract MimeType getMimeType(); + /** + * Returns {@link MimeType} of the exported data. + * + * @return {@link MimeType} of the exported data + */ + public abstract MimeType getMimeType(); - /** - * Returns extension of the exported file. - * - * @return extension of the exported file - */ - public abstract String getFileExtension(); + /** + * Returns extension of the exported file. + * + * @return extension of the exported file + */ + public abstract String getFileExtension(); - /** - * Export model to {@link InputStream}. - * - * @param model model to be exported - * @return {@link InputStream} with exported data - * @throws InconsistentModelException thrown when given model is inconsistent and unable to be exported - */ - public InputStream model2InputStream(Model model) - throws InconsistentModelException, ConverterException { - String modelString = model2String(model); - return new ByteArrayInputStream(modelString.getBytes(StandardCharsets.UTF_8)); - } + /** + * Export model to {@link InputStream}. + * + * @param model + * model to be exported + * @return {@link InputStream} with exported data + * @throws InconsistentModelException + * thrown when given model is inconsistent and unable to be exported + */ + public InputStream model2InputStream(Model model) + throws InconsistentModelException, ConverterException { + String modelString = model2String(model); + return new ByteArrayInputStream(modelString.getBytes(StandardCharsets.UTF_8)); + } - /** - * Export model to {@link File}. - * - * @param model model to be exported - * @param filePath exported file path - * @return {@link File} with exported data - * @throws InconsistentModelException thrown when given model is inconsistent and unable to be exported - */ - public File model2File(Model model, String filePath) - throws InconsistentModelException, IOException, ConverterException { - String modelString = model2String(model); - File file = new File(filePath); + /** + * Export model to {@link File}. + * + * @param model + * model to be exported + * @param filePath + * exported file path + * @return {@link File} with exported data + * @throws InconsistentModelException + * thrown when given model is inconsistent and unable to be exported + */ + public File model2File(Model model, String filePath) + throws InconsistentModelException, IOException, ConverterException { + String modelString = model2String(model); + File file = new File(filePath); File parentFile = file.getParentFile(); if (parentFile != null) { parentFile.mkdirs(); } - try (PrintWriter out = new PrintWriter(file)) { - out.println(modelString); - } - return new File(filePath); - } + try (PrintWriter out = new PrintWriter(file)) { + out.println(modelString); + } + return new File(filePath); + } - public File inputStream2File(InputStream inputStream) throws IOException { - File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); - tempFile.deleteOnExit(); - FileUtils.copyInputStreamToFile(inputStream, tempFile); - return tempFile; - } + public File inputStream2File(InputStream inputStream) throws IOException { + File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); + tempFile.deleteOnExit(); + FileUtils.copyInputStreamToFile(inputStream, tempFile); + return tempFile; + } } diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ConverterException.java b/converter/src/main/java/lcsb/mapviewer/converter/ConverterException.java index fad178973d..78605cf808 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ConverterException.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ConverterException.java @@ -1,56 +1,56 @@ package lcsb.mapviewer.converter; /** - * Generic exception thrown when implementation of {@link Converter} encounter - * a problem. + * Generic exception thrown when implementation of {@link Converter} encounter a + * problem. * * @author Piotr Gawron * */ public class ConverterException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with exception message. - * - * @param message - * error message - */ - public ConverterException(String message) { - super(message); - } + /** + * Default constructor with exception message. + * + * @param message + * error message + */ + public ConverterException(String message) { + super(message); + } - /** - * Default constructor with super exception as a source. - * - * @param e - * super exception - */ - public ConverterException(Exception e) { - super(e); - } + /** + * Default constructor with super exception as a source. + * + * @param e + * super exception + */ + public ConverterException(Exception e) { + super(e); + } - /** - * Default constructor - initializes instance variable to unknown. - */ + /** + * Default constructor - initializes instance variable to unknown. + */ - public ConverterException() { - super(); // call superclass constructor - } + public ConverterException() { + super(); // call superclass constructor + } - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * super exception - */ - public ConverterException(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * super exception + */ + public ConverterException(String message, Exception e) { + super(message, e); + } } \ No newline at end of file diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ConverterParams.java b/converter/src/main/java/lcsb/mapviewer/converter/ConverterParams.java index d774588c8b..214a3bb95a 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ConverterParams.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ConverterParams.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.converter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; +import java.io.*; import org.apache.xerces.xni.parser.XMLInputSource; diff --git a/converter/src/main/java/lcsb/mapviewer/converter/GlyphParser.java b/converter/src/main/java/lcsb/mapviewer/converter/GlyphParser.java index 79d5062a22..ae7e3d3bed 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/GlyphParser.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/GlyphParser.java @@ -6,7 +6,8 @@ import java.util.zip.ZipFile; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.converter.zip.GlyphZipEntryFile; import lcsb.mapviewer.model.cache.UploadedFileEntry; diff --git a/converter/src/main/java/lcsb/mapviewer/converter/InvalidCoordinatesFile.java b/converter/src/main/java/lcsb/mapviewer/converter/InvalidCoordinatesFile.java index cf6037be29..a558f73ca4 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/InvalidCoordinatesFile.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/InvalidCoordinatesFile.java @@ -1,51 +1,51 @@ package lcsb.mapviewer.converter; - /** * Exception thrown when the {@link OverviewParser#COORDINATES_FILENAME image - * link coordinates file} in {@link lcsb.mapviewer.converter.zip.InputFileType#OVERLAY_IMAGE_DATA input file} - * is invalid. + * link coordinates file} in + * {@link lcsb.mapviewer.converter.zip.InputFileType#OVERLAY_IMAGE_DATA input + * file} is invalid. * * @author Piotr Gawron * */ public class InvalidCoordinatesFile extends InvalidOverviewFile { - /** - * Default constructor. - * - * @param e - * parent exception (reason) - */ - public InvalidCoordinatesFile(Exception e) { - super(e); - } + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * parent exception (reason) - */ - public InvalidCoordinatesFile(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param e + * parent exception (reason) + */ + public InvalidCoordinatesFile(Exception e) { + super(e); + } - /** - * Default constructor. - * - * @param message - * exception message - */ - public InvalidCoordinatesFile(String message) { - super(message); - } + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * parent exception (reason) + */ + public InvalidCoordinatesFile(String message, Exception e) { + super(message, e); + } - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Default constructor. + * + * @param message + * exception message + */ + public InvalidCoordinatesFile(String message) { + super(message); + } } diff --git a/converter/src/main/java/lcsb/mapviewer/converter/InvalidOverviewFile.java b/converter/src/main/java/lcsb/mapviewer/converter/InvalidOverviewFile.java index 45c1a26809..cd96f56f85 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/InvalidOverviewFile.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/InvalidOverviewFile.java @@ -1,9 +1,9 @@ package lcsb.mapviewer.converter; - /** - * Exception thrown when the {@link lcsb.mapviewer.converter.zip.InputFileType#OVERLAY_IMAGE_DATA input file - * * } containing data about {@link lcsb.mapviewer.model.map.OverviewImage + * Exception thrown when the + * {@link lcsb.mapviewer.converter.zip.InputFileType#OVERLAY_IMAGE_DATA input + * file * } containing data about {@link lcsb.mapviewer.model.map.OverviewImage * overview images} is invalid. * * @author Piotr Gawron @@ -11,41 +11,41 @@ package lcsb.mapviewer.converter; */ public class InvalidOverviewFile extends InvalidInputDataExecption { - /** - * Default constructor. - * - * @param e - * parent exception (reason) - */ - public InvalidOverviewFile(Exception e) { - super(e); - } + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * exception message - * @param e - * parent exception (reason) - */ - public InvalidOverviewFile(String message, Exception e) { - super(message, e); - } + /** + * Default constructor. + * + * @param e + * parent exception (reason) + */ + public InvalidOverviewFile(Exception e) { + super(e); + } - /** - * Default constructor. - * - * @param message - * exception message - */ - public InvalidOverviewFile(String message) { - super(message); - } + /** + * Default constructor. + * + * @param message + * exception message + * @param e + * parent exception (reason) + */ + public InvalidOverviewFile(String message, Exception e) { + super(message, e); + } - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Default constructor. + * + * @param message + * exception message + */ + public InvalidOverviewFile(String message) { + super(message); + } } diff --git a/converter/src/main/java/lcsb/mapviewer/converter/OverviewParser.java b/converter/src/main/java/lcsb/mapviewer/converter/OverviewParser.java index 6bef70719c..4c162fed12 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/OverviewParser.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/OverviewParser.java @@ -1,34 +1,24 @@ package lcsb.mapviewer.converter; -import java.awt.Polygon; +import java.awt.*; import java.awt.geom.Area; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; +import java.io.*; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import javax.imageio.ImageIO; import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.zip.ImageZipEntryFile; -import lcsb.mapviewer.model.map.OverviewImage; -import lcsb.mapviewer.model.map.OverviewImageLink; -import lcsb.mapviewer.model.map.OverviewLink; -import lcsb.mapviewer.model.map.OverviewModelLink; -import lcsb.mapviewer.model.map.OverviewSearchLink; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; /** @@ -328,7 +318,7 @@ public class OverviewParser { } String filename = columns[filenameColumn]; String polygon = columns[polygonColumn]; - String modelName = FilenameUtils.getBaseName(columns[targetFilenameColumn]); + String modelName = FilenameUtils.getBaseName(columns[targetFilenameColumn]); String coord = columns[redirectionCoordinatesColumn]; String zoomLevel = columns[zoomLevelColumn]; String linkType = columns[targetTypeColumn]; diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java b/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java index 869980f1b9..ee388ac99a 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ProjectFactory.java @@ -1,28 +1,18 @@ package lcsb.mapviewer.converter; import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.converter.zip.GlyphZipEntryFile; -import lcsb.mapviewer.converter.zip.ImageZipEntryFile; -import lcsb.mapviewer.converter.zip.LayoutZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFile; +import lcsb.mapviewer.converter.zip.*; import lcsb.mapviewer.model.Project; -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.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; +import lcsb.mapviewer.model.map.layout.graphics.*; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Element; public class ProjectFactory { diff --git a/converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java b/converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java index c491491e18..4bbbf82354 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/ZIndexPopulator.java @@ -1,10 +1,9 @@ package lcsb.mapviewer.converter; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.comparator.DoubleComparator; @@ -14,9 +13,7 @@ import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.model.Model; 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.model.map.species.*; /** * This util class populate with z-index data if necessary. diff --git a/converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java b/converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java index 96b1582d9d..4c811618c5 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/annotation/XmlAnnotationParser.java @@ -2,26 +2,16 @@ package lcsb.mapviewer.converter.annotation; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Author; /** diff --git a/converter/src/main/java/lcsb/mapviewer/converter/package-info.java b/converter/src/main/java/lcsb/mapviewer/converter/package-info.java index 4ebbd0ce6b..9fea77d73d 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/package-info.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/package-info.java @@ -4,4 +4,3 @@ * */ package lcsb.mapviewer.converter; - diff --git a/converter/src/main/java/lcsb/mapviewer/converter/zip/InputFileType.java b/converter/src/main/java/lcsb/mapviewer/converter/zip/InputFileType.java index 5c933d2fca..75cfe57902 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/zip/InputFileType.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/zip/InputFileType.java @@ -8,36 +8,36 @@ package lcsb.mapviewer.converter.zip; * */ public enum InputFileType { - /** - * Identifies file which is CellDesigner file. - */ - CELLDESIGNER("CellDesigner (*.xml)"), + /** + * Identifies file which is CellDesigner file. + */ + CELLDESIGNER("CellDesigner (*.xml)"), - /** - * Unknown file type. - */ - UNKNOWN("Unknown (*.*)"); + /** + * Unknown file type. + */ + UNKNOWN("Unknown (*.*)"); - /** - * Common name used for the type. - */ - private String commonName; + /** + * Common name used for the type. + */ + private String commonName; - /** - * Default constructor. - * - * @param commonName - * {@link #commonName} - */ - InputFileType(String commonName) { - this.commonName = commonName; - } + /** + * Default constructor. + * + * @param commonName + * {@link #commonName} + */ + InputFileType(String commonName) { + this.commonName = commonName; + } - /** - * @return the commonName - * @see #commonName - */ - public String getCommonName() { - return commonName; - } + /** + * @return the commonName + * @see #commonName + */ + public String getCommonName() { + return commonName; + } } diff --git a/converter/src/main/java/lcsb/mapviewer/converter/zip/ModelZipEntryFile.java b/converter/src/main/java/lcsb/mapviewer/converter/zip/ModelZipEntryFile.java index b2569f492f..6a238e40f8 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/zip/ModelZipEntryFile.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/zip/ModelZipEntryFile.java @@ -13,188 +13,188 @@ import lcsb.mapviewer.model.map.model.SubmodelType; * */ public class ModelZipEntryFile extends ZipEntryFile implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Name that should be used for the file. - */ - private String name; - - /** - * Is the file root (top) model in the project. - */ - private String root = "false"; - - /** - * Is the file a mapping file. - */ - private String mapping = "false"; - - /** - * What kind of submodel it is. - */ - private SubmodelType type = SubmodelType.UNKNOWN; - - /** - * Type of the input file. For now we accept only CellDesigner files, but in - * future it will change. - */ - private InputFileType fileType = InputFileType.UNKNOWN; - - /** - * Default constructor. - */ - public ModelZipEntryFile() { - - } - - /** - * Constructor that initializes all params. - * - * @param filename - * {@link #filename} - * @param name - * {@link #name} - * @param root - * {@link #root} - * @param mapping - * {@link #mapping} - * @param type - * {@link #type} - */ - public ModelZipEntryFile(String filename, String name, boolean root, boolean mapping, SubmodelType type) { - setFilename(filename); - if (name == null && !mapping) { - throw new InvalidArgumentException("Name cannot be null for submap"); - } - this.name = name; - this.root = root + ""; - this.mapping = mapping + ""; - this.type = type; - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the type - * @see #type - */ - public SubmodelType getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(SubmodelType type) { - this.type = type; - } - - /** - * @return the root - * @see #root - */ - public String getRoot() { - return root; - } - - /** - * @param root - * the root to set - * @see #root - */ - public void setRoot(String root) { - this.root = root; - } - - /** - * @return the mapping - * @see #mapping - */ - public String getMapping() { - return mapping; - } - - /** - * @param mapping - * the mapping to set - * @see #mapping - */ - public void setMapping(String mapping) { - this.mapping = mapping; - } - - /** - * @return the fileType - * @see #fileType - */ - public InputFileType getFileType() { - return fileType; - } - - /** - * @param fileType - * the fileType to set - * @see #fileType - */ - public void setFileType(InputFileType fileType) { - this.fileType = fileType; - } - - /** - * Sets {@link #root} vale. - * - * @param root - * new {@link #root} value - */ - public void setRoot(boolean root) { - if (root) { - setRoot("true"); - } else { - setRoot("false"); - } - } - - /** - * Returns <code>true</code> if {@link #root} is positive, <code>false</code> - * otherwise. - * - * @return <code>true</code> if {@link #root} is positive, <code>false</code> - * otherwise - */ - public boolean isRoot() { - return "true".equalsIgnoreCase(root); - } - - /** - * Returns <code>true</code> if {@link #mapping} is positive, - * <code>false</code> otherwise. - * - * @return <code>true</code> if {@link #mapping} is positive, - * <code>false</code> otherwise - */ - public boolean isMappingFile() { - return "true".equalsIgnoreCase(mapping); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Name that should be used for the file. + */ + private String name; + + /** + * Is the file root (top) model in the project. + */ + private String root = "false"; + + /** + * Is the file a mapping file. + */ + private String mapping = "false"; + + /** + * What kind of submodel it is. + */ + private SubmodelType type = SubmodelType.UNKNOWN; + + /** + * Type of the input file. For now we accept only CellDesigner files, but in + * future it will change. + */ + private InputFileType fileType = InputFileType.UNKNOWN; + + /** + * Default constructor. + */ + public ModelZipEntryFile() { + + } + + /** + * Constructor that initializes all params. + * + * @param filename + * {@link #filename} + * @param name + * {@link #name} + * @param root + * {@link #root} + * @param mapping + * {@link #mapping} + * @param type + * {@link #type} + */ + public ModelZipEntryFile(String filename, String name, boolean root, boolean mapping, SubmodelType type) { + setFilename(filename); + if (name == null && !mapping) { + throw new InvalidArgumentException("Name cannot be null for submap"); + } + this.name = name; + this.root = root + ""; + this.mapping = mapping + ""; + this.type = type; + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the type + * @see #type + */ + public SubmodelType getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(SubmodelType type) { + this.type = type; + } + + /** + * @return the root + * @see #root + */ + public String getRoot() { + return root; + } + + /** + * @return the mapping + * @see #mapping + */ + public String getMapping() { + return mapping; + } + + /** + * @param mapping + * the mapping to set + * @see #mapping + */ + public void setMapping(String mapping) { + this.mapping = mapping; + } + + /** + * @return the fileType + * @see #fileType + */ + public InputFileType getFileType() { + return fileType; + } + + /** + * @param fileType + * the fileType to set + * @see #fileType + */ + public void setFileType(InputFileType fileType) { + this.fileType = fileType; + } + + /** + * Returns <code>true</code> if {@link #root} is positive, <code>false</code> + * otherwise. + * + * @return <code>true</code> if {@link #root} is positive, <code>false</code> + * otherwise + */ + public boolean isRoot() { + return "true".equalsIgnoreCase(root); + } + + /** + * @param root + * the root to set + * @see #root + */ + public void setRoot(String root) { + this.root = root; + } + + /** + * Sets {@link #root} vale. + * + * @param root + * new {@link #root} value + */ + public void setRoot(boolean root) { + if (root) { + setRoot("true"); + } else { + setRoot("false"); + } + } + + /** + * Returns <code>true</code> if {@link #mapping} is positive, <code>false</code> + * otherwise. + * + * @return <code>true</code> if {@link #mapping} is positive, <code>false</code> + * otherwise + */ + public boolean isMappingFile() { + return "true".equalsIgnoreCase(mapping); + } } diff --git a/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFile.java b/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFile.java index 5eb83c136b..94fa6e3cdf 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFile.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFile.java @@ -11,75 +11,75 @@ import java.util.Map; * */ public abstract class ZipEntryFile { - /** - * Name of the file in zip archive. - */ - private String filename; + /** + * Name of the file in zip archive. + */ + private String filename; - /** - * This map contains information that are stored in the header (first few - * lines) in a text file. This information is stored as a pair: - * - * <pre> - * # key=value - * </pre> - */ - private Map<String, String> headerParameters = new HashMap<String, String>(); + /** + * This map contains information that are stored in the header (first few lines) + * in a text file. This information is stored as a pair: + * + * <pre> + * # key=value + * </pre> + */ + private Map<String, String> headerParameters = new HashMap<String, String>(); - /** - * Default constructor. - */ - public ZipEntryFile() { - } + /** + * Default constructor. + */ + public ZipEntryFile() { + } - /** - * Default constructor. - * - * @param filename - * {@link #filename} - */ - public ZipEntryFile(String filename) { - this.filename = filename; - } + /** + * Default constructor. + * + * @param filename + * {@link #filename} + */ + public ZipEntryFile(String filename) { + this.filename = filename; + } - /** - * @return the filename - * @see #filename - */ - public String getFilename() { - return filename; - } + /** + * @return the filename + * @see #filename + */ + public String getFilename() { + return filename; + } - /** - * @param filename - * the filename to set - * @see #filename - */ - public void setFilename(String filename) { - this.filename = filename; - } + /** + * @param filename + * the filename to set + * @see #filename + */ + public void setFilename(String filename) { + this.filename = filename; + } - /** - * Adds new param (or replace old one) to {@link #headerParameters}. - * - * @param key - * key identifing param - * @param value - * value of the param - */ - public void setHeaderParameter(String key, String value) { - headerParameters.put(key, value); - } + /** + * Adds new param (or replace old one) to {@link #headerParameters}. + * + * @param key + * key identifing param + * @param value + * value of the param + */ + public void setHeaderParameter(String key, String value) { + headerParameters.put(key, value); + } - /** - * Returns value of the param identified by string key. - * - * @param key - * key used to identify param - * @return value of the param identified by string key - */ - public String getHeaderParameter(String key) { - return headerParameters.get(key); - } + /** + * Returns value of the param identified by string key. + * + * @param key + * key used to identify param + * @return value of the param identified by string key + */ + public String getHeaderParameter(String key) { + return headerParameters.get(key); + } } diff --git a/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFileFactory.java b/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFileFactory.java index 41d64302f6..a249cc8664 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFileFactory.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/zip/ZipEntryFileFactory.java @@ -7,7 +7,8 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.TextFileUtils; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -20,68 +21,59 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; */ public class ZipEntryFileFactory { /** - * Default class logger. + * Name of the parameter in {@link LayoutZipEntryFile file describing layout} + * corresponding to the {@link LayoutZipEntryFile#type type}. */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ZipEntryFileFactory.class); - + public static final String LAYOUT_HEADER_PARAM_TYPE = "TYPE"; + /** + * Name of the parameter in {@link LayoutZipEntryFile file describing layout} + * corresponding to the {@link LayoutZipEntryFile#genomeType genome type}. + */ + public static final String LAYOUT_HEADER_PARAM_GENOME_TYPE = "GENOME_TYPE"; + /** + * Name of the parameter in {@link LayoutZipEntryFile file describing layout} + * corresponding to the {@link LayoutZipEntryFile#genomeVersion genome version}. + */ + public static final String LAYOUT_HEADER_PARAM_GENOME_VERSION = "GENOME_VERSION"; /** * Directory in a zip file where information about submodels is stored. These * entries should be by default transformed into {@link ModelZipEntryFile}. */ private static final String SUBMODEL_DIRECTORY = "submaps/"; - /** * Directory in a zip file where information about * {@link lcsb.mapviewer.model.map.OverviewImage OverviewImage} is stored. These * entries should be by default transformed into {@link ImageZipEntryFile}. */ private static final String IMAGES_DIRECTORY = "images/"; - /** * Directory in a zip file where information about * {@link lcsb.mapviewer.model.map.layout.graphics.Glyph} is stored. These * entries should be by default transformed into {@link GlyphZipEntryFile}. */ private static final String GLYPHS_DIRECTORY = "glyphs/"; - /** * Directory in a zip file where information about * {@link lcsb.mapviewer.model.map.layout.Layout Layout} is stored. These * entries should be by default transformed into {@link LayoutZipEntryFile}. */ private static final String LAYOUT_DIRECTORY = "layouts/"; - /** * Name of the parameter in {@link LayoutZipEntryFile file describing layout} * corresponding to the {@link LayoutZipEntryFile#name layout name}. */ private static final String LAYOUT_HEADER_PARAM_NAME = "NAME"; - /** * Name of the parameter in {@link LayoutZipEntryFile file describing layout} * corresponding to the {@link LayoutZipEntryFile#description layout * description}. */ private static final String LAYOUT_HEADER_PARAM_DESCRIPTION = "DESCRIPTION"; - - /** - * Name of the parameter in {@link LayoutZipEntryFile file describing layout} - * corresponding to the {@link LayoutZipEntryFile#type type}. - */ - public static final String LAYOUT_HEADER_PARAM_TYPE = "TYPE"; - - /** - * Name of the parameter in {@link LayoutZipEntryFile file describing layout} - * corresponding to the {@link LayoutZipEntryFile#genomeType genome type}. - */ - public static final String LAYOUT_HEADER_PARAM_GENOME_TYPE = "GENOME_TYPE"; - /** - * Name of the parameter in {@link LayoutZipEntryFile file describing layout} - * corresponding to the {@link LayoutZipEntryFile#genomeVersion genome version}. + * Default class logger. */ - public static final String LAYOUT_HEADER_PARAM_GENOME_VERSION = "GENOME_VERSION"; + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ZipEntryFileFactory.class); /** * Generates instance of {@link ZipEntryFile} representing entry in the zip file diff --git a/converter/src/main/java/lcsb/mapviewer/converter/zip/package-info.java b/converter/src/main/java/lcsb/mapviewer/converter/zip/package-info.java index fdbf9c0a4c..607eff173e 100644 --- a/converter/src/main/java/lcsb/mapviewer/converter/zip/package-info.java +++ b/converter/src/main/java/lcsb/mapviewer/converter/zip/package-info.java @@ -2,4 +2,3 @@ * Package with structures describing zip file entries. */ package lcsb.mapviewer.converter.zip; - diff --git a/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java b/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java index 15d26751d2..275ae8bbd5 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/ConverterTestFunctions.java @@ -1,37 +1,21 @@ package lcsb.mapviewer.converter; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; import java.util.List; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; +import javax.xml.parsers.*; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.junit.*; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; @@ -39,14 +23,11 @@ import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; public abstract class ConverterTestFunctions { - private Logger logger = LogManager.getLogger(ConverterTestFunctions.class); - protected static double EPSILON = Configuration.EPSILON; - - private MinervaLoggerAppender appender; - @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); + private Logger logger = LogManager.getLogger(ConverterTestFunctions.class); + private MinervaLoggerAppender appender; @Before public final void _setUp() throws Exception { diff --git a/converter/src/test/java/lcsb/mapviewer/converter/MockConverter.java b/converter/src/test/java/lcsb/mapviewer/converter/MockConverter.java index 2ac740ab6e..b89d181c9b 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/MockConverter.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/MockConverter.java @@ -7,14 +7,9 @@ import lcsb.mapviewer.common.MimeType; 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; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.reaction.type.TransportReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class MockConverter extends Converter { @@ -90,27 +85,27 @@ public class MockConverter extends Converter { } @Override - public InputStream model2InputStream(Model model) throws InconsistentModelException, ConverterException { + public String getCommonName() { return null; } @Override - public File model2File(Model model, String filePath) throws InconsistentModelException { + public MimeType getMimeType() { return null; } @Override - public String getCommonName() { + public String getFileExtension() { return null; } @Override - public MimeType getMimeType() { + public InputStream model2InputStream(Model model) throws InconsistentModelException, ConverterException { return null; } @Override - public String getFileExtension() { + public File model2File(Model model, String filePath) throws InconsistentModelException { return null; } diff --git a/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java b/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java index 5b57488a49..5d6f98d24a 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/ZIndexPopulatorTest.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.converter; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import lcsb.mapviewer.model.map.compartment.Compartment; @@ -13,9 +14,7 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; 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.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; public class ZIndexPopulatorTest { @@ -203,10 +202,9 @@ public class ZIndexPopulatorTest { return result; } - private Reaction createReaction () { + private Reaction createReaction() { Reaction result = new TransportReaction("s" + identifierCounter++); return result; } - } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/ClearColorModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/ClearColorModelCommand.java index 541db6b893..e0ce5889dd 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/ClearColorModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/ClearColorModelCommand.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.commands; -import java.awt.Color; +import java.awt.*; import java.util.ArrayList; import lcsb.mapviewer.model.map.model.Model; @@ -13,34 +13,35 @@ import lcsb.mapviewer.model.map.model.Model; */ public class ClearColorModelCommand extends ModelCommand { - /** - * Coloring command that will clear colors. - */ - private ColorModelCommand colorModelCommand; - - /** - * Default constructor. - * - * @param model - * original model - */ - public ClearColorModelCommand(Model model) { - super(model); - colorModelCommand = new ColorModelCommand(model, new ArrayList<>(), new ColorExtractor(Color.WHITE, Color.WHITE, Color.WHITE)); - } - - @Override - protected void undoImplementation() throws CommandExecutionException { - colorModelCommand.undo(); - } - - @Override - protected void redoImplementation() throws CommandExecutionException { - colorModelCommand.redo(); - } - - @Override - protected void executeImplementation() throws CommandExecutionException { - colorModelCommand.execute(); - } + /** + * Coloring command that will clear colors. + */ + private ColorModelCommand colorModelCommand; + + /** + * Default constructor. + * + * @param model + * original model + */ + public ClearColorModelCommand(Model model) { + super(model); + colorModelCommand = new ColorModelCommand(model, new ArrayList<>(), + new ColorExtractor(Color.WHITE, Color.WHITE, Color.WHITE)); + } + + @Override + protected void undoImplementation() throws CommandExecutionException { + colorModelCommand.undo(); + } + + @Override + protected void redoImplementation() throws CommandExecutionException { + colorModelCommand.redo(); + } + + @Override + protected void executeImplementation() throws CommandExecutionException { + colorModelCommand.execute(); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/ColorExtractor.java b/model-command/src/main/java/lcsb/mapviewer/commands/ColorExtractor.java index e08bdca655..434e7d0f32 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/ColorExtractor.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/ColorExtractor.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.commands; -import java.awt.Color; +import java.awt.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.layout.ColorSchema; @@ -14,92 +14,94 @@ import lcsb.mapviewer.model.map.layout.ColorSchema; */ public class ColorExtractor { - /** - * Color that should be used for min values of {@link ColorSchema#value}. - */ - private Color minColor; + /** + * Color that should be used for min values of {@link ColorSchema#value}. + */ + private Color minColor; - /** - * Color that should be used for maxvalues of {@link ColorSchema#value}. - */ - private Color maxColor; + /** + * Color that should be used for maxvalues of {@link ColorSchema#value}. + */ + private Color maxColor; - private Color simpleColor; + private Color simpleColor; - /** - * Default constructor. - * - * @param minColor - * Color that should be used for min values of - * {@link ColorSchema#value} - * @param maxColor - * Color that should be used for max values of - * {@link ColorSchema#value} - */ - public ColorExtractor(Color minColor, Color maxColor, Color simpleColor) { - if (minColor == null || maxColor == null || simpleColor == null) { - throw new InvalidArgumentException("Parameters cannot be null"); - } - this.minColor = minColor; - this.maxColor = maxColor; - this.simpleColor = simpleColor; - } + /** + * Default constructor. + * + * @param minColor + * Color that should be used for min values of + * {@link ColorSchema#value} + * @param maxColor + * Color that should be used for max values of + * {@link ColorSchema#value} + */ + public ColorExtractor(Color minColor, Color maxColor, Color simpleColor) { + if (minColor == null || maxColor == null || simpleColor == null) { + throw new InvalidArgumentException("Parameters cannot be null"); + } + this.minColor = minColor; + this.maxColor = maxColor; + this.simpleColor = simpleColor; + } - /** - * Extracts color from {@link ColorSchema} object. - * - * @param colorSchema - * {@link ColorSchema} from which {@link Color} should be extracted - * - * @return color from {@link ColorSchema} object - */ - public Color getNormalizedColor(ColorSchema colorSchema) { - if (colorSchema.getColor() != null) { - return colorSchema.getColor(); - } else if (colorSchema.getValue() == null) { - return simpleColor; - } else { - return getColorForValue(colorSchema.getValue()); - } - } + /** + * Extracts color from {@link ColorSchema} object. + * + * @param colorSchema + * {@link ColorSchema} from which {@link Color} should be extracted + * + * @return color from {@link ColorSchema} object + */ + public Color getNormalizedColor(ColorSchema colorSchema) { + if (colorSchema.getColor() != null) { + return colorSchema.getColor(); + } else if (colorSchema.getValue() == null) { + return simpleColor; + } else { + return getColorForValue(colorSchema.getValue()); + } + } - /** - * Returns color from red - green scale for the given normalized double value - * (from range -1,1). - * - * @param value - * double value that should be converted into color - * @return color for the double value - */ - protected Color getColorForValue(Double value) { - if (value > 0) { - double ratio = value; - return new Color((int) (maxColor.getRed() * ratio), (int) (maxColor.getGreen() * ratio), (int) (maxColor.getBlue() * ratio)); - } - if (value < 0) { - double ratio = -value; - return new Color((int) (minColor.getRed() * ratio), (int) (minColor.getGreen() * ratio), (int) (minColor.getBlue() * ratio)); - } - return Color.WHITE; - } + /** + * Returns color from red - green scale for the given normalized double value + * (from range -1,1). + * + * @param value + * double value that should be converted into color + * @return color for the double value + */ + protected Color getColorForValue(Double value) { + if (value > 0) { + double ratio = value; + return new Color((int) (maxColor.getRed() * ratio), (int) (maxColor.getGreen() * ratio), + (int) (maxColor.getBlue() * ratio)); + } + if (value < 0) { + double ratio = -value; + return new Color((int) (minColor.getRed() * ratio), (int) (minColor.getGreen() * ratio), + (int) (minColor.getBlue() * ratio)); + } + return Color.WHITE; + } - /** - * @return the minColor - * @see #minColor - */ - public Color getMinColor() { - return minColor; - } + /** + * @return the minColor + * @see #minColor + */ + public Color getMinColor() { + return minColor; + } - /** - * @return the maxColor - * @see #maxColor - */ - public Color getMaxColor() { - return maxColor; - } - - public Color getSimpleColor() { - return simpleColor; - } + /** + * @return the maxColor + * @see #maxColor + */ + public Color getMaxColor() { + return maxColor; + } + + public Color getSimpleColor() { + return simpleColor; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java index 9cce0d6982..961ad55116 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.commands; -import java.awt.Color; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; +import java.awt.*; +import java.util.*; import java.util.List; -import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.comparator.StringComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -18,13 +16,8 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -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.reaction.AbstractNode; -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.model.*; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -322,10 +315,19 @@ public class ColorModelCommand extends ModelCommand { throw new NotImplementedException(); } + @Override + protected void executeImplementation() throws CommandExecutionException { + try { + colorModel(getModel(), true); + } catch (InvalidColorSchemaException e) { + throw new CommandExecutionException(e); + } + } + /** * Colors parameter model using coloring for this command. This method is used * internally to color either top {@link Model} or one of it's sumbodels. - * + * * @param result * model to color * @param top @@ -372,13 +374,4 @@ public class ColorModelCommand extends ModelCommand { } } - @Override - protected void executeImplementation() throws CommandExecutionException { - try { - colorModel(getModel(), true); - } catch (InvalidColorSchemaException e) { - throw new CommandExecutionException(e); - } - } - } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/CommandExecutionException.java b/model-command/src/main/java/lcsb/mapviewer/commands/CommandExecutionException.java index ae9195d4b2..8fef89fbbf 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/CommandExecutionException.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/CommandExecutionException.java @@ -8,48 +8,48 @@ package lcsb.mapviewer.commands; */ public class CommandExecutionException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - */ - public CommandExecutionException() { - super(); - } + /** + * Default constructor. + */ + public CommandExecutionException() { + super(); + } - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public CommandExecutionException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public CommandExecutionException(String string) { + super(string); + } - /** - * Public constructor with parent exception that was catched. - * - * @param e - * parent exception - */ - public CommandExecutionException(Exception e) { - super(e.getMessage(), e); - } + /** + * Public constructor with parent exception that was catched. + * + * @param e + * parent exception + */ + public CommandExecutionException(Exception e) { + super(e.getMessage(), e); + } - /** - * Public constructor with parent exception that was catched. - * - * @param string - * message of this exception - * @param e - * parent exception - */ - public CommandExecutionException(String string, Exception e) { - super(string, e); - } + /** + * Public constructor with parent exception that was catched. + * + * @param string + * message of this exception + * @param e + * parent exception + */ + public CommandExecutionException(String string, Exception e) { + super(string, e); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/CopyCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/CopyCommand.java index 3d5f910225..214b1df6f7 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/CopyCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/CopyCommand.java @@ -1,38 +1,19 @@ package lcsb.mapviewer.commands; -import java.util.Calendar; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidClassException; -import lcsb.mapviewer.common.exception.InvalidStateException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.kinetics.SbmlArgument; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.model.Author; -import lcsb.mapviewer.model.map.model.ElementSubmodelConnection; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelConnection; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.NodeOperator; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.model.*; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.species.*; /** * Command that creates a new instance of the model with the same data. @@ -257,12 +238,12 @@ public class CopyCommand extends NewModelCommand { for (MiriamData md : model.getMiriamData()) { result.addMiriamData(new MiriamData(md)); } - - if (model.getCreationDate()!=null) { - result.setCreationDate((Calendar)(model.getCreationDate().clone())); + + if (model.getCreationDate() != null) { + result.setCreationDate((Calendar) (model.getCreationDate().clone())); } - - for (Calendar calendar: model.getModificationDates()) { + + for (Calendar calendar : model.getModificationDates()) { result.addModificationDate((Calendar) calendar.clone()); } 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 06f8c1c02d..09e86f7372 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/CreateHierarchyCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/CreateHierarchyCommand.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.commands; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.commons.lang3.math.NumberUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidStateException; @@ -15,13 +13,9 @@ import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.model.celldesigner.annotation.RestAnnotationParser; 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.layout.graphics.*; 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.model.map.species.*; /** * This {@link ModelCommand command} class allows to transform model into @@ -32,16 +26,10 @@ import lcsb.mapviewer.model.map.species.Species; * */ public class CreateHierarchyCommand extends ModelCommand { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CreateHierarchyCommand.class); /** * Natural logarithm of four. */ private static final double LOG_4 = Math.log(4); - /** * Top left corner x coordinate of the text associated with compartment. */ @@ -50,7 +38,11 @@ public class CreateHierarchyCommand extends ModelCommand { * Top left corner y coordinate of the text associated with compartment. */ private static final double DEFAULT_TITLE_Y_COORD_IN_ARTIFITIAL_COMPARTMENT = 10; - + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CreateHierarchyCommand.class); /** * How many levels are possible. */ @@ -81,6 +73,11 @@ public class CreateHierarchyCommand extends ModelCommand { throw new NotImplementedException(); } + @Override + protected void redoImplementation() { + throw new NotImplementedException(); + } + @Override protected void executeImplementation() { if (!ModelCommandStatus.CREATED.equals(getStatus()) && !ModelCommandStatus.UNDONE.equals(getStatus())) { @@ -121,11 +118,6 @@ public class CreateHierarchyCommand extends ModelCommand { } } - @Override - protected void redoImplementation() { - throw new NotImplementedException(); - } - /** * Cleans hierarchical information from the model. */ diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/InvalidModelException.java b/model-command/src/main/java/lcsb/mapviewer/commands/InvalidModelException.java index b0d70db8e0..7b6855f0a7 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/InvalidModelException.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/InvalidModelException.java @@ -8,19 +8,19 @@ package lcsb.mapviewer.commands; * */ public class InvalidModelException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public InvalidModelException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public InvalidModelException(String string) { + super(string); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommand.java index 56394014f0..0f1288dd4b 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommand.java @@ -26,205 +26,206 @@ import lcsb.mapviewer.model.map.species.Element; */ public abstract class ModelCommand { - /** - * Status of the command. - */ - private ModelCommandStatus status = ModelCommandStatus.CREATED; - - /** - * Model on which command is performed. - */ - private Model model; - - /** - * Region that is affected by this command. If null then command didn't - * affected layout. - */ - private Rectangle2D affectedRegion; - - /** - * Undo the operation. - * - * @throws CommandExecutionException - * thrown when undo cannot be performed due to invalid input data - */ - public void undo() throws CommandExecutionException { - if (!ModelCommandStatus.EXECUTED.equals(getStatus())) { - throw new InvalidStateException("To undo command, the command must be executed first. " + getStatus() + " found."); - } else { - affectedRegion = null; - undoImplementation(); - } - } - - /** - * Redo the operation if the command was undone. - * - * @throws CommandExecutionException - * thrown when undo cannot be executed due to problemtaic input data - */ - public void redo() throws CommandExecutionException { - if (!ModelCommandStatus.UNDONE.equals(getStatus())) { - throw new InvalidStateException("To redo command, the command must be undone first. " + getStatus() + " found."); - } else { - affectedRegion = null; - redoImplementation(); - } - } - - /** - * Executed the operation. - * - * @throws CommandExecutionException - * thrown when execution cannot be performed due to invalid input - * data - */ - public void execute() throws CommandExecutionException { - if (!ModelCommandStatus.CREATED.equals(getStatus()) && !ModelCommandStatus.UNDONE.equals(getStatus())) { - throw new InvalidStateException("To execute command, the command must be in CREATED or UNDONE state. " + getStatus() + " found."); - } else { - affectedRegion = null; - executeImplementation(); - setStatus(ModelCommandStatus.EXECUTED); - } - } - - /** - * Command specific implementation of {@link #undo()} operation. - * - * @throws CommandExecutionException - * thrown when undo cannot be executed due to problematic input data - */ - protected abstract void undoImplementation() throws CommandExecutionException; - - /** - * Command specific implementation of {@link #redo()} operation. - * - * @throws CommandExecutionException - * thrown when redo cannot be executed due to problematic input data - */ - protected abstract void redoImplementation() throws CommandExecutionException; - - /** - * Command specific implementation how to execute this command. - * - * @throws CommandExecutionException - * thrown when command cannot be executed due to problematic input - * data - */ - protected abstract void executeImplementation() throws CommandExecutionException; - - /** - * Default constructor. - * - * @param model - * {@link #model} - */ - public ModelCommand(Model model) { - this.model = model; - } - - /** - * @return the status - * @see #status - */ - public ModelCommandStatus getStatus() { - return status; - } - - /** - * @return the model - * @see #model - */ - protected Model getModel() { - return model; - } - - /** - * @param model - * the model to set - * @see #model - */ - protected void setModel(Model model) { - this.model = model; - } - - /** - * @param status - * the status to set - * @see #status - */ - protected void setStatus(ModelCommandStatus status) { - this.status = status; - } - - /** - * @return the affectedRegion - * @see #affectedRegion - */ - public Rectangle2D getAffectedRegion() { - return affectedRegion; - } - - /** - * Adds point to {@link #affectedRegion}. - * - * @param point - * point to be included in affected region - */ - protected void includeInAffectedRegion(Point2D point) { - if (affectedRegion == null) { - affectedRegion = new Rectangle2D.Double(point.getY(), point.getY(), 0, 0); - } else { - affectedRegion.add(point); - } - } - - /** - * Adds line to {@link #affectedRegion}. - * - * @param pd - * line to be included in affected region - */ - protected void includeInAffectedRegion(PolylineData pd) { - if (affectedRegion == null) { - affectedRegion = new Rectangle2D.Double(pd.getBeginPoint().getX(), pd.getBeginPoint().getY(), 0, 0); - } - for (Point2D point : pd.getPoints()) { - affectedRegion.add(point); - } - } - - /** - * Adds alias to {@link #affectedRegion}. - * - * @param alias - * alias to be included in affected region - */ - protected void includeInAffectedRegion(Element alias) { - if (affectedRegion == null) { - affectedRegion = new Rectangle2D.Double(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight()); - } else { - affectedRegion.add(alias.getX(), alias.getY()); - affectedRegion.add(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight()); - } - } - - /** - * Adds reaction to {@link #affectedRegion}. - * - * @param reaction - * reaction to be included in affected region - */ - protected void includeInAffectedRegion(Reaction reaction) { - if (affectedRegion == null) { - Point2D point = reaction.getNodes().iterator().next().getLine().getBeginPoint(); - affectedRegion = new Rectangle2D.Double(point.getX(), point.getY(), 0, 0); - } - for (AbstractNode node : reaction.getNodes()) { - includeInAffectedRegion(node.getLine()); - } - - } + /** + * Status of the command. + */ + private ModelCommandStatus status = ModelCommandStatus.CREATED; + + /** + * Model on which command is performed. + */ + private Model model; + + /** + * Region that is affected by this command. If null then command didn't affected + * layout. + */ + private Rectangle2D affectedRegion; + + /** + * Default constructor. + * + * @param model + * {@link #model} + */ + public ModelCommand(Model model) { + this.model = model; + } + + /** + * Undo the operation. + * + * @throws CommandExecutionException + * thrown when undo cannot be performed due to invalid input data + */ + public void undo() throws CommandExecutionException { + if (!ModelCommandStatus.EXECUTED.equals(getStatus())) { + throw new InvalidStateException( + "To undo command, the command must be executed first. " + getStatus() + " found."); + } else { + affectedRegion = null; + undoImplementation(); + } + } + + /** + * Redo the operation if the command was undone. + * + * @throws CommandExecutionException + * thrown when undo cannot be executed due to problemtaic input data + */ + public void redo() throws CommandExecutionException { + if (!ModelCommandStatus.UNDONE.equals(getStatus())) { + throw new InvalidStateException("To redo command, the command must be undone first. " + getStatus() + " found."); + } else { + affectedRegion = null; + redoImplementation(); + } + } + + /** + * Executed the operation. + * + * @throws CommandExecutionException + * thrown when execution cannot be performed due to invalid input data + */ + public void execute() throws CommandExecutionException { + if (!ModelCommandStatus.CREATED.equals(getStatus()) && !ModelCommandStatus.UNDONE.equals(getStatus())) { + throw new InvalidStateException( + "To execute command, the command must be in CREATED or UNDONE state. " + getStatus() + " found."); + } else { + affectedRegion = null; + executeImplementation(); + setStatus(ModelCommandStatus.EXECUTED); + } + } + + /** + * Command specific implementation of {@link #undo()} operation. + * + * @throws CommandExecutionException + * thrown when undo cannot be executed due to problematic input data + */ + protected abstract void undoImplementation() throws CommandExecutionException; + + /** + * Command specific implementation of {@link #redo()} operation. + * + * @throws CommandExecutionException + * thrown when redo cannot be executed due to problematic input data + */ + protected abstract void redoImplementation() throws CommandExecutionException; + + /** + * Command specific implementation how to execute this command. + * + * @throws CommandExecutionException + * thrown when command cannot be executed due to problematic input + * data + */ + protected abstract void executeImplementation() throws CommandExecutionException; + + /** + * @return the status + * @see #status + */ + public ModelCommandStatus getStatus() { + return status; + } + + /** + * @param status + * the status to set + * @see #status + */ + protected void setStatus(ModelCommandStatus status) { + this.status = status; + } + + /** + * @return the model + * @see #model + */ + protected Model getModel() { + return model; + } + + /** + * @param model + * the model to set + * @see #model + */ + protected void setModel(Model model) { + this.model = model; + } + + /** + * @return the affectedRegion + * @see #affectedRegion + */ + public Rectangle2D getAffectedRegion() { + return affectedRegion; + } + + /** + * Adds point to {@link #affectedRegion}. + * + * @param point + * point to be included in affected region + */ + protected void includeInAffectedRegion(Point2D point) { + if (affectedRegion == null) { + affectedRegion = new Rectangle2D.Double(point.getY(), point.getY(), 0, 0); + } else { + affectedRegion.add(point); + } + } + + /** + * Adds line to {@link #affectedRegion}. + * + * @param pd + * line to be included in affected region + */ + protected void includeInAffectedRegion(PolylineData pd) { + if (affectedRegion == null) { + affectedRegion = new Rectangle2D.Double(pd.getBeginPoint().getX(), pd.getBeginPoint().getY(), 0, 0); + } + for (Point2D point : pd.getPoints()) { + affectedRegion.add(point); + } + } + + /** + * Adds alias to {@link #affectedRegion}. + * + * @param alias + * alias to be included in affected region + */ + protected void includeInAffectedRegion(Element alias) { + if (affectedRegion == null) { + affectedRegion = new Rectangle2D.Double(alias.getX(), alias.getY(), alias.getWidth(), alias.getHeight()); + } else { + affectedRegion.add(alias.getX(), alias.getY()); + affectedRegion.add(alias.getX() + alias.getWidth(), alias.getY() + alias.getHeight()); + } + } + + /** + * Adds reaction to {@link #affectedRegion}. + * + * @param reaction + * reaction to be included in affected region + */ + protected void includeInAffectedRegion(Reaction reaction) { + if (affectedRegion == null) { + Point2D point = reaction.getNodes().iterator().next().getLine().getBeginPoint(); + affectedRegion = new Rectangle2D.Double(point.getX(), point.getY(), 0, 0); + } + for (AbstractNode node : reaction.getNodes()) { + includeInAffectedRegion(node.getLine()); + } + + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommandStatus.java b/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommandStatus.java index 5bcf5084fe..0be6884ea5 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommandStatus.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/ModelCommandStatus.java @@ -7,16 +7,16 @@ package lcsb.mapviewer.commands; * */ public enum ModelCommandStatus { - /** - * {@link ModelCommand} was created. - */ - CREATED, - /** - * {@link ModelCommand} was executed. - */ - EXECUTED, - /** - * {@link ModelCommand} was undone. - */ - UNDONE; + /** + * {@link ModelCommand} was created. + */ + CREATED, + /** + * {@link ModelCommand} was executed. + */ + EXECUTED, + /** + * {@link ModelCommand} was undone. + */ + UNDONE; } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/MoveCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/MoveCommand.java index 42aa36319f..9b8114b09b 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/MoveCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/MoveCommand.java @@ -17,60 +17,61 @@ import lcsb.mapviewer.model.map.species.Element; */ public class MoveCommand extends ModelCommand { - /** - * Delta x. - */ - private double dx; - /** - * Delta y. - */ - private double dy; + /** + * Delta x. + */ + private double dx; + /** + * Delta y. + */ + private double dy; - /** - * Default constructor. - * - * @param model - * model to move - * @param dx - * delta x - * @param dy - * delat y - */ - public MoveCommand(Model model, double dx, double dy) { - super(model); - this.dx = dx; - this.dy = dy; - } + /** + * Default constructor. + * + * @param model + * model to move + * @param dx + * delta x + * @param dy + * delat y + */ + public MoveCommand(Model model, double dx, double dy) { + super(model); + this.dx = dx; + this.dy = dy; + } - @Override - protected void undoImplementation() { - throw new NotImplementedException(); - } + @Override + protected void undoImplementation() { + throw new NotImplementedException(); + } - @Override - protected void redoImplementation() { - throw new NotImplementedException(); - } + @Override + protected void redoImplementation() { + throw new NotImplementedException(); + } - @Override - protected void executeImplementation() { + @Override + protected void executeImplementation() { - Model model = getModel(); + Model model = getModel(); - for (Element alias : model.getElements()) { - alias.setX(alias.getX() + dx); - alias.setY(alias.getY() + dy); - if (alias instanceof Compartment) { - ((Compartment) alias).setNamePoint(((Compartment) alias).getNamePoint().getX() + dx, ((Compartment) alias).getNamePoint().getY() + dy); - } - } - for (Reaction reaction : model.getReactions()) { - for (AbstractNode node : reaction.getNodes()) { - for (Point2D point : node.getLine().getPoints()) { - point.setLocation(point.getX() + dx, point.getY() + dy); - } - } - } - } + for (Element alias : model.getElements()) { + alias.setX(alias.getX() + dx); + alias.setY(alias.getY() + dy); + if (alias instanceof Compartment) { + ((Compartment) alias).setNamePoint(((Compartment) alias).getNamePoint().getX() + dx, + ((Compartment) alias).getNamePoint().getY() + dy); + } + } + for (Reaction reaction : model.getReactions()) { + for (AbstractNode node : reaction.getNodes()) { + for (Point2D point : node.getLine().getPoints()) { + point.setLocation(point.getX() + dx, point.getY() + dy); + } + } + } + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java index 251149fcf3..cb65a4c741 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/MoveElementsCommand.java @@ -1,25 +1,17 @@ package lcsb.mapviewer.commands; 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 java.util.*; -import org.apache.logging.log4j.*; +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.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -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.reaction.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.field.ModificationResidue; import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/NewModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/NewModelCommand.java index 0c89b1852c..70f5ac14f7 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/NewModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/NewModelCommand.java @@ -10,43 +10,43 @@ import lcsb.mapviewer.model.map.model.Model; * */ public abstract class NewModelCommand { - - /** - * Model on which command is performed. - */ - private Model model; - /** - * Executed the operation. - * - * @return new {@link Model} object accoriding to initialization params - */ - public abstract Model execute(); + /** + * Model on which command is performed. + */ + private Model model; - /** - * Default constructor. - * - * @param model - * {@link #model} - */ - public NewModelCommand(Model model) { - this.model = model; - } + /** + * Default constructor. + * + * @param model + * {@link #model} + */ + public NewModelCommand(Model model) { + this.model = model; + } - /** - * @return the model - * @see #model - */ - protected Model getModel() { - return model; - } + /** + * Executed the operation. + * + * @return new {@link Model} object accoriding to initialization params + */ + public abstract Model execute(); - /** - * @param model - * the model to set - * @see #model - */ - protected void setModel(Model model) { - this.model = model; - } + /** + * @return the model + * @see #model + */ + protected Model getModel() { + return model; + } + + /** + * @param model + * the model to set + * @see #model + */ + protected void setModel(Model model) { + this.model = model; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/SemanticZoomLevelMatcher.java b/model-command/src/main/java/lcsb/mapviewer/commands/SemanticZoomLevelMatcher.java index d49f59d7a0..d1fdee3c73 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/SemanticZoomLevelMatcher.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/SemanticZoomLevelMatcher.java @@ -1,49 +1,49 @@ package lcsb.mapviewer.commands; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; public class SemanticZoomLevelMatcher { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(SemanticZoomLevelMatcher.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(SemanticZoomLevelMatcher.class); - /** - * Checks if level belongs to the range defined in - * semanticZoomLevelVisibility. - * - * @param level - * level to ve checked - * @param semanticZoomLevelVisibility - * range of levels to be checked - * @return true if level is in the range - */ - public boolean isVisible(int level, String semanticZoomLevelVisibility) { - return matchLevel(level, semanticZoomLevelVisibility); - } + /** + * Checks if level belongs to the range defined in semanticZoomLevelVisibility. + * + * @param level + * level to ve checked + * @param semanticZoomLevelVisibility + * range of levels to be checked + * @return true if level is in the range + */ + public boolean isVisible(int level, String semanticZoomLevelVisibility) { + return matchLevel(level, semanticZoomLevelVisibility); + } - public boolean isTransparent(int level, String semanticZoomLevelVisibility) { - return matchLevel(level, semanticZoomLevelVisibility); - } + public boolean isTransparent(int level, String semanticZoomLevelVisibility) { + return matchLevel(level, semanticZoomLevelVisibility); + } - private boolean matchLevel(int level, String semanticZoomLevelVisibility) { - if (semanticZoomLevelVisibility == null || semanticZoomLevelVisibility.isEmpty()) { - return true; - } - if (semanticZoomLevelVisibility.contains("{")) { - String strLevels = semanticZoomLevelVisibility.replace("{", "").replace("}", ""); - String[] ranges = strLevels.split(","); - for (String string : ranges) { - if (Integer.valueOf(string).equals(level)) { - return true; - } - } - } - if (Integer.valueOf(semanticZoomLevelVisibility) <= level) { - return true; - } - return false; - } + private boolean matchLevel(int level, String semanticZoomLevelVisibility) { + if (semanticZoomLevelVisibility == null || semanticZoomLevelVisibility.isEmpty()) { + return true; + } + if (semanticZoomLevelVisibility.contains("{")) { + String strLevels = semanticZoomLevelVisibility.replace("{", "").replace("}", ""); + String[] ranges = strLevels.split(","); + for (String string : ranges) { + if (Integer.valueOf(string).equals(level)) { + return true; + } + } + } + if (Integer.valueOf(semanticZoomLevelVisibility) <= level) { + return true; + } + return false; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/SetFixedHierarchyLevelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/SetFixedHierarchyLevelCommand.java index 99325ce1f1..b17a17ca27 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/SetFixedHierarchyLevelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/SetFixedHierarchyLevelCommand.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.commands; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -37,6 +38,11 @@ public class SetFixedHierarchyLevelCommand extends ModelCommand { throw new NotImplementedException(); } + @Override + protected void redoImplementation() { + throw new NotImplementedException(); + } + @Override protected void executeImplementation() { if (!ModelCommandStatus.CREATED.equals(getStatus()) && !ModelCommandStatus.UNDONE.equals(getStatus())) { @@ -70,9 +76,4 @@ public class SetFixedHierarchyLevelCommand extends ModelCommand { setStatus(ModelCommandStatus.EXECUTED); } - @Override - protected void redoImplementation() { - throw new NotImplementedException(); - } - } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/SubModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/SubModelCommand.java index de058e7b7e..4c6ea2f29c 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/SubModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/SubModelCommand.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.commands; import java.awt.geom.Path2D; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; 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.reaction.Reaction; import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; /** * Creates a new instance of the model with data limited to region described by diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplyLayoutModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplyLayoutModelCommand.java index b760013ef3..dd47fbf5dc 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplyLayoutModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/layout/ApplyLayoutModelCommand.java @@ -5,7 +5,8 @@ import java.awt.geom.Point2D; import java.util.Collection; import java.util.HashSet; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.ModelCommand; import lcsb.mapviewer.common.geometry.DoubleDimension; 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 3d5c0ab39a..7af8cb6dff 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 @@ -26,17 +26,15 @@ import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationResidue; public class ApplySimpleLayoutModelCommand extends ApplyLayoutModelCommand { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(ApplySimpleLayoutModelCommand.class); - public static final double COMPARTMENT_BORDER = 10; private static final double BORDER_FROM_EXISTING_ELEMENTS = 10; private static final int SPECIES_WIDTH = 90; private static final int SPECIES_HEIGHT = 30; private static final double COMPLEX_PADDING = 5; - + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(ApplySimpleLayoutModelCommand.class); private PointTransformation pt = new PointTransformation(); public ApplySimpleLayoutModelCommand(Model model, Collection<BioEntity> bioEntities, Double minX, Double minY, @@ -56,30 +54,6 @@ public class ApplySimpleLayoutModelCommand extends ApplyLayoutModelCommand { this(model, null); } - @Override - protected void executeImplementation() throws CommandExecutionException { - Set<Model> models = new HashSet<>(); - models.add(this.getModel()); - models.addAll(this.getModel().getSubmodels()); - for (Model model : models) { - Collection<BioEntity> bioEntites = new HashSet<>(); - for (BioEntity bioEntity : this.getBioEntities()) { - if (bioEntity.getModel() == model) { - bioEntites.add(bioEntity); - } - } - if (bioEntites.size() > 0) { - Dimension2D dimension = null; - Point2D minPoint = null; - if (model == this.getModel()) { - dimension = getStartDimension(); - minPoint = getStartPoint(); - } - createLayout(model, bioEntites, null, minPoint, dimension); - } - } - } - private void createLayout(Model model, Collection<BioEntity> bioEntites, Compartment compartment, Point2D minPoint, Dimension2D dimension) { if (dimension == null) { @@ -466,6 +440,30 @@ public class ApplySimpleLayoutModelCommand extends ApplyLayoutModelCommand { throw new NotImplementedException(); } + @Override + protected void executeImplementation() throws CommandExecutionException { + Set<Model> models = new HashSet<>(); + models.add(this.getModel()); + models.addAll(this.getModel().getSubmodels()); + for (Model model : models) { + Collection<BioEntity> bioEntites = new HashSet<>(); + for (BioEntity bioEntity : this.getBioEntities()) { + if (bioEntity.getModel() == model) { + bioEntites.add(bioEntity); + } + } + if (bioEntites.size() > 0) { + Dimension2D dimension = null; + Point2D minPoint = null; + if (model == this.getModel()) { + dimension = getStartDimension(); + minPoint = getStartPoint(); + } + createLayout(model, bioEntites, null, minPoint, dimension); + } + } + } + protected void modifyComplexLocation(Complex complex, double centerX, double centerY) { if (complex.getWidth() == null || complex.getHeight() == null) { computeComplexSize(complex); diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/package-info.java b/model-command/src/main/java/lcsb/mapviewer/commands/package-info.java index 912c51cf99..43a01ab5dc 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/package-info.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/package-info.java @@ -4,4 +4,3 @@ * */ package lcsb.mapviewer.commands; - diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementFormerSymbolsCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementFormerSymbolsCommand.java index 7b94301d00..23b24ed986 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementFormerSymbolsCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementFormerSymbolsCommand.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.model.Model; @@ -17,58 +18,59 @@ import lcsb.mapviewer.model.map.species.Element; */ public class AddElementFormerSymbolsCommand extends AddElementPropertyListEntryCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(AddElementFormerSymbolsCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param values - * new {@link Element#synonym} values to be added - */ - public AddElementFormerSymbolsCommand(Model model, Element alias, List<String> values) { - super(model, alias, values); - } - - @Override - protected void executeImplementation() throws CommandExecutionException { - - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - for (String string : getNewValues()) { - if (getAlias().getFormerSymbols().contains(string)) { - throw new CommandExecutionException("Cannot add former synonym \"" + string + "\"to the list. Element already exists."); - } - } - - getAlias().getFormerSymbols().addAll(getNewValues()); - - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } - - @Override - protected void undoImplementation() { - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - getAlias().getFormerSymbols().removeAll(getNewValues()); - - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(AddElementFormerSymbolsCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param values + * new {@link Element#synonym} values to be added + */ + public AddElementFormerSymbolsCommand(Model model, Element alias, List<String> values) { + super(model, alias, values); + } + + @Override + protected void undoImplementation() { + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + getAlias().getFormerSymbols().removeAll(getNewValues()); + + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + } + + @Override + protected void executeImplementation() throws CommandExecutionException { + + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + for (String string : getNewValues()) { + if (getAlias().getFormerSymbols().contains(string)) { + throw new CommandExecutionException( + "Cannot add former synonym \"" + string + "\"to the list. Element already exists."); + } + } + + getAlias().getFormerSymbols().addAll(getNewValues()); + + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementMiriamDataCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementMiriamDataCommand.java index ba6c059195..11d2bfcac8 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementMiriamDataCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementMiriamDataCommand.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.MiriamData; @@ -18,57 +19,57 @@ import lcsb.mapviewer.model.map.species.Element; */ public class AddElementMiriamDataCommand extends AddElementPropertyListEntryCommand<MiriamData> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(AddElementMiriamDataCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(AddElementMiriamDataCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param values - * new annotation values to be added - */ - public AddElementMiriamDataCommand(Model model, Element alias, List<MiriamData> values) { - super(model, alias, values); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param values + * new annotation values to be added + */ + public AddElementMiriamDataCommand(Model model, Element alias, List<MiriamData> values) { + super(model, alias, values); + } - @Override - protected void executeImplementation() throws CommandExecutionException { + @Override + protected void undoImplementation() { + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getMiriamData().removeAll(getNewValues()); - for (MiriamData md : getNewValues()) { - if (getAlias().getMiriamData().contains(md)) { - throw new CommandExecutionException("Cannot add miriam \"" + md + "\" to the list. Element already exists."); - } - } + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getMiriamData().addAll(getNewValues()); + } - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + @Override + protected void executeImplementation() throws CommandExecutionException { - @Override - protected void undoImplementation() { - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getMiriamData().removeAll(getNewValues()); + for (MiriamData md : getNewValues()) { + if (getAlias().getMiriamData().contains(md)) { + throw new CommandExecutionException("Cannot add miriam \"" + md + "\" to the list. Element already exists."); + } + } - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getMiriamData().addAll(getNewValues()); - } + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementPropertyListEntryCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementPropertyListEntryCommand.java index 921b7c72af..50a9a50b0f 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementPropertyListEntryCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementPropertyListEntryCommand.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import lcsb.mapviewer.commands.CommandExecutionException; -import lcsb.mapviewer.commands.ModelCommand; -import lcsb.mapviewer.commands.ModelCommandStatus; +import lcsb.mapviewer.commands.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; @@ -20,72 +18,72 @@ import lcsb.mapviewer.model.map.species.Element; */ public abstract class AddElementPropertyListEntryCommand<T> extends ModelCommand { - /** - * List of new values that should be added to property. - */ - private List<T> newValues; + /** + * List of new values that should be added to property. + */ + private List<T> newValues; - /** - * {@link Element} for which we will change the property. - */ - private Element alias; + /** + * {@link Element} for which we will change the property. + */ + private Element alias; - /** - * Default constructor. - * - * @param model - * model to move - * - * @param alias - * alias to be changed - * - * @param newValues - * new values of the element property that will be added - * - */ - public AddElementPropertyListEntryCommand(Model model, Element alias, List<T> newValues) { - super(model); - this.alias = alias; - this.newValues = newValues; - } + /** + * Default constructor. + * + * @param model + * model to move + * + * @param alias + * alias to be changed + * + * @param newValues + * new values of the element property that will be added + * + */ + public AddElementPropertyListEntryCommand(Model model, Element alias, List<T> newValues) { + super(model); + this.alias = alias; + this.newValues = newValues; + } - @Override - protected void redoImplementation() throws CommandExecutionException { - executeImplementation(); - setStatus(ModelCommandStatus.EXECUTED); - } + @Override + protected void redoImplementation() throws CommandExecutionException { + executeImplementation(); + setStatus(ModelCommandStatus.EXECUTED); + } - /** - * @return the alias - * @see #alias - */ - protected Element getAlias() { - return alias; - } + /** + * @return the alias + * @see #alias + */ + protected Element getAlias() { + return alias; + } - /** - * @param alias - * the alias to set - * @see #alias - */ - protected void setAlias(Element alias) { - this.alias = alias; - } + /** + * @param alias + * the alias to set + * @see #alias + */ + protected void setAlias(Element alias) { + this.alias = alias; + } - /** - * @return the newValue - * @see #newValue - */ - protected List<T> getNewValues() { - return newValues; - } + /** + * @return the newValue + * @see #newValue + */ + protected List<T> getNewValues() { + return newValues; + } - /** - * @param newValue - * the newValue to set - * @see #newValue - */ - protected void setNewValues(List<T> newValue) { - this.newValues = newValue; - } + /** + * @param newValue + * the newValue to set + * @see #newValue + */ + protected void setNewValues(List<T> newValue) { + this.newValues = newValue; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementSynonymsCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementSynonymsCommand.java index ee8bd9971b..c39368de05 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementSynonymsCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/AddElementSynonymsCommand.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.model.Model; @@ -17,57 +18,57 @@ import lcsb.mapviewer.model.map.species.Element; */ public class AddElementSynonymsCommand extends AddElementPropertyListEntryCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(AddElementSynonymsCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(AddElementSynonymsCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param values - * new {@link Element#synonym} values to be added - */ - public AddElementSynonymsCommand(Model model, Element alias, List<String> values) { - super(model, alias, values); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param values + * new {@link Element#synonym} values to be added + */ + public AddElementSynonymsCommand(Model model, Element alias, List<String> values) { + super(model, alias, values); + } - @Override - protected void executeImplementation() throws CommandExecutionException { + @Override + protected void undoImplementation() { + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getSynonyms().removeAll(getNewValues()); - for (String string : getNewValues()) { - if (getAlias().getSynonyms().contains(string)) { - throw new CommandExecutionException("Cannot add synonym to the list: " + string + ". Element already exists."); - } - } + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getSynonyms().addAll(getNewValues()); + } - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + @Override + protected void executeImplementation() throws CommandExecutionException { - @Override - protected void undoImplementation() { - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getSynonyms().removeAll(getNewValues()); + for (String string : getNewValues()) { + if (getAlias().getSynonyms().contains(string)) { + throw new CommandExecutionException("Cannot add synonym to the list: " + string + ". Element already exists."); + } + } - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getSynonyms().addAll(getNewValues()); - } + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommand.java index acad51f8d5..4c8e92575f 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementAbbreviationCommand.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.commands.properties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes name * of the element connected to {@link Element}. @@ -14,37 +15,37 @@ import org.apache.logging.log4j.*; */ public class ChangeElementAbbreviationCommand extends ChangeElementPropertyCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementAbbreviationCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new name of the elemnt - */ - public ChangeElementAbbreviationCommand(Model model, Element alias, String newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - // abbreviation is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getAbbreviation()); - getAlias().setAbbreviation((String) getNewValue()); - - // abbreviation is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementAbbreviationCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new name of the elemnt + */ + public ChangeElementAbbreviationCommand(Model model, Element alias, String newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + // abbreviation is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getAbbreviation()); + getAlias().setAbbreviation((String) getNewValue()); + + // abbreviation is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommand.java index 5f42faaa87..8b3f9ec7b2 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommand.java @@ -1,12 +1,13 @@ package lcsb.mapviewer.commands.properties; -import java.awt.Color; +import java.awt.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that * {@link Element#color}. @@ -16,34 +17,34 @@ import org.apache.logging.log4j.*; */ public class ChangeElementColorCommand extends ChangeElementPropertyCommand<Color> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementColorCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new {@link Element#color} value - */ - public ChangeElementColorCommand(Model model, Element alias, Color newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getColor()); - getAlias().setColor((Color) getNewValue()); - - includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementColorCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new {@link Element#color} value + */ + public ChangeElementColorCommand(Model model, Element alias, Color newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getColor()); + getAlias().setColor((Color) getNewValue()); + + includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommand.java index f128cba3af..09b3c9a505 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFontSizeCommand.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.commands.properties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes * {@link Element#fontSize}. @@ -14,38 +15,38 @@ import org.apache.logging.log4j.*; */ public class ChangeElementFontSizeCommand extends ChangeElementPropertyCommand<Double> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementFontSizeCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new {@link Element#fontSize} value - */ - public ChangeElementFontSizeCommand(Model model, Element alias, Double newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - // abbreviation is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getFontSize()); - getAlias().setFontSize((Double) getNewValue()); - - // abbreviation is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementFontSizeCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new {@link Element#fontSize} value + */ + public ChangeElementFontSizeCommand(Model model, Element alias, Double newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + // abbreviation is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getFontSize()); + getAlias().setFontSize((Double) getNewValue()); + + // abbreviation is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommand.java index 5e82bf21d1..3e468ff3e0 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommand.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.commands.properties; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.model.Model; @@ -15,50 +16,50 @@ import lcsb.mapviewer.model.map.species.Element; */ public class ChangeElementFormerSymbolCommand extends ChangeElementPropertyListEntryCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementFormerSymbolCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementFormerSymbolCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newValue - * new {@link Element#synonym} value - * @param oldValue - * old {@link Element#synonym} value - */ - public ChangeElementFormerSymbolCommand(Model model, Element alias, String newValue, String oldValue) { - super(model, alias, newValue, oldValue); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newValue + * new {@link Element#synonym} value + * @param oldValue + * old {@link Element#synonym} value + */ + public ChangeElementFormerSymbolCommand(Model model, Element alias, String newValue, String oldValue) { + super(model, alias, newValue, oldValue); + } - @Override - protected void executeImplementation() throws CommandExecutionException { - if (getOldValue().equals(getNewValue())) { - return; - } + @Override + protected void executeImplementation() throws CommandExecutionException { + if (getOldValue().equals(getNewValue())) { + return; + } - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - int index = getAlias().getFormerSymbols().indexOf(getOldValue()); - if (index < 0) { - throw new CommandExecutionException("Former symbol " + getOldValue() + " doesn't exist."); - } - int index2 = getAlias().getFormerSymbols().indexOf(getNewValue()); - if (index2 >= 0) { - throw new CommandExecutionException("Former symbol " + getNewValue() + " already exist."); - } - getAlias().getFormerSymbols().set(index, (String) getNewValue()); + int index = getAlias().getFormerSymbols().indexOf(getOldValue()); + if (index < 0) { + throw new CommandExecutionException("Former symbol " + getOldValue() + " doesn't exist."); + } + int index2 = getAlias().getFormerSymbols().indexOf(getNewValue()); + if (index2 >= 0) { + throw new CommandExecutionException("Former symbol " + getNewValue() + " already exist."); + } + getAlias().getFormerSymbols().set(index, (String) getNewValue()); - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommand.java index 238ea5f95d..7529b9a5d2 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFormulaCommand.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.commands.properties; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; @@ -14,38 +15,38 @@ import lcsb.mapviewer.model.map.species.Element; */ public class ChangeElementFormulaCommand extends ChangeElementPropertyCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementFormulaCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new {@link Element#formula} value - */ - public ChangeElementFormulaCommand(Model model, Element alias, String newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - // formula is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getFormula()); - getAlias().setFormula((String) getNewValue()); - - // formula is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementFormulaCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new {@link Element#formula} value + */ + public ChangeElementFormulaCommand(Model model, Element alias, String newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + // formula is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getFormula()); + getAlias().setFormula((String) getNewValue()); + + // formula is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommand.java index cdf2c16147..cfc3d8c42b 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementFullNameCommand.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.commands.properties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes full * name of the element connected to {@link Element}. @@ -14,38 +15,38 @@ import org.apache.logging.log4j.*; */ public class ChangeElementFullNameCommand extends ChangeElementPropertyCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementFullNameCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new {@link Element#fullName} value - */ - public ChangeElementFullNameCommand(Model model, Element alias, String newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - // fullname is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getFullName()); - getAlias().setFullName((String) getNewValue()); - - // fullname is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementFullNameCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new {@link Element#fullName} value + */ + public ChangeElementFullNameCommand(Model model, Element alias, String newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + // fullname is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getFullName()); + getAlias().setFullName((String) getNewValue()); + + // fullname is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommand.java index 6062330455..87a4e8ea5e 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementMiriamDataCommand.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.commands.properties; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.MiriamData; @@ -16,53 +17,53 @@ import lcsb.mapviewer.model.map.species.Element; */ public class ChangeElementMiriamDataCommand extends ChangeElementPropertyListEntryCommand<MiriamData> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementMiriamDataCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementMiriamDataCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newValue - * new annotation value - * @param oldValue - * old annotation value - */ - public ChangeElementMiriamDataCommand(Model model, Element alias, MiriamData newValue, MiriamData oldValue) { - super(model, alias, newValue, oldValue); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newValue + * new annotation value + * @param oldValue + * old annotation value + */ + public ChangeElementMiriamDataCommand(Model model, Element alias, MiriamData newValue, MiriamData oldValue) { + super(model, alias, newValue, oldValue); + } - @Override - protected void executeImplementation() throws CommandExecutionException { - // if there is no change then return - if (getOldValue().equals(getNewValue())) { - return; - } + @Override + protected void executeImplementation() throws CommandExecutionException { + // if there is no change then return + if (getOldValue().equals(getNewValue())) { + return; + } - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - if (!getAlias().getMiriamData().contains(getOldValue())) { - throw new CommandExecutionException("Miriam " + getOldValue() + " doesn't exist."); - } - if (getAlias().getMiriamData().contains(getNewValue())) { - throw new CommandExecutionException("Miriam " + getNewValue() + " already exist."); - } - getAlias().getMiriamData().remove(getOldValue()); - getOldValue().setDataType(getNewValue().getDataType()); - getOldValue().setRelationType(getNewValue().getRelationType()); - getOldValue().setResource(getNewValue().getResource()); - getAlias().getMiriamData().add(getOldValue()); + if (!getAlias().getMiriamData().contains(getOldValue())) { + throw new CommandExecutionException("Miriam " + getOldValue() + " doesn't exist."); + } + if (getAlias().getMiriamData().contains(getNewValue())) { + throw new CommandExecutionException("Miriam " + getNewValue() + " already exist."); + } + getAlias().getMiriamData().remove(getOldValue()); + getOldValue().setDataType(getNewValue().getDataType()); + getOldValue().setRelationType(getNewValue().getRelationType()); + getOldValue().setResource(getNewValue().getResource()); + getAlias().getMiriamData().add(getOldValue()); - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommand.java index 7a6f4d5d7f..6890836955 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNameCommand.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.commands.properties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes name * of the element connected to {@link Element}. @@ -14,34 +15,34 @@ import org.apache.logging.log4j.*; */ public class ChangeElementNameCommand extends ChangeElementPropertyCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementNameCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new name of the elemnt - */ - public ChangeElementNameCommand(Model model, Element alias, String newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getName()); - getAlias().setName((String) getNewValue()); - - includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementNameCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new name of the elemnt + */ + public ChangeElementNameCommand(Model model, Element alias, String newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getName()); + getAlias().setName((String) getNewValue()); + + includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommand.java index 77a25a50bd..9ae0f8a006 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementNotesCommand.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.commands.properties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes notes * of the element connected to {@link Element}. @@ -14,38 +15,38 @@ import org.apache.logging.log4j.*; */ public class ChangeElementNotesCommand extends ChangeElementPropertyCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementNotesCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new {@link Element#notes} value - */ - public ChangeElementNotesCommand(Model model, Element alias, String newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - // notes is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getNotes()); - getAlias().setNotes((String) getNewValue()); - - // notes is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementNotesCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new {@link Element#notes} value + */ + public ChangeElementNotesCommand(Model model, Element alias, String newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + // notes is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getNotes()); + getAlias().setNotes((String) getNewValue()); + + // notes is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyCommand.java index 6613c69e48..b3259d67df 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyCommand.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.commands.properties; -import lcsb.mapviewer.commands.CommandExecutionException; -import lcsb.mapviewer.commands.ModelCommand; -import lcsb.mapviewer.commands.ModelCommandStatus; +import lcsb.mapviewer.commands.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; @@ -18,103 +16,103 @@ import lcsb.mapviewer.model.map.species.Element; */ public abstract class ChangeElementPropertyCommand<T> extends ModelCommand { - /** - * New element property value. - */ - private T newValue; + /** + * New element property value. + */ + private T newValue; - /** - * Old element property value. - */ - private T oldValue; + /** + * Old element property value. + */ + private T oldValue; - /** - * {@link Element} for which we will change the property. - */ - private Element alias; + /** + * {@link Element} for which we will change the property. + */ + private Element alias; - /** - * Default constructor. - * - * @param model - * model to move - * - * @param alias - * alias to be changed - * - * @param newValue - * new value of the element property - */ - public ChangeElementPropertyCommand(Model model, Element alias, T newValue) { - super(model); - this.alias = alias; - this.newValue = newValue; - } + /** + * Default constructor. + * + * @param model + * model to move + * + * @param alias + * alias to be changed + * + * @param newValue + * new value of the element property + */ + public ChangeElementPropertyCommand(Model model, Element alias, T newValue) { + super(model); + this.alias = alias; + this.newValue = newValue; + } - @Override - protected void undoImplementation() throws CommandExecutionException { - T tmp = newValue; - newValue = oldValue; - executeImplementation(); - newValue = tmp; - oldValue = null; - setStatus(ModelCommandStatus.UNDONE); - } + @Override + protected void undoImplementation() throws CommandExecutionException { + T tmp = newValue; + newValue = oldValue; + executeImplementation(); + newValue = tmp; + oldValue = null; + setStatus(ModelCommandStatus.UNDONE); + } - @Override - protected void redoImplementation() throws CommandExecutionException { - executeImplementation(); - setStatus(ModelCommandStatus.EXECUTED); - } + @Override + protected void redoImplementation() throws CommandExecutionException { + executeImplementation(); + setStatus(ModelCommandStatus.EXECUTED); + } - /** - * @return the alias - * @see #alias - */ - protected Element getAlias() { - return alias; - } + /** + * @return the alias + * @see #alias + */ + protected Element getAlias() { + return alias; + } - /** - * @param alias - * the alias to set - * @see #alias - */ - protected void setAlias(Element alias) { - this.alias = alias; - } + /** + * @param alias + * the alias to set + * @see #alias + */ + protected void setAlias(Element alias) { + this.alias = alias; + } - /** - * @return the oldValue - * @see #oldValue - */ - protected Object getOldValue() { - return oldValue; - } + /** + * @return the oldValue + * @see #oldValue + */ + protected Object getOldValue() { + return oldValue; + } - /** - * @param oldValue - * the oldValue to set - * @see #oldValue - */ - protected void setOldValue(T oldValue) { - this.oldValue = oldValue; - } + /** + * @param oldValue + * the oldValue to set + * @see #oldValue + */ + protected void setOldValue(T oldValue) { + this.oldValue = oldValue; + } - /** - * @return the newValue - * @see #newValue - */ - protected Object getNewValue() { - return newValue; - } + /** + * @return the newValue + * @see #newValue + */ + protected Object getNewValue() { + return newValue; + } - /** - * @param newValue - * the newValue to set - * @see #newValue - */ - protected void setNewValue(T newValue) { - this.newValue = newValue; - } + /** + * @param newValue + * the newValue to set + * @see #newValue + */ + protected void setNewValue(T newValue) { + this.newValue = newValue; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyListEntryCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyListEntryCommand.java index b842c08eca..cb1f3a8250 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyListEntryCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementPropertyListEntryCommand.java @@ -1,15 +1,12 @@ package lcsb.mapviewer.commands.properties; -import lcsb.mapviewer.commands.CommandExecutionException; -import lcsb.mapviewer.commands.ModelCommand; -import lcsb.mapviewer.commands.ModelCommandStatus; +import lcsb.mapviewer.commands.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes single - * entry in a property of the {@link Element Element} - * that is list. + * entry in a property of the {@link Element Element} that is list. * * @param <T> * class of property to edit @@ -19,109 +16,109 @@ import lcsb.mapviewer.model.map.species.Element; */ public abstract class ChangeElementPropertyListEntryCommand<T> extends ModelCommand { - /** - * New element property value. - */ - private T newValue; + /** + * New element property value. + */ + private T newValue; - /** - * Old element property value. - */ - private T oldValue; + /** + * Old element property value. + */ + private T oldValue; - /** - * {@link Element} for which we will change the property. - */ - private Element alias; + /** + * {@link Element} for which we will change the property. + */ + private Element alias; - /** - * Default constructor. - * - * @param model - * model to move - * - * @param alias - * alias to be changed - * - * @param newValue - * new value of the element property - * - * @param oldValue - * old value of the element property - */ - public ChangeElementPropertyListEntryCommand(Model model, Element alias, T newValue, T oldValue) { - super(model); - this.alias = alias; - this.oldValue = oldValue; - this.newValue = newValue; - } + /** + * Default constructor. + * + * @param model + * model to move + * + * @param alias + * alias to be changed + * + * @param newValue + * new value of the element property + * + * @param oldValue + * old value of the element property + */ + public ChangeElementPropertyListEntryCommand(Model model, Element alias, T newValue, T oldValue) { + super(model); + this.alias = alias; + this.oldValue = oldValue; + this.newValue = newValue; + } - @Override - protected void undoImplementation() throws CommandExecutionException { - T tmpNewValue = newValue; - T tmpOldValue = oldValue; - newValue = tmpOldValue; - oldValue = tmpNewValue; - executeImplementation(); - newValue = tmpNewValue; - oldValue = tmpOldValue; - setStatus(ModelCommandStatus.UNDONE); - } + @Override + protected void undoImplementation() throws CommandExecutionException { + T tmpNewValue = newValue; + T tmpOldValue = oldValue; + newValue = tmpOldValue; + oldValue = tmpNewValue; + executeImplementation(); + newValue = tmpNewValue; + oldValue = tmpOldValue; + setStatus(ModelCommandStatus.UNDONE); + } - @Override - protected void redoImplementation() throws CommandExecutionException { - executeImplementation(); - setStatus(ModelCommandStatus.EXECUTED); - } + @Override + protected void redoImplementation() throws CommandExecutionException { + executeImplementation(); + setStatus(ModelCommandStatus.EXECUTED); + } - /** - * @return the alias - * @see #alias - */ - protected Element getAlias() { - return alias; - } + /** + * @return the alias + * @see #alias + */ + protected Element getAlias() { + return alias; + } - /** - * @param alias - * the alias to set - * @see #alias - */ - protected void setAlias(Element alias) { - this.alias = alias; - } + /** + * @param alias + * the alias to set + * @see #alias + */ + protected void setAlias(Element alias) { + this.alias = alias; + } - /** - * @return the oldValue - * @see #oldValue - */ - protected T getOldValue() { - return oldValue; - } + /** + * @return the oldValue + * @see #oldValue + */ + protected T getOldValue() { + return oldValue; + } - /** - * @param oldValue - * the oldValue to set - * @see #oldValue - */ - protected void setOldValue(T oldValue) { - this.oldValue = oldValue; - } + /** + * @param oldValue + * the oldValue to set + * @see #oldValue + */ + protected void setOldValue(T oldValue) { + this.oldValue = oldValue; + } - /** - * @return the newValue - * @see #newValue - */ - protected T getNewValue() { - return newValue; - } + /** + * @return the newValue + * @see #newValue + */ + protected T getNewValue() { + return newValue; + } - /** - * @param newValue - * the newValue to set - * @see #newValue - */ - protected void setNewValue(T newValue) { - this.newValue = newValue; - } + /** + * @param newValue + * the newValue to set + * @see #newValue + */ + protected void setNewValue(T newValue) { + this.newValue = newValue; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommand.java index 646926e4d5..21197254af 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSymbolCommand.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.commands.properties; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; -import org.apache.logging.log4j.*; - /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that changes symbol * of the element connected to {@link Element}. @@ -14,38 +15,38 @@ import org.apache.logging.log4j.*; */ public class ChangeElementSymbolCommand extends ChangeElementPropertyCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementSymbolCommand.class); - - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newName - * new {@link Element#symbol} value - */ - public ChangeElementSymbolCommand(Model model, Element alias, String newName) { - super(model, alias, newName); - } - - @Override - protected void executeImplementation() { - - // symbol is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - - setOldValue(getAlias().getSymbol()); - getAlias().setSymbol((String) getNewValue()); - - // symbol is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementSymbolCommand.class); + + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newName + * new {@link Element#symbol} value + */ + public ChangeElementSymbolCommand(Model model, Element alias, String newName) { + super(model, alias, newName); + } + + @Override + protected void executeImplementation() { + + // symbol is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + + setOldValue(getAlias().getSymbol()); + getAlias().setSymbol((String) getNewValue()); + + // symbol is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommand.java index 8c0d2705b0..dd3b797660 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/ChangeElementSynonymCommand.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.commands.properties; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.model.Model; @@ -15,50 +16,50 @@ import lcsb.mapviewer.model.map.species.Element; */ public class ChangeElementSynonymCommand extends ChangeElementPropertyListEntryCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ChangeElementSynonymCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ChangeElementSynonymCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param newValue - * new {@link Element#synonym} value - * @param oldValue - * old {@link Element#synonym} value - */ - public ChangeElementSynonymCommand(Model model, Element alias, String newValue, String oldValue) { - super(model, alias, newValue, oldValue); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param newValue + * new {@link Element#synonym} value + * @param oldValue + * old {@link Element#synonym} value + */ + public ChangeElementSynonymCommand(Model model, Element alias, String newValue, String oldValue) { + super(model, alias, newValue, oldValue); + } - @Override - protected void executeImplementation() throws CommandExecutionException { - if (getOldValue().equals(getNewValue())) { - return; - } + @Override + protected void executeImplementation() throws CommandExecutionException { + if (getOldValue().equals(getNewValue())) { + return; + } - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - int index = getAlias().getSynonyms().indexOf(getOldValue()); - if (index < 0) { - throw new CommandExecutionException("Synonym " + getOldValue() + " doesn't exist."); - } - int index2 = getAlias().getSynonyms().indexOf(getNewValue()); - if (index2 >= 0) { - throw new CommandExecutionException("Synonym " + getNewValue() + " already exist."); - } - getAlias().getSynonyms().set(index, getNewValue()); + int index = getAlias().getSynonyms().indexOf(getOldValue()); + if (index < 0) { + throw new CommandExecutionException("Synonym " + getOldValue() + " doesn't exist."); + } + int index2 = getAlias().getSynonyms().indexOf(getNewValue()); + if (index2 >= 0) { + throw new CommandExecutionException("Synonym " + getNewValue() + " already exist."); + } + getAlias().getSynonyms().set(index, getNewValue()); - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementFormerSymbolsCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementFormerSymbolsCommand.java index 13e233fd70..cde5df4197 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementFormerSymbolsCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementFormerSymbolsCommand.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.model.Model; @@ -17,57 +18,58 @@ import lcsb.mapviewer.model.map.species.Element; */ public class RemoveElementFormerSymbolsCommand extends RemoveElementPropertyListEntryCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(RemoveElementFormerSymbolsCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(RemoveElementFormerSymbolsCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param values - * {@link Element#synonym} values to be removed - */ - public RemoveElementFormerSymbolsCommand(Model model, Element alias, List<String> values) { - super(model, alias, values); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param values + * {@link Element#synonym} values to be removed + */ + public RemoveElementFormerSymbolsCommand(Model model, Element alias, List<String> values) { + super(model, alias, values); + } - @Override - protected void executeImplementation() throws CommandExecutionException { + @Override + protected void undoImplementation() { + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getFormerSymbols().addAll(getValues()); - for (String string : getValues()) { - if (!getAlias().getFormerSymbols().contains(string)) { - throw new CommandExecutionException("Cannot remove former symbol \"" + string + "\" from the list. Element doesn't exist."); - } - } + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getFormerSymbols().removeAll(getValues()); + } - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + @Override + protected void executeImplementation() throws CommandExecutionException { - @Override - protected void undoImplementation() { - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getFormerSymbols().addAll(getValues()); + for (String string : getValues()) { + if (!getAlias().getFormerSymbols().contains(string)) { + throw new CommandExecutionException( + "Cannot remove former symbol \"" + string + "\" from the list. Element doesn't exist."); + } + } - // former symbols are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getFormerSymbols().removeAll(getValues()); - } + // former symbols are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementMiriamDataCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementMiriamDataCommand.java index 4a7bc50cf0..5a929d61c8 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementMiriamDataCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementMiriamDataCommand.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.MiriamData; @@ -18,57 +19,58 @@ import lcsb.mapviewer.model.map.species.Element; */ public class RemoveElementMiriamDataCommand extends RemoveElementPropertyListEntryCommand<MiriamData> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(RemoveElementMiriamDataCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(RemoveElementMiriamDataCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param values - * {@link Element#synonym} values to be removed - */ - public RemoveElementMiriamDataCommand(Model model, Element alias, List<MiriamData> values) { - super(model, alias, values); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param values + * {@link Element#synonym} values to be removed + */ + public RemoveElementMiriamDataCommand(Model model, Element alias, List<MiriamData> values) { + super(model, alias, values); + } - @Override - protected void executeImplementation() throws CommandExecutionException { + @Override + protected void undoImplementation() { + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getMiriamData().addAll(getValues()); - for (MiriamData string : getValues()) { - if (!getAlias().getMiriamData().contains(string)) { - throw new CommandExecutionException("Cannot remove miriam \"" + string + "\" from the list. Element doesn't exist."); - } - } + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getMiriamData().removeAll(getValues()); + } - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + @Override + protected void executeImplementation() throws CommandExecutionException { - @Override - protected void undoImplementation() { - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getMiriamData().addAll(getValues()); + for (MiriamData string : getValues()) { + if (!getAlias().getMiriamData().contains(string)) { + throw new CommandExecutionException( + "Cannot remove miriam \"" + string + "\" from the list. Element doesn't exist."); + } + } - // miriam data is not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getMiriamData().removeAll(getValues()); - } + // miriam data is not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementPropertyListEntryCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementPropertyListEntryCommand.java index b61167bc40..0a2b660b3a 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementPropertyListEntryCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementPropertyListEntryCommand.java @@ -2,16 +2,13 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import lcsb.mapviewer.commands.CommandExecutionException; -import lcsb.mapviewer.commands.ModelCommand; -import lcsb.mapviewer.commands.ModelCommandStatus; +import lcsb.mapviewer.commands.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; /** * {@link lcsb.mapviewer.commands.ModelCommand ModelCommand} that removes - * entries from a property of the {@link Element - * Element} that is list. + * entries from a property of the {@link Element Element} that is list. * * @param <T> * class of property to edit @@ -21,72 +18,72 @@ import lcsb.mapviewer.model.map.species.Element; */ public abstract class RemoveElementPropertyListEntryCommand<T> extends ModelCommand { - /** - * Rlement property values to be removed. - */ - private List<T> values; + /** + * Rlement property values to be removed. + */ + private List<T> values; - /** - * {@link Element} for which we will change the property. - */ - private Element alias; + /** + * {@link Element} for which we will change the property. + */ + private Element alias; - /** - * Default constructor. - * - * @param model - * model to move - * - * @param alias - * alias to be changed - * - * @param values - * values of the element property to remove - */ - public RemoveElementPropertyListEntryCommand(Model model, Element alias, List<T> values) { - super(model); - this.alias = alias; - this.values = values; - } + /** + * Default constructor. + * + * @param model + * model to move + * + * @param alias + * alias to be changed + * + * @param values + * values of the element property to remove + */ + public RemoveElementPropertyListEntryCommand(Model model, Element alias, List<T> values) { + super(model); + this.alias = alias; + this.values = values; + } - @Override - protected void redoImplementation() throws CommandExecutionException { - executeImplementation(); - setStatus(ModelCommandStatus.EXECUTED); - } + @Override + protected void redoImplementation() throws CommandExecutionException { + executeImplementation(); + setStatus(ModelCommandStatus.EXECUTED); + } - /** - * @return the alias - * @see #alias - */ - protected Element getAlias() { - return alias; - } + /** + * @return the alias + * @see #alias + */ + protected Element getAlias() { + return alias; + } - /** - * @param alias - * the alias to set - * @see #alias - */ - protected void setAlias(Element alias) { - this.alias = alias; - } + /** + * @param alias + * the alias to set + * @see #alias + */ + protected void setAlias(Element alias) { + this.alias = alias; + } - /** - * @return the values - * @see #values - */ - public List<T> getValues() { - return values; - } + /** + * @return the values + * @see #values + */ + public List<T> getValues() { + return values; + } - /** - * @param values - * the values to set - * @see #values - */ - public void setValues(List<T> values) { - this.values = values; - } + /** + * @param values + * the values to set + * @see #values + */ + public void setValues(List<T> values) { + this.values = values; + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementSynonymsCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementSynonymsCommand.java index 318510ec51..f70347cc9f 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementSynonymsCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/RemoveElementSynonymsCommand.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.commands.properties; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.model.map.model.Model; @@ -17,57 +18,58 @@ import lcsb.mapviewer.model.map.species.Element; */ public class RemoveElementSynonymsCommand extends RemoveElementPropertyListEntryCommand<String> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(RemoveElementSynonymsCommand.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(RemoveElementSynonymsCommand.class); - /** - * Default constructor. - * - * @param model - * {@link lcsb.mapviewer.commands.ModelCommand#model} - * @param alias - * {@link ChangeElementPropertyCommand#alias} - * @param values - * {@link Element#synonym} values to be removed - */ - public RemoveElementSynonymsCommand(Model model, Element alias, List<String> values) { - super(model, alias, values); - } + /** + * Default constructor. + * + * @param model + * {@link lcsb.mapviewer.commands.ModelCommand#model} + * @param alias + * {@link ChangeElementPropertyCommand#alias} + * @param values + * {@link Element#synonym} values to be removed + */ + public RemoveElementSynonymsCommand(Model model, Element alias, List<String> values) { + super(model, alias, values); + } - @Override - protected void executeImplementation() throws CommandExecutionException { + @Override + protected void undoImplementation() { + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getSynonyms().addAll(getValues()); - for (String string : getValues()) { - if (!getAlias().getSynonyms().contains(string)) { - throw new CommandExecutionException("Cannot remove synonym from the list: " + string + ". Element doesn't exist."); - } - } + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getSynonyms().removeAll(getValues()); + } - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); - } + @Override + protected void executeImplementation() throws CommandExecutionException { - @Override - protected void undoImplementation() { - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); - getAlias().getSynonyms().addAll(getValues()); + for (String string : getValues()) { + if (!getAlias().getSynonyms().contains(string)) { + throw new CommandExecutionException( + "Cannot remove synonym from the list: " + string + ". Element doesn't exist."); + } + } - // synonyms are not visualized, so we don't need to report any - // visualization changes - // includeInAffectedRegion(getAlias()); + getAlias().getSynonyms().removeAll(getValues()); - } + // synonyms are not visualized, so we don't need to report any + // visualization changes + // includeInAffectedRegion(getAlias()); + } } diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/properties/package-info.java b/model-command/src/main/java/lcsb/mapviewer/commands/properties/package-info.java index 900c3f4675..3769d5ed6c 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/properties/package-info.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/properties/package-info.java @@ -5,4 +5,3 @@ * */ package lcsb.mapviewer.commands.properties; - diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/AllCommandsTests.java b/model-command/src/test/java/lcsb/mapviewer/commands/AllCommandsTests.java index 1357d8589e..afc4a01a40 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/AllCommandsTests.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/AllCommandsTests.java @@ -1,12 +1,12 @@ package lcsb.mapviewer.commands; -import lcsb.mapviewer.commands.layout.AllLayoutTests; -import lcsb.mapviewer.commands.properties.AllPropertyCommandTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.commands.layout.AllLayoutTests; +import lcsb.mapviewer.commands.properties.AllPropertyCommandTests; + @RunWith(Suite.class) @SuiteClasses({ AllLayoutTests.class, AllPropertyCommandTests.class, 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 16db4493fc..b60c45de52 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java @@ -2,8 +2,9 @@ package lcsb.mapviewer.commands; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.util.*; +import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; 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 6ebfaff56f..88df2a2dda 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/CommandTestFunctions.java @@ -3,12 +3,10 @@ package lcsb.mapviewer.commands; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Rule; import lcsb.mapviewer.common.UnitTestFailedWatcher; @@ -23,15 +21,12 @@ import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.model.map.species.GenericProtein; public abstract class CommandTestFunctions { + private static Map<String, Model> models = new HashMap<String, Model>(); public double EPSILON = 1e-6; - @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - Logger logger = LogManager.getLogger(CommandTestFunctions.class); - private static Map<String, Model> models = new HashMap<String, Model>(); - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { if (!fromCache) { logger.debug("File without cache: " + fileName); @@ -79,11 +74,11 @@ public abstract class CommandTestFunctions { String xmlString = parser.model2String(original); InputStream stream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)); Model result = parser.createModel(new ConverterParams().inputStream(stream).sizeAutoAdjust(false)); - - for (Drawable bioEntity: original.getDrawables()) { + + for (Drawable bioEntity : original.getDrawables()) { bioEntity.setZ(null); } - for (Drawable bioEntity: result.getDrawables()) { + for (Drawable bioEntity : result.getDrawables()) { bioEntity.setZ(null); } return result; diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java index 881e2d9e3d..3bdcd703ad 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/SubModelCommandTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.commands; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import java.awt.geom.Path2D; import java.util.Arrays; diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/AllPropertyCommandTests.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/AllPropertyCommandTests.java index d0b9fc798b..0a456a10da 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/AllPropertyCommandTests.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/AllPropertyCommandTests.java @@ -6,17 +6,17 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ChangeElementAbbreviationCommandTest.class, - ChangeElementColorCommandTest.class, - ChangeElementFontSizeCommandTest.class, - ChangeElementFormerSymbolCommandTest.class, - ChangeElementFormulaCommandTest.class, - ChangeElementFullNameCommandTest.class, - ChangeElementMiriamDataCommandTest.class, - ChangeElementNameCommandTest.class, - ChangeElementNotesCommandTest.class, - ChangeElementSymbolCommandTest.class, - ChangeElementSynonymCommandTest.class, - + ChangeElementColorCommandTest.class, + ChangeElementFontSizeCommandTest.class, + ChangeElementFormerSymbolCommandTest.class, + ChangeElementFormulaCommandTest.class, + ChangeElementFullNameCommandTest.class, + ChangeElementMiriamDataCommandTest.class, + ChangeElementNameCommandTest.class, + ChangeElementNotesCommandTest.class, + ChangeElementSymbolCommandTest.class, + ChangeElementSynonymCommandTest.class, + }) public class AllPropertyCommandTests { diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java index 38fe93c7bb..bf3b226e50 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementColorCommandTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.commands.properties; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.junit.*; diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java index 74762f248b..dfadfb32ea 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/properties/ChangeElementFormerSymbolCommandTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.commands.properties; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; import org.junit.*; diff --git a/model/src/main/java/lcsb/mapviewer/model/Project.java b/model/src/main/java/lcsb/mapviewer/model/Project.java index c19fdba60e..f4d5edb4c8 100644 --- a/model/src/main/java/lcsb/mapviewer/model/Project.java +++ b/model/src/main/java/lcsb/mapviewer/model/Project.java @@ -1,21 +1,15 @@ package lcsb.mapviewer.model; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import javax.persistence.*; +import javax.persistence.Entity; +import javax.persistence.OrderBy; import org.apache.logging.log4j.core.LogEvent; - -import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; - import lcsb.mapviewer.common.MinervaLoggerAppender; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -205,14 +199,14 @@ public class Project implements Serializable { this.disease = disease; } - public void setOrganism(MiriamData organism) { - this.organism = organism; - } - public MiriamData getOrganism() { return organism; } + public void setOrganism(MiriamData organism) { + this.organism = organism; + } + public void addWarning(String warning) { if (warning.trim().contains("\n")) { throw new InvalidArgumentException("Warning must be one line of text"); @@ -264,7 +258,7 @@ public class Project implements Serializable { public void addLoggingInfo(MinervaLoggerAppender appender) { List<String> warnings = new ArrayList<>(); for (LogEvent event : appender.getWarnings()) { - warnings.add(event.getMessage().getFormattedMessage().replaceAll("\n", "_NEW_LINE_")); + warnings.add(event.getMessage().getFormattedMessage().replaceAll("\n", "_NEW_LINE_")); } addWarnings(warnings); } diff --git a/model/src/main/java/lcsb/mapviewer/model/cache/BigFileEntry.java b/model/src/main/java/lcsb/mapviewer/model/cache/BigFileEntry.java index ee01e60a6c..3e821853e9 100644 --- a/model/src/main/java/lcsb/mapviewer/model/cache/BigFileEntry.java +++ b/model/src/main/java/lcsb/mapviewer/model/cache/BigFileEntry.java @@ -3,9 +3,7 @@ package lcsb.mapviewer.model.cache; import java.io.Serializable; import java.util.Calendar; -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; +import javax.persistence.*; import lcsb.mapviewer.common.IProgressUpdater; diff --git a/model/src/main/java/lcsb/mapviewer/model/cache/CacheQuery.java b/model/src/main/java/lcsb/mapviewer/model/cache/CacheQuery.java index 419ec89421..5f7773b19b 100644 --- a/model/src/main/java/lcsb/mapviewer/model/cache/CacheQuery.java +++ b/model/src/main/java/lcsb/mapviewer/model/cache/CacheQuery.java @@ -3,13 +3,7 @@ package lcsb.mapviewer.model.cache; import java.io.Serializable; import java.util.Calendar; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; +import javax.persistence.*; /** * Object that defines cached value retrieved from external resource. The key in @@ -136,6 +130,15 @@ public class CacheQuery implements Serializable { this.type = type; } + /** + * + * @param type2 + * new {@link #type} value + */ + public void setType(CacheType type2) { + this.type = type2.getId(); + } + /** * @return the expires * @see #expires @@ -170,13 +173,4 @@ public class CacheQuery implements Serializable { this.accessed = accessed; } - /** - * - * @param type2 - * new {@link #type} value - */ - public void setType(CacheType type2) { - this.type = type2.getId(); - } - } diff --git a/model/src/main/java/lcsb/mapviewer/model/cache/CacheType.java b/model/src/main/java/lcsb/mapviewer/model/cache/CacheType.java index 8c209bfec6..f620f05083 100644 --- a/model/src/main/java/lcsb/mapviewer/model/cache/CacheType.java +++ b/model/src/main/java/lcsb/mapviewer/model/cache/CacheType.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.model.cache; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; /** * Defines types of objects stored in the cache and interfaces used for diff --git a/model/src/main/java/lcsb/mapviewer/model/cache/FileEntry.java b/model/src/main/java/lcsb/mapviewer/model/cache/FileEntry.java index b4bebc29f0..ff3f241e93 100644 --- a/model/src/main/java/lcsb/mapviewer/model/cache/FileEntry.java +++ b/model/src/main/java/lcsb/mapviewer/model/cache/FileEntry.java @@ -2,15 +2,7 @@ package lcsb.mapviewer.model.cache; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; +import javax.persistence.*; /** * Database object representing file put in the system (it can be some cached diff --git a/model/src/main/java/lcsb/mapviewer/model/cache/UploadedFileEntry.java b/model/src/main/java/lcsb/mapviewer/model/cache/UploadedFileEntry.java index 6d36a152d0..a36354e420 100644 --- a/model/src/main/java/lcsb/mapviewer/model/cache/UploadedFileEntry.java +++ b/model/src/main/java/lcsb/mapviewer/model/cache/UploadedFileEntry.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.model.cache; import java.io.Serializable; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.model.user.User; diff --git a/model/src/main/java/lcsb/mapviewer/model/cache/package-info.java b/model/src/main/java/lcsb/mapviewer/model/cache/package-info.java index eeada7b7b0..7b7108e1ac 100644 --- a/model/src/main/java/lcsb/mapviewer/model/cache/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/cache/package-info.java @@ -2,4 +2,3 @@ * Contains structures used for storing cached data. */ package lcsb.mapviewer.model.cache; - diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowType.java b/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowType.java index d59fee3b9f..f4db2ef1e4 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowType.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowType.java @@ -27,7 +27,7 @@ public enum ArrowType { * /> */ BLANK_CROSSBAR, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -37,7 +37,7 @@ public enum ArrowType { * */ FULL_CROSSBAR, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -47,7 +47,7 @@ public enum ArrowType { * */ DIAMOND, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -56,7 +56,7 @@ public enum ArrowType { * /> */ BLANK, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -66,7 +66,7 @@ public enum ArrowType { * */ CROSSBAR, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -75,7 +75,7 @@ public enum ArrowType { * /> * */ CIRCLE, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -84,7 +84,7 @@ public enum ArrowType { * /> */ OPEN, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> @@ -93,7 +93,7 @@ public enum ArrowType { * /> */ FULL, - + /** * The arrow end that should look as an image bellow. <br/> * <br/> diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparator.java b/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparator.java index 63a3dfcfd1..33da4e15f6 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.graphics; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/LineType.java b/model/src/main/java/lcsb/mapviewer/model/graphics/LineType.java index 908cff784d..5040ec54a1 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/LineType.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/LineType.java @@ -1,7 +1,6 @@ package lcsb.mapviewer.model.graphics; -import java.awt.BasicStroke; -import java.awt.Stroke; +import java.awt.*; import java.util.List; import lcsb.mapviewer.common.comparator.FloatComparator; @@ -126,15 +125,6 @@ public enum LineType { 0.0f); } - /** - * Return the {@link BasicStroke} for this line type. - * - * @return the {@link BasicStroke} for this line type - */ - public Stroke getStroke() { - return stroke; - } - public static LineType getTypeByDashArray(List<Short> strokeDashArray) { FloatComparator doubleComparator = new FloatComparator(); for (LineType type : LineType.values()) { @@ -155,4 +145,13 @@ public enum LineType { } return LineType.SOLID; } + + /** + * Return the {@link BasicStroke} for this line type. + * + * @return the {@link BasicStroke} for this line type + */ + public Stroke getStroke() { + return stroke; + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/MapCanvasType.java b/model/src/main/java/lcsb/mapviewer/model/graphics/MapCanvasType.java index 0c400788d7..8c84cfb17c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/MapCanvasType.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/MapCanvasType.java @@ -1,7 +1,8 @@ package lcsb.mapviewer.model.graphics; public enum MapCanvasType { - GOOGLE_MAPS_API("Google Maps API"), OPEN_LAYERS("OpenLayers"); + GOOGLE_MAPS_API("Google Maps API"), + OPEN_LAYERS("OpenLayers"); private String commonName; diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineData.java b/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineData.java index 9f0fc47877..f25e0c205e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineData.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineData.java @@ -1,31 +1,18 @@ package lcsb.mapviewer.model.graphics; -import java.awt.Color; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; +import java.awt.*; +import java.awt.geom.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; +import javax.persistence.*; import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.OrderColumn; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.Type; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -232,9 +219,18 @@ public class PolylineData implements Serializable, Drawable { return result; } + /** + * Returns coordinates of the last point in the line. + * + * @return coordinates of the last point in the line + */ + public Point2D getEndPoint() { + return points.get(points.size() - 1); + } + /** * Sets the new value of the last point in the line. - * + * * @param point * new value of the last point in the line */ @@ -242,15 +238,6 @@ public class PolylineData implements Serializable, Drawable { setPoint(points.size() - 1, point); } - /** - * Returns coordinates of the last point in the line. - * - * @return coordinates of the last point in the line - */ - public Point2D getEndPoint() { - return points.get(points.size() - 1); - } - /** * Transforms line representation into {@link GeneralPath} class. * @@ -443,6 +430,15 @@ public class PolylineData implements Serializable, Drawable { this.width = width; } + /** + * @param string + * the width to set + * @see #width + */ + public void setWidth(String string) { + setWidth(Double.parseDouble(string)); + } + /** * @return the color * @see #color @@ -494,15 +490,6 @@ public class PolylineData implements Serializable, Drawable { this.id = id; } - /** - * @param string - * the width to set - * @see #width - */ - public void setWidth(String string) { - setWidth(Double.parseDouble(string)); - } - /** * Prepares a copy of the object. * @@ -537,12 +524,12 @@ public class PolylineData implements Serializable, Drawable { } @Override - public double getSize() { - return 0; + public String getElementId() { + return toString(); } @Override - public String getElementId() { - return toString(); + public double getSize() { + return 0; } } diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineDataComparator.java b/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineDataComparator.java index 0dd770744b..760d473337 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineDataComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/PolylineDataComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.graphics; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/graphics/package-info.java b/model/src/main/java/lcsb/mapviewer/model/graphics/package-info.java index 12c79169f4..6f900188e2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/graphics/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/graphics/package-info.java @@ -3,4 +3,3 @@ * have to belong to the map. */ package lcsb.mapviewer.model.graphics; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/BioEntity.java b/model/src/main/java/lcsb/mapviewer/model/map/BioEntity.java index 9879bc60c5..59d6324012 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/BioEntity.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/BioEntity.java @@ -1,9 +1,7 @@ package lcsb.mapviewer.model.map; import java.io.Serializable; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; +import java.util.*; import lcsb.mapviewer.common.comparator.IntegerComparator; import lcsb.mapviewer.model.map.model.Model; @@ -68,6 +66,15 @@ public interface BioEntity extends Serializable, Drawable { */ String getName(); + /** + * Sets the name to the object. + * + * @param name + * name of the object + * + */ + void setName(String name); + /** * Returns notes about the object. * @@ -128,14 +135,6 @@ public interface BioEntity extends Serializable, Drawable { */ void setAbbreviation(String abbreviation); - /** - * Sets formula. - * - * @param formula - * new formula - */ - void setFormula(String formula); - /** * Returns the formula. * @@ -144,13 +143,12 @@ public interface BioEntity extends Serializable, Drawable { String getFormula(); /** - * Sets the name to the object. - * - * @param name - * name of the object + * Sets formula. * + * @param formula + * new formula */ - void setName(String name); + void setFormula(String formula); /** * Returns database identifier of the object. @@ -166,6 +164,13 @@ public interface BioEntity extends Serializable, Drawable { */ String getStringType(); + /** + * Returns semantic zoom level visibility. + * + * @return semantic zoom level visibility + */ + String getVisibilityLevel(); + /** * Sets semantic zoom level visibility. * @@ -182,13 +187,6 @@ public interface BioEntity extends Serializable, Drawable { */ void setVisibilityLevel(Integer zoomLevelVisibility); - /** - * Returns semantic zoom level visibility. - * - * @return semantic zoom level visibility - */ - String getVisibilityLevel(); - /** * Returns the {@link Model} where BioEntity is located. * diff --git a/model/src/main/java/lcsb/mapviewer/model/map/Comment.java b/model/src/main/java/lcsb/mapviewer/model/map/Comment.java index d19627c469..8747682ed2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/Comment.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/Comment.java @@ -3,13 +3,7 @@ package lcsb.mapviewer.model.map; import java.awt.geom.Point2D; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; import org.hibernate.annotations.Type; @@ -97,6 +91,10 @@ public class Comment implements Serializable { * If feedback is located on the element, what is the identifier of the element. */ private Integer tableId; + /** + * Determines if comment should be visible on the map. + */ + private boolean pinned = false; /** * @return the tableId @@ -285,11 +283,6 @@ public class Comment implements Serializable { this.deleted = deleted; } - /** - * Determines if comment should be visible on the map. - */ - private boolean pinned = false; - /** * @return the pinned * @see #pinned @@ -316,7 +309,7 @@ public class Comment implements Serializable { public void setModel(Model model2) { this.model = model2.getModelData(); } - + public void setModel(ModelData model2) { this.model = model2; } @@ -339,20 +332,20 @@ public class Comment implements Serializable { } /** - * @param submodel - * the submodel to set + * @return the submodel * @see #submodel */ - public void setSubmodel(Model submodel) { - this.submodel = submodel.getModelData(); + public Model getSubmodel() { + return this.submodel.getModel(); } /** - * @return the submodel + * @param submodel + * the submodel to set * @see #submodel */ - public Model getSubmodel() { - return this.submodel.getModel(); + public void setSubmodel(Model submodel) { + this.submodel = submodel.getModelData(); } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/MiriamData.java b/model/src/main/java/lcsb/mapviewer/model/map/MiriamData.java index 1c5908da61..13c6aa49cd 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/MiriamData.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/MiriamData.java @@ -2,15 +2,11 @@ package lcsb.mapviewer.model.map; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -25,17 +21,15 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; @XmlRootElement public class MiriamData implements Comparable<MiriamData>, Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(MiriamData.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Unique database identifier. */ @@ -149,14 +143,6 @@ public class MiriamData implements Comparable<MiriamData>, Serializable { this(mt, resource, null); } - /** - * - * @return {@link #resource} - */ - public String getResource() { - return resource; - } - /** * @param identifier * string represents identifier. @@ -172,6 +158,14 @@ public class MiriamData implements Comparable<MiriamData>, Serializable { return identifier; } + /** + * + * @return {@link #resource} + */ + public String getResource() { + return resource; + } + /** * Sets new {@link #resource}. * @@ -186,6 +180,11 @@ public class MiriamData implements Comparable<MiriamData>, Serializable { } } + @Override + public int hashCode() { + return (dataType + resource).hashCode(); + } + @Override public boolean equals(Object aThat) { // check for self-comparison @@ -212,8 +211,14 @@ public class MiriamData implements Comparable<MiriamData>, Serializable { } @Override - public int hashCode() { - return (dataType + resource).hashCode(); + public String toString() { + String annotatorClass = annotator != null ? ":" + annotator.getName() : ""; + if (relationType != null) { + return "[" + relationType.getStringRepresentation() + "] " + dataType + ":" + resource + annotatorClass; + } else { + return "[UNKNOWN] " + dataType + ":" + resource + annotatorClass; + + } } @Override @@ -276,7 +281,7 @@ public class MiriamData implements Comparable<MiriamData>, Serializable { } /** - * + * * @return {@link #annotator} */ public Class<?> getAnnotator() { @@ -284,22 +289,11 @@ public class MiriamData implements Comparable<MiriamData>, Serializable { } /** - * + * * @param {@link * #annotator} */ public void setAnnotator(Class<?> annotator) { this.annotator = annotator; } - - @Override - public String toString() { - String annotatorClass = annotator != null ? ":" + annotator.getName() : ""; - if (relationType != null) { - return "[" + relationType.getStringRepresentation() + "] " + dataType + ":" + resource + annotatorClass; - } else { - return "[UNKNOWN] " + dataType + ":" + resource + annotatorClass; - - } - } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/MiriamRelationType.java b/model/src/main/java/lcsb/mapviewer/model/map/MiriamRelationType.java index 6f365b2be9..2938dd8334 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/MiriamRelationType.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/MiriamRelationType.java @@ -89,17 +89,9 @@ public enum MiriamRelationType { this.stringRepresentation = stringRepresentation; } - /** - * @return the stringRepresentation - * @see #stringRepresentation - */ - public String getStringRepresentation() { - return stringRepresentation; - } - /** * Returns {@link MiriamRelationType} associated with #stringRepresentation. - * + * * @param string * #stringRepresentation * @return {@link MiriamRelationType} for given #stringRepresentation @@ -112,4 +104,12 @@ public enum MiriamRelationType { } return null; } + + /** + * @return the stringRepresentation + * @see #stringRepresentation + */ + public String getStringRepresentation() { + return stringRepresentation; + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/MiriamType.java b/model/src/main/java/lcsb/mapviewer/model/map/MiriamType.java index 0ae6e05571..d9c44cd820 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/MiriamType.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/MiriamType.java @@ -9,13 +9,7 @@ import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Chemical; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; +import lcsb.mapviewer.model.map.species.*; /** * Type of known miriam annotation. @@ -813,33 +807,9 @@ public enum MiriamType { exampleIdentifier); } - /** - * - * @return {@link #commonName} - */ - public String getCommonName() { - return commonName; - } - - /** - * - * @return {@link #uris} - */ - public List<String> getUris() { - return uris; - } - - /** - * - * @return {@link #validClass} - */ - public List<Class<? extends BioEntity>> getValidClass() { - return validClass; - } - /** * Returns {@link MiriamType} associated with parameter uri address. - * + * * @param uri * uri to check * @return {@link MiriamType} for given uri @@ -856,33 +826,9 @@ public enum MiriamType { return null; } - /** - * @return the dbHomepage - * @see #dbHomepage - */ - public String getDbHomepage() { - return dbHomepage; - } - - /** - * @return the registryIdentifier - * @see #registryIdentifier - */ - public String getRegistryIdentifier() { - return registryIdentifier; - } - - /** - * @return the requiredClass - * @see #requiredClass - */ - public List<Class<? extends BioEntity>> getRequiredClass() { - return requiredClass; - } - /** * Returns {@link MiriamType} associated with {@link #commonName}. - * + * * @param string * {@link #commonName} * @return {@link MiriamType} for given name @@ -898,7 +844,7 @@ public enum MiriamType { /** * Transforms identifier into {@link MiriamData}. - * + * * @param generalIdentifier * identifier in the format NAME:IDENTIFIER. Where NAME is the name * from {@link MiriamType#commonName} and IDENTIFIER is resource @@ -923,7 +869,7 @@ public enum MiriamType { /** * Creates {@link MiriamData} from miriam uri. - * + * * @param miriamUri * miriam uri defining {@link MiriamData} * @return {@link MiriamData} from miriam uri @@ -966,6 +912,54 @@ public enum MiriamType { throw new InvalidArgumentException("Invalid miriam uri: " + miriamUri); } + /** + * + * @return {@link #commonName} + */ + public String getCommonName() { + return commonName; + } + + /** + * + * @return {@link #uris} + */ + public List<String> getUris() { + return uris; + } + + /** + * + * @return {@link #validClass} + */ + public List<Class<? extends BioEntity>> getValidClass() { + return validClass; + } + + /** + * @return the dbHomepage + * @see #dbHomepage + */ + public String getDbHomepage() { + return dbHomepage; + } + + /** + * @return the registryIdentifier + * @see #registryIdentifier + */ + public String getRegistryIdentifier() { + return registryIdentifier; + } + + /** + * @return the requiredClass + * @see #requiredClass + */ + public List<Class<? extends BioEntity>> getRequiredClass() { + return requiredClass; + } + public String getNamespace() { return namespace; } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImage.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImage.java index 72e0ee423d..f11a3ff3dc 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImage.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImage.java @@ -4,14 +4,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; +import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageComparator.java index 26d2a1a282..0f5e232dbb 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageComparator.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.model.map; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLink.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLink.java index d3daa9f373..6cad8e099f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLink.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLink.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.model.map; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.common.exception.NotImplementedException; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java index df31581e58..679b9dfb57 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -35,11 +36,6 @@ public class OverviewImageLinkComparator extends Comparator<OverviewImageLink> { this.epsilon = epsilon; } - @Override - protected Comparator<?> getParentComparator() { - return new OverviewLinkComparator(epsilon); - } - /** * Default constructor. */ @@ -47,6 +43,11 @@ public class OverviewImageLinkComparator extends Comparator<OverviewImageLink> { this(Configuration.EPSILON); } + @Override + protected Comparator<?> getParentComparator() { + return new OverviewLinkComparator(epsilon); + } + @Override protected int internalCompare(OverviewImageLink arg0, OverviewImageLink arg1) { int result = 0; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewLink.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewLink.java index 150de91e50..c73e2cdf41 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewLink.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewLink.java @@ -5,17 +5,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.ManyToOne; +import javax.persistence.*; /** * Abstract class representing link that connects {@link OverviewImage parent diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewLinkComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewLinkComparator.java index 675dde9e30..d4682f1764 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewLinkComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewLinkComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLink.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLink.java index ed236721b9..fa7e27a557 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLink.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLink.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.model.map; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.model.Model; @@ -131,6 +128,21 @@ public class OverviewModelLink extends OverviewLink { this.xCoord = xCoord; } + /** + * Sets {@link #xCoord} value. Value will be trimmed to {@link Integer}. + * + * @param value + * the xCoord to set + * @see #xCoord + */ + public void setxCoord(Double value) { + if (value == null) { + this.xCoord = null; + } else { + this.xCoord = value.intValue(); + } + } + /** * @return the yCoord * @see #yCoord @@ -148,21 +160,6 @@ public class OverviewModelLink extends OverviewLink { this.yCoord = yCoord; } - /** - * Sets {@link #xCoord} value. Value will be trimmed to {@link Integer}. - * - * @param value - * the xCoord to set - * @see #xCoord - */ - public void setxCoord(Double value) { - if (value == null) { - this.xCoord = null; - } else { - this.xCoord = value.intValue(); - } - } - /** * Sets {@link #yCoord} value. Value will be trimmed to {@link Integer}. * diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLinkComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLinkComparator.java index 1338b8a25f..8e64c1ec92 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLinkComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewModelLinkComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/SearchIndex.java b/model/src/main/java/lcsb/mapviewer/model/map/SearchIndex.java index d5270b88ad..dbe0faa688 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/SearchIndex.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/SearchIndex.java @@ -2,13 +2,10 @@ package lcsb.mapviewer.model.map; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Element; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/compartment/Compartment.java b/model/src/main/java/lcsb/mapviewer/model/map/compartment/Compartment.java index 7e023dda8b..73b490dae3 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/compartment/Compartment.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/compartment/Compartment.java @@ -1,23 +1,19 @@ package lcsb.mapviewer.model.map.compartment; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import java.util.HashSet; import java.util.Set; -import javax.persistence.DiscriminatorValue; +import javax.persistence.*; import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToMany; -import org.apache.logging.log4j.*; -import org.hibernate.annotations.Cascade; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.Type; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Species; @@ -306,14 +302,6 @@ public class Compartment extends Element { setNamePoint(new Point2D.Double(x, y)); } - /** - * @param elements - * the elements to set - */ - public void setElements(Set<Element> elements) { - this.elements = elements; - } - /** * @return the thickness * @see #thickness @@ -390,6 +378,14 @@ public class Compartment extends Element { return elements; } + /** + * @param elements + * the elements to set + */ + public void setElements(Set<Element> elements) { + this.elements = elements; + } + @Override public String getStringType() { return "Compartment"; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java index 7b4b97c17b..1aa57624bf 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java @@ -3,13 +3,12 @@ package lcsb.mapviewer.model.map.compartment; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.PointComparator; +import lcsb.mapviewer.common.comparator.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.ElementComparator; @@ -45,10 +44,6 @@ public class CompartmentComparator extends Comparator<Compartment> { this.epsilon = epsilon; } - protected Comparator<?> getParentComparator() { - return new ElementComparator(epsilon); - } - /** * Default constructor. */ @@ -56,6 +51,10 @@ public class CompartmentComparator extends Comparator<Compartment> { this(Configuration.EPSILON); } + protected Comparator<?> getParentComparator() { + return new ElementComparator(epsilon); + } + @Override protected int internalCompare(Compartment arg0, Compartment arg1) { ElementComparator elementComparator = new ElementComparator(epsilon); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/compartment/PathwayCompartment.java b/model/src/main/java/lcsb/mapviewer/model/map/compartment/PathwayCompartment.java index 2c1fe73421..dfd70ecebd 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/compartment/PathwayCompartment.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/compartment/PathwayCompartment.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.compartment; -import java.awt.Color; +import java.awt.*; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartment.java b/model/src/main/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartment.java index d6dd6c0614..36e73ed224 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartment.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartment.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.compartment; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.model.Model; @@ -53,26 +54,10 @@ public class RightSquareCompartment extends Compartment { setHeight(model.getHeight() * 2); } - /** - * Sets the CellDesigner point coordinates. In the implementation of - * BottomSquare it should define left border. - * - * @param y - * to be ignored - * @param x - * left border - * - */ - public void setPoint(String x, String y) { - // set left border - setX(x); - setWidth(getWidth() - getX()); - } - /** * Constructor that creates a compartment with the new shape and takes the * reference data from the compartment given as parameter. - * + * * @param original * original compartment where the data was kept */ @@ -82,7 +67,7 @@ public class RightSquareCompartment extends Compartment { /** * Default constructor. - * + * * @param elementId * identifier of the compartment */ @@ -90,6 +75,22 @@ public class RightSquareCompartment extends Compartment { setElementId(elementId); } + /** + * Sets the CellDesigner point coordinates. In the implementation of + * BottomSquare it should define left border. + * + * @param y + * to be ignored + * @param x + * left border + * + */ + public void setPoint(String x, String y) { + // set left border + setX(x); + setWidth(getWidth() - getX()); + } + @Override public RightSquareCompartment copy() { if (this.getClass() == RightSquareCompartment.class) { diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunction.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunction.java index 70116802e0..8be9199db2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunction.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunction.java @@ -4,20 +4,11 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OrderColumn; +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.model.ModelData; @@ -31,17 +22,15 @@ import lcsb.mapviewer.model.map.model.ModelData; @XmlRootElement public class SbmlFunction implements Serializable, SbmlArgument { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(SbmlFunction.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Unique database identifier. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionComparator.java index 877f176ac9..b2d2a4eed9 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.kinetics; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.comparator.StringComparator; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKinetics.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKinetics.java index 7e3ce2c1ac..1c96fd0929 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKinetics.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKinetics.java @@ -1,24 +1,13 @@ package lcsb.mapviewer.model.map.kinetics; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; +import java.util.*; + +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -34,17 +23,15 @@ import lcsb.mapviewer.model.map.species.Element; @XmlRootElement public class SbmlKinetics implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(SbmlKinetics.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - @Cascade({ CascadeType.ALL }) @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "kinetic_law_parameters", joinColumns = { diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsComparator.java index e7d68acfcd..158d4dd886 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.kinetics; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.comparator.SetComparator; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java index 11f1a54546..4fb498449d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java @@ -2,14 +2,11 @@ package lcsb.mapviewer.model.map.kinetics; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Representation of a single SBML parameter @@ -21,17 +18,15 @@ import org.apache.logging.log4j.*; @XmlRootElement public class SbmlParameter implements Serializable, SbmlArgument { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(SbmlParameter.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Unique database identifier. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnit.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnit.java index d9242e6c69..bb194bead6 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnit.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnit.java @@ -4,16 +4,11 @@ import java.io.Serializable; import java.util.HashSet; import java.util.Set; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -29,17 +24,15 @@ import lcsb.mapviewer.model.map.model.ModelData; @XmlRootElement public class SbmlUnit implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(SbmlUnit.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Unique database identifier. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparator.java index 2144c14b64..9643289589 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparator.java @@ -1,13 +1,14 @@ package lcsb.mapviewer.model.map.kinetics; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.comparator.SetComparator; import lcsb.mapviewer.common.comparator.StringComparator; public class SbmlUnitComparator extends Comparator<SbmlUnit> { - private static Logger logger =LogManager.getLogger(SbmlUnitComparator.class); + private static Logger logger = LogManager.getLogger(SbmlUnitComparator.class); public SbmlUnitComparator() { super(SbmlUnit.class); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactor.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactor.java index bea7bc652a..5683a2eb9a 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactor.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactor.java @@ -2,17 +2,11 @@ package lcsb.mapviewer.model.map.kinetics; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Representation of a single SBML unit factor. For example unit for velocity is @@ -29,17 +23,15 @@ import org.apache.logging.log4j.*; @XmlRootElement public class SbmlUnitTypeFactor implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(SbmlUnitTypeFactor.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Unique database identifier. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorComparator.java index c54e7745fe..3bdb448691 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorComparator.java @@ -1,9 +1,7 @@ package lcsb.mapviewer.model.map.kinetics; import lcsb.mapviewer.common.Comparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.EnumComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; +import lcsb.mapviewer.common.comparator.*; public class SbmlUnitTypeFactorComparator extends Comparator<SbmlUnitTypeFactor> { diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/BlockDiagram.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/BlockDiagram.java index c0dec6dc38..e20ad8a3d0 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/BlockDiagram.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/BlockDiagram.java @@ -2,18 +2,18 @@ package lcsb.mapviewer.model.map.layout; import java.io.Serializable; - /** - * This model element is used by cell designer but don't know how... We ignore it + * This model element is used by cell designer but don't know how... We ignore + * it * * @author Piotr Gawron * */ public abstract class BlockDiagram implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - + /** + * + */ + private static final long serialVersionUID = 1L; + } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/ColorSchema.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/ColorSchema.java index 0c16a03410..c74488a69d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/ColorSchema.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/ColorSchema.java @@ -1,12 +1,9 @@ package lcsb.mapviewer.model.map.layout; -import java.awt.Color; +import java.awt.*; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamData; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/DataOverlayImageLayer.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/DataOverlayImageLayer.java index cbba9f6cac..dd06b35e1d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/DataOverlayImageLayer.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/DataOverlayImageLayer.java @@ -3,14 +3,10 @@ package lcsb.mapviewer.model.map.layout; import java.io.Serializable; import java.util.Comparator; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; @@ -24,11 +20,6 @@ import lcsb.mapviewer.model.map.model.ModelData; */ @Entity public class DataOverlayImageLayer implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - public static final Comparator<? super DataOverlayImageLayer> ID_COMPARATOR = new Comparator<DataOverlayImageLayer>() { @Override @@ -36,7 +27,10 @@ public class DataOverlayImageLayer implements Serializable { return o1.getId() - o2.getId(); } }; - + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariation.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariation.java index d2142f1c26..1b0db4fd86 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariation.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariation.java @@ -1,14 +1,11 @@ package lcsb.mapviewer.model.map.layout; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.MiriamData; /** * Class describing single gene variation. @@ -18,17 +15,15 @@ import lcsb.mapviewer.model.map.MiriamData; */ public class GeneVariation implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(GeneVariation.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Variation position in the genome. */ @@ -115,6 +110,16 @@ public class GeneVariation implements Serializable { this.position = position; } + /** + * Sets {@link #position}. + * + * @param position + * new position value + */ + public void setPosition(int position) { + this.position = (long) position; + } + /** * @return the originalDna * @see #originalDna @@ -185,7 +190,7 @@ public class GeneVariation implements Serializable { /** * Creates copy of the object. - * + * * @return copy of the object */ public GeneVariation copy() { @@ -213,16 +218,6 @@ public class GeneVariation implements Serializable { this.contig = contig; } - /** - * Sets {@link #position}. - * - * @param position - * new position value - */ - public void setPosition(int position) { - this.position = (long) position; - } - /** * @return the allelFrequency * @see #allelFrequency diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchema.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchema.java index ead689d83e..192ae2684a 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchema.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchema.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; import lcsb.mapviewer.common.exception.NotImplementedException; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/Layout.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/Layout.java index af80343e57..54a13b49d3 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/Layout.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/Layout.java @@ -1,24 +1,12 @@ package lcsb.mapviewer.model.map.layout; import java.io.Serializable; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; - -import org.apache.logging.log4j.*; +import java.util.*; + +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -35,11 +23,6 @@ import lcsb.mapviewer.model.user.User; */ @Entity public class Layout implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - public static final Comparator<Layout> ID_COMPARATOR = new Comparator<Layout>() { @Override @@ -47,7 +30,6 @@ public class Layout implements Serializable { return o1.getId() - o2.getId(); } }; - public static final Comparator<? super Layout> ORDER_COMPARATOR = new Comparator<Layout>() { @Override @@ -55,7 +37,10 @@ public class Layout implements Serializable { return o1.getOrderIndex() - o2.getOrderIndex(); } }; - + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/LayoutStatus.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/LayoutStatus.java index 2f1a42efcd..d43eacbd2e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/LayoutStatus.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/LayoutStatus.java @@ -38,17 +38,9 @@ public enum LayoutStatus { */ private String commonName; - /** - * - * @return {@link #commonName} - */ - public String getCommonName() { - return commonName; - } - /** * Default constructor. - * + * * @param commonName * {@link #commonName} */ @@ -56,4 +48,12 @@ public enum LayoutStatus { this.commonName = commonName; } + /** + * + * @return {@link #commonName} + */ + public String getCommonName() { + return commonName; + } + } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenome.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenome.java index ea3a0fbeae..bd99b2eee5 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenome.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenome.java @@ -4,16 +4,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.OrderBy; +import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMapping.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMapping.java index c69adf638d..9f220014b5 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMapping.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMapping.java @@ -2,12 +2,7 @@ package lcsb.mapviewer.model.map.layout; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; /** * This object defines information about mapping genes to gene. This data is diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Glyph.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Glyph.java index 7aba408a26..181ebd848f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Glyph.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Glyph.java @@ -2,16 +2,10 @@ package lcsb.mapviewer.model.map.layout.graphics; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; - -import org.apache.logging.log4j.*; +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -69,7 +63,8 @@ public class Glyph implements Serializable { /** * Constructor that creates copy of the element. * - * @param original element to be copied + * @param original + * element to be copied */ public Glyph(Glyph original) { // we should reference to the same file diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Layer.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Layer.java index 0574b9248b..e49a892911 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Layer.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/Layer.java @@ -1,24 +1,12 @@ package lcsb.mapviewer.model.map.layout.graphics; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderColumn; - -import org.apache.logging.log4j.*; +import java.util.*; + +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -273,6 +261,17 @@ public class Layer implements Serializable { this.locked = locked; } + /** + * Sets locked param from the text input. + * + * @param param + * text representing true/false + * @see #locked + */ + public void setLocked(String param) { + locked = param.equalsIgnoreCase("TRUE"); + } + /** * @return the visible * @see #visible @@ -290,6 +289,17 @@ public class Layer implements Serializable { this.visible = visible; } + /** + * Sets visible param from the text input. + * + * @param param + * text representing true/false + * @see #visible + */ + public void setVisible(String param) { + visible = param.equalsIgnoreCase("TRUE"); + } + /** * @return the name * @see #name @@ -307,28 +317,6 @@ public class Layer implements Serializable { this.name = name; } - /** - * Sets locked param from the text input. - * - * @param param - * text representing true/false - * @see #locked - */ - public void setLocked(String param) { - locked = param.equalsIgnoreCase("TRUE"); - } - - /** - * Sets visible param from the text input. - * - * @param param - * text representing true/false - * @see #visible - */ - public void setVisible(String param) { - visible = param.equalsIgnoreCase("TRUE"); - } - /** * Adds text to the layer. * @@ -409,7 +397,8 @@ public class Layer implements Serializable { } public boolean isEmpty() { - return this.getOvals().size() == 0 && this.getRectangles().size() == 0 && this.getTexts().size() == 0 && this.getLines().size()==0; + return this.getOvals().size() == 0 && this.getRectangles().size() == 0 && this.getTexts().size() == 0 + && this.getLines().size() == 0; } public Set<Drawable> getDrawables() { diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java index 0c6ec1a1b2..fd61a1c447 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java @@ -1,12 +1,11 @@ package lcsb.mapviewer.model.map.layout.graphics; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.BooleanComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.StringComparator; +import lcsb.mapviewer.common.comparator.*; import lcsb.mapviewer.model.graphics.PolylineDataComparator; /** diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOval.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOval.java index c6378b539f..d9646a079a 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOval.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOval.java @@ -1,14 +1,12 @@ package lcsb.mapviewer.model.map.layout.graphics; -import java.awt.Color; +import java.awt.*; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -93,65 +91,9 @@ public class LayerOval implements Serializable, Drawable { this.height = layerOval.getHeight(); } - /** - * Set x from string containing double value. - * - * @param param - * x of the line in text format - */ - public void setX(String param) { - try { - x = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid x value: " + param, e); - } - } - - /** - * Set y from string containing double value. - * - * @param param - * y of the line in text format - */ - public void setY(String param) { - try { - y = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid y value: " + param, e); - } - } - - /** - * Set width from string containing double value. - * - * @param param - * width of the line in text format - */ - public void setWidth(String param) { - try { - width = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid width value: " + param, e); - } - } - - /** - * Set height from string containing double value. - * - * @param param - * height of the line in text format - */ - public void setHeight(String param) { - try { - height = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid height value: " + param, e); - } - } - /** * Prepares a copy of the object. - * + * * @return copy of LayerOval */ public LayerOval copy() { @@ -204,6 +146,20 @@ public class LayerOval implements Serializable, Drawable { return x; } + /** + * Set x from string containing double value. + * + * @param param + * x of the line in text format + */ + public void setX(String param) { + try { + x = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid x value: " + param, e); + } + } + /** * @param x * the x to set @@ -221,6 +177,20 @@ public class LayerOval implements Serializable, Drawable { return y; } + /** + * Set y from string containing double value. + * + * @param param + * y of the line in text format + */ + public void setY(String param) { + try { + y = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid y value: " + param, e); + } + } + /** * @param y * the y to set @@ -238,6 +208,20 @@ public class LayerOval implements Serializable, Drawable { return width; } + /** + * Set width from string containing double value. + * + * @param param + * width of the line in text format + */ + public void setWidth(String param) { + try { + width = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid width value: " + param, e); + } + } + /** * @param width * the width to set @@ -255,6 +239,20 @@ public class LayerOval implements Serializable, Drawable { return height; } + /** + * Set height from string containing double value. + * + * @param param + * height of the line in text format + */ + public void setHeight(String param) { + try { + height = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid height value: " + param, e); + } + } + /** * @param height * the height to set @@ -275,13 +273,13 @@ public class LayerOval implements Serializable, Drawable { } @Override - public double getSize() { - return width * height; + public String getElementId() { + return "x=" + x + ";y=" + y + "; w=" + width + ", h=" + height; } @Override - public String getElementId() { - return "x=" + x + ";y=" + y + "; w=" + width + ", h=" + height; + public double getSize() { + return width * height; } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparator.java index 28e0d8ca50..27d61e137c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparator.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.model.map.layout.graphics; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.ColorComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; +import lcsb.mapviewer.common.comparator.*; /** * Comparator of {@link LayerOval} class. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRect.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRect.java index 64c003fc34..32f3a36ed2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRect.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRect.java @@ -1,14 +1,12 @@ package lcsb.mapviewer.model.map.layout.graphics; -import java.awt.Color; +import java.awt.*; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -93,65 +91,9 @@ public class LayerRect implements Serializable, Drawable { height = layerRect.getHeight(); } - /** - * Set x from string containing double value. - * - * @param param - * x of the line in text format - */ - public void setX(String param) { - try { - x = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid x value: " + param, e); - } - } - - /** - * Set y from string containing double value. - * - * @param param - * y of the line in text format - */ - public void setY(String param) { - try { - y = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid y value: " + param, e); - } - } - - /** - * Set width from string containing double value. - * - * @param param - * width of the line in text format - */ - public void setWidth(String param) { - try { - width = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid width value: " + param, e); - } - } - - /** - * Set height from string containing double value. - * - * @param param - * height of the line in text format - */ - public void setHeight(String param) { - try { - height = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid height value: " + param, e); - } - } - /** * Prepares a copy of the object. - * + * * @return copy of LayerRect */ public LayerRect copy() { @@ -187,6 +129,20 @@ public class LayerRect implements Serializable, Drawable { return x; } + /** + * Set x from string containing double value. + * + * @param param + * x of the line in text format + */ + public void setX(String param) { + try { + x = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid x value: " + param, e); + } + } + /** * @param x * the x to set @@ -204,6 +160,20 @@ public class LayerRect implements Serializable, Drawable { return y; } + /** + * Set y from string containing double value. + * + * @param param + * y of the line in text format + */ + public void setY(String param) { + try { + y = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid y value: " + param, e); + } + } + /** * @param y * the y to set @@ -221,6 +191,20 @@ public class LayerRect implements Serializable, Drawable { return width; } + /** + * Set width from string containing double value. + * + * @param param + * width of the line in text format + */ + public void setWidth(String param) { + try { + width = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid width value: " + param, e); + } + } + /** * @param width * the width to set @@ -238,6 +222,20 @@ public class LayerRect implements Serializable, Drawable { return height; } + /** + * Set height from string containing double value. + * + * @param param + * height of the line in text format + */ + public void setHeight(String param) { + try { + height = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid height value: " + param, e); + } + } + /** * @param height * the height to set @@ -257,14 +255,14 @@ public class LayerRect implements Serializable, Drawable { this.z = z; } - @Override - public double getSize() { - return width * height; - } - @Override public String getElementId() { return "x=" + x + ";y=" + y + "; w=" + width + ", h=" + height; } - + + @Override + public double getSize() { + return width * height; + } + } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparator.java index 90c3453f38..7ec13f41a9 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparator.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.model.map.layout.graphics; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.ColorComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; +import lcsb.mapviewer.common.comparator.*; /** * Compparator of {@link LayerRect} class. @@ -68,7 +66,6 @@ public class LayerRectComparator extends Comparator<LayerRect> { return integerComparator.compare(arg0.getZ(), arg1.getZ()); } - return 0; } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerText.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerText.java index 72e9575eba..fc37eeeee9 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerText.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerText.java @@ -1,17 +1,13 @@ package lcsb.mapviewer.model.map.layout.graphics; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Rectangle2D; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -143,80 +139,9 @@ public class LayerText implements Serializable, Drawable { } } - /** - * Set x from string containing double value. - * - * @param param - * x of the line in text format - */ - public void setX(String param) { - try { - x = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid x value: " + param, e); - } - } - - /** - * Set y from string containing double value. - * - * @param param - * y of the line in text format - */ - public void setY(String param) { - try { - y = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid y value: " + param, e); - } - } - - /** - * Set width from string containing double value. - * - * @param param - * width of the line in text format - */ - public void setWidth(String param) { - try { - width = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid width value: " + param, e); - } - } - - /** - * Set height from string containing double value. - * - * @param param - * height of the line in text format - */ - public void setHeight(String param) { - try { - height = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid height value: " + param, e); - } - } - - /** - * Set font size from string containing double value. - * - * @param param - * font size of the line in text format - */ - public void setFontSize(String param) { - try { - fontSize = Double.parseDouble(param); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid fontSize value: " + param, e); - } - - } - /** * Prepares a copy of the object. - * + * * @return copy of LayerText */ public LayerText copy() { @@ -252,6 +177,20 @@ public class LayerText implements Serializable, Drawable { return x; } + /** + * Set x from string containing double value. + * + * @param param + * x of the line in text format + */ + public void setX(String param) { + try { + x = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid x value: " + param, e); + } + } + /** * @param x * the x to set @@ -269,6 +208,20 @@ public class LayerText implements Serializable, Drawable { return y; } + /** + * Set y from string containing double value. + * + * @param param + * y of the line in text format + */ + public void setY(String param) { + try { + y = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid y value: " + param, e); + } + } + /** * @param y * the y to set @@ -286,6 +239,20 @@ public class LayerText implements Serializable, Drawable { return width; } + /** + * Set width from string containing double value. + * + * @param param + * width of the line in text format + */ + public void setWidth(String param) { + try { + width = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid width value: " + param, e); + } + } + /** * @param width * the width to set @@ -303,6 +270,20 @@ public class LayerText implements Serializable, Drawable { return height; } + /** + * Set height from string containing double value. + * + * @param param + * height of the line in text format + */ + public void setHeight(String param) { + try { + height = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid height value: " + param, e); + } + } + /** * @param height * the height to set @@ -337,6 +318,21 @@ public class LayerText implements Serializable, Drawable { return fontSize; } + /** + * Set font size from string containing double value. + * + * @param param + * font size of the line in text format + */ + public void setFontSize(String param) { + try { + fontSize = Double.parseDouble(param); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid fontSize value: " + param, e); + } + + } + /** * @param fontSize * the fontSize to set @@ -379,13 +375,13 @@ public class LayerText implements Serializable, Drawable { } @Override - public double getSize() { - return width * height; + public String getElementId() { + return "x=" + x + ";y=" + y + "; w=" + width + ", h=" + height; } @Override - public String getElementId() { - return "x=" + x + ";y=" + y + "; w=" + width + ", h=" + height; + public double getSize() { + return width * height; } public Glyph getGlyph() { diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparator.java index 385f5679fa..e656f63c47 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparator.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.model.map.layout.graphics; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.ColorComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.StringComparator; +import lcsb.mapviewer.common.comparator.*; /** * Comparator of {@link LayerText} class. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/package-info.java index 97326a877f..4002611446 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/package-info.java @@ -3,4 +3,3 @@ * lines, rectangles, etc.). */ package lcsb.mapviewer.model.map.layout.graphics; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/package-info.java index 2d03a51ab7..94a5b8a726 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/package-info.java @@ -3,4 +3,3 @@ * of the map. */ package lcsb.mapviewer.model.map.layout; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/Author.java b/model/src/main/java/lcsb/mapviewer/model/map/model/Author.java index 54f5052ba6..9f0372bbb6 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/Author.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/Author.java @@ -2,13 +2,11 @@ package lcsb.mapviewer.model.map.model; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Class representing author object. @@ -20,17 +18,15 @@ import org.apache.logging.log4j.*; @XmlRootElement public class Author implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(Author.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Unique database identifier. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/AuthorComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/model/AuthorComparator.java index 5ea4038644..2c58a0c49f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/AuthorComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/AuthorComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.comparator.StringComparator; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnection.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnection.java index 2b9d98a088..455de1fe4a 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnection.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnection.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.model.map.model; import java.io.Serializable; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Element; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparator.java index c56a1ea9b2..567d385633 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java b/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java index 05bfbe7f99..2a46333d64 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/Model.java @@ -1,27 +1,16 @@ package lcsb.mapviewer.model.map.model; -import java.util.Calendar; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.Set; +import java.util.*; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.Drawable; -import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.kinetics.SbmlArgument; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.layout.BlockDiagram; import lcsb.mapviewer.model.map.layout.ElementGroup; import lcsb.mapviewer.model.map.layout.graphics.Layer; 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.model.map.species.*; /** * This interface defines functionality that the model container class should @@ -64,46 +53,67 @@ public interface Model { void setWidth(double width); /** - * + * Sets model width. + * + * @param text + * new model width + */ + void setWidth(String text); + + /** + * + * @param width + * new {@link ModelData#width} + */ + void setWidth(int width); + + /** + * * @return model height */ double getHeight(); /** * Sets model height. - * + * * @param height * new model height */ void setHeight(double height); - /** - * Sets model width. - * - * @param text - * new model width - */ - void setWidth(String text); - /** * Sets model height. - * + * * @param text * new model height */ void setHeight(String text); + /** + * + * @param height + * new {@link ModelData#height} + */ + void setHeight(int height); + /** * Returns set of all elements. - * + * * @return set of all elements */ Set<Element> getElements(); + /** + * + * @param elements + * new {@link ModelData#elements} collection + */ + void setElements(Set<Element> elements); + /** * Returns element with the given element identifier ({@link Element#elementId} * ). - * + * * @param idElement * element identifier * @param <T> @@ -114,7 +124,7 @@ public interface Model { /** * Adds reaction to the model. - * + * * @param reaction * reaction to add */ @@ -122,7 +132,7 @@ public interface Model { /** * Returns set of reactions. - * + * * @return set of reaction in the model */ Set<Reaction> getReactions(); @@ -134,43 +144,43 @@ public interface Model { /** * Adds layer to the model. - * + * * @param layer * object to add */ void addLayer(Layer layer); /** - * + * * @return set of layers */ Set<Layer> getLayers(); /** * Adds list of elements into model. - * + * * @param elements * list of elements */ void addElements(Collection<? extends Element> elements); + /** + * + * @return short description of the model + */ + String getNotes(); + /** * Sets new short description of the model. - * + * * @param notes * new short description */ void setNotes(String notes); - /** - * - * @return short description of the model - */ - String getNotes(); - /** * Returns reaction with the id given in the parameter. - * + * * @param idReaction * reaction identifier ({@link Reaction#idReaction}) * @return reaction with the id given in the parameter @@ -179,7 +189,7 @@ public interface Model { /** * Adds set of layers to the model. - * + * * @param layers * object to add */ @@ -187,7 +197,7 @@ public interface Model { /** * Adds {@link ElementGroup} to the model. - * + * * @param elementGroup * object to add */ @@ -195,12 +205,18 @@ public interface Model { /** * Adds {@link BlockDiagram} to the model. - * + * * @param blockDiagram * object to add */ void addBlockDiagream(BlockDiagram blockDiagram); + /** + * @return the idModel + * @see Model#idModel + */ + String getIdModel(); + /** * @param idModel * the idModel to set @@ -209,10 +225,10 @@ public interface Model { void setIdModel(String idModel); /** - * @return the idModel - * @see Model#idModel + * @return the tileSize + * @see ModelData#tileSize */ - String getIdModel(); + int getTileSize(); /** * @param tileSize @@ -222,10 +238,10 @@ public interface Model { void setTileSize(int tileSize); /** - * @return the tileSize - * @see ModelData#tileSize + * @return the zoomLevels + * @see ModelData#zoomLevels */ - int getTileSize(); + int getZoomLevels(); /** * @param zoomLevels @@ -234,15 +250,9 @@ public interface Model { */ void setZoomLevels(int zoomLevels); - /** - * @return the zoomLevels - * @see ModelData#zoomLevels - */ - int getZoomLevels(); - /** * Removes reaction from model. - * + * * @param reaction * reaction to remove */ @@ -250,7 +260,7 @@ public interface Model { /** * Removes {@link Element} from the model. - * + * * @param element * element to remove */ @@ -258,28 +268,28 @@ public interface Model { /** * Returns collection of all {@link Species} excluding {@link Complex}. - * + * * @return collection of all {@link Species} excluding {@link Complex}. */ Collection<Species> getNotComplexSpeciesList(); /** * Returns list of all {@link Species} in the model. - * + * * @return list of all {@link Species} in the model */ List<Species> getSpeciesList(); /** * Returns collection of {@link Complex}. - * + * * @return collection of {@link Complex} */ Collection<Complex> getComplexList(); /** * Adds reactions to model. - * + * * @param reactions2 * list of reaction to add */ @@ -287,7 +297,7 @@ public interface Model { /** * Returns list of elements annotated by the {@link MiriamData}. - * + * * @param miriamData * {@link MiriamData} * @return list of elements @@ -296,30 +306,16 @@ public interface Model { /** * Returns list of elements with given name. - * + * * @param name * name of the element * @return list of elements with given name */ List<Element> getElementsByName(String name); - /** - * - * @param height - * new {@link ModelData#height} - */ - void setHeight(int height); - - /** - * - * @param width - * new {@link ModelData#width} - */ - void setWidth(int width); - /** * Returns {@link Element} for given database identifier. - * + * * @param dbId * element database identifier ({@link Element#id}) * @return {@link Element} for a given id @@ -328,7 +324,7 @@ public interface Model { /** * Returns {@link Reaction} for given database identifier. - * + * * @param dbId * reaction database identifier ({@link Reaction#id}) * @return {@link Reaction} for a given id @@ -337,25 +333,18 @@ public interface Model { /** * Returns sorted by size list of compartments. - * + * * @return list of compartment sorted by size */ List<Compartment> getSortedCompartments(); /** * Returns list of elements sorted by the size. - * + * * @return list of elements sorted by the size */ List<Element> getElementsSortedBySize(); - /** - * - * @param project - * new {@link ModelData#project} - */ - void setProject(Project project); - /** * * @return {@link ModelData#project} @@ -363,11 +352,11 @@ public interface Model { Project getProject(); /** - * - * @param elements - * new {@link ModelData#elements} collection + * + * @param project + * new {@link ModelData#project} */ - void setElements(Set<Element> elements); + void setProject(Project project); /** * @return the modelData @@ -380,9 +369,17 @@ public interface Model { */ Integer getId(); + /** + * Sets database identifier of the model. + * + * @param id + * database identifier + */ + void setId(int id); + /** * Adds submodel connection. - * + * * @param submodel * submodel to add */ @@ -390,21 +387,21 @@ public interface Model { /** * Returns set of submodel connections. - * + * * @return collection of submodels */ Collection<ModelSubmodelConnection> getSubmodelConnections(); /** * Returns name of the model. - * + * * @return name of the model */ String getName(); /** * Sets name of the model. - * + * * @param name * name of the model */ @@ -413,7 +410,7 @@ public interface Model { /** * Returns {@link Model submodel} by the {@link ModelData#id database * identifier} given in the parameter. - * + * * @param idObject * the {@link ModelData#id database identifier} that identifies * submodel @@ -425,14 +422,14 @@ public interface Model { /** * Returns set of connections that point to this model. Be very carefoul with * using this function as the implementation forces lazy loading of the maps. - * + * * @return set of connections that point to this model */ Collection<SubmodelConnection> getParentModels(); /** * Returns connection to a submodel identified by connection name. - * + * * @param name * name of the connection * @return connection to a submodel identified by connection name @@ -441,7 +438,7 @@ public interface Model { /** * Returns connection to a submodel identified by connection identifier. - * + * * @param id * id of the connection * @return connection to a submodel identified by connection identifier @@ -450,7 +447,7 @@ public interface Model { /** * Returns submodel identified by submodel identifier. - * + * * @param identifier * identifier of the model * @return submodel identified by identifier @@ -459,7 +456,7 @@ public interface Model { /** * Returns collection of {@link Model submodels}. - * + * * @return collection of {@link Model submodels} */ Collection<Model> getSubmodels(); @@ -467,7 +464,7 @@ public interface Model { /** * Returns {@link Model submodel} identified by the {@link ModelData#name model * name}. It returns this 'parent' object when the names matches. - * + * * @param name * name of the submodel that should be returned * @return {@link Model submodel} identified by the {@link ModelData#name model @@ -475,14 +472,6 @@ public interface Model { */ Model getSubmodelByName(String name); - /** - * Sets database identifier of the model. - * - * @param id - * database identifier - */ - void setId(int id); - /** * Return list of all {@link BioEntity} in the map. This includes all * {@link Reaction reactions} and {@link Element elements}. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelComparator.java index 4fdff6e9ab..2055171f78 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelComparator.java @@ -1,29 +1,16 @@ package lcsb.mapviewer.model.map.model; -import java.util.Calendar; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.CalendarComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.ListComparator; -import lcsb.mapviewer.common.comparator.SetComparator; -import lcsb.mapviewer.common.comparator.StringComparator; +import lcsb.mapviewer.common.comparator.*; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamDataComparator; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlFunctionComparator; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; -import lcsb.mapviewer.model.map.kinetics.SbmlParameterComparator; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; -import lcsb.mapviewer.model.map.kinetics.SbmlUnitComparator; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.layout.graphics.Layer; import lcsb.mapviewer.model.map.layout.graphics.LayerComparator; import lcsb.mapviewer.model.map.reaction.Reaction; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelData.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelData.java index 0e07da18b9..aba2d8751c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelData.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelData.java @@ -1,40 +1,20 @@ package lcsb.mapviewer.model.map.model; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderColumn; -import javax.persistence.Transient; +import java.util.*; + +import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.layout.BlockDiagram; import lcsb.mapviewer.model.map.layout.ElementGroup; import lcsb.mapviewer.model.map.layout.graphics.Layer; @@ -311,16 +291,7 @@ public class ModelData implements Serializable { } /** - * - * @param elements - * new {@link #elements} collection - */ - public void setElements(Set<Element> elements) { - this.elements = elements; - } - - /** - * + * * @return {@link #project} */ public Project getProject() { @@ -328,7 +299,7 @@ public class ModelData implements Serializable { } /** - * + * * @param project * new {@link #project} */ @@ -336,27 +307,9 @@ public class ModelData implements Serializable { this.project = project; } - /** - * - * @param width - * new {@link #width} - */ - public void setWidth(int width) { - setWidth(Double.valueOf(width)); - } - - /** - * - * @param height - * new {@link #height} - */ - public void setHeight(int height) { - setHeight(Double.valueOf(height)); - } - /** * Adds reactions to model. - * + * * @param reactions2 * list of reaction to add */ @@ -368,7 +321,7 @@ public class ModelData implements Serializable { /** * Adds collection of {@link Layer layers} to the model data. - * + * * @param layers * objets to add */ @@ -380,7 +333,7 @@ public class ModelData implements Serializable { /** * Adds {@link ElementGroup} to the model data. - * + * * @param elementGroup * object to add */ @@ -390,7 +343,7 @@ public class ModelData implements Serializable { /** * Adds {@link BlockDiagram} to the model data. - * + * * @param blockDiagram * object to add */ @@ -400,7 +353,7 @@ public class ModelData implements Serializable { /** * Removes {@link Element} from the model. - * + * * @param element * element to remove */ @@ -419,7 +372,7 @@ public class ModelData implements Serializable { /** * Removes reaction from model. - * + * * @param reaction * reaction to remove */ @@ -512,6 +465,15 @@ public class ModelData implements Serializable { return elements; } + /** + * + * @param elements + * new {@link #elements} collection + */ + public void setElements(Set<Element> elements) { + this.elements = elements; + } + /** * @return the layers * @see #layers @@ -554,6 +516,15 @@ public class ModelData implements Serializable { return width; } + /** + * + * @param width + * new {@link #width} + */ + public void setWidth(int width) { + setWidth(Double.valueOf(width)); + } + /** * @param width * the width to set @@ -571,6 +542,15 @@ public class ModelData implements Serializable { return height; } + /** + * + * @param height + * new {@link #height} + */ + public void setHeight(int height) { + setHeight(Double.valueOf(height)); + } + /** * @param height * the height to set diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java index 0d6a451085..8592b4abe5 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelFullIndexed.java @@ -1,33 +1,20 @@ package lcsb.mapviewer.model.map.model; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.logging.log4j.*; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.Drawable; -import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; -import lcsb.mapviewer.model.map.kinetics.SbmlUnit; +import lcsb.mapviewer.model.map.kinetics.*; import lcsb.mapviewer.model.map.layout.BlockDiagram; import lcsb.mapviewer.model.map.layout.ElementGroup; import lcsb.mapviewer.model.map.layout.graphics.Layer; 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.model.map.species.*; /** * This class implements {@link Model} interface. It's is very simple @@ -131,6 +118,16 @@ public class ModelFullIndexed implements Model { modelData.setWidth(width); } + @Override + public void setWidth(String text) { + modelData.setWidth(Double.parseDouble(text)); + } + + @Override + public void setWidth(int width) { + setWidth(Double.valueOf(width)); + } + @Override public double getHeight() { return modelData.getHeight(); @@ -142,13 +139,13 @@ public class ModelFullIndexed implements Model { } @Override - public void setWidth(String text) { - modelData.setWidth(Double.parseDouble(text)); + public void setHeight(String text) { + modelData.setHeight(Double.parseDouble(text)); } @Override - public void setHeight(String text) { - modelData.setHeight(Double.parseDouble(text)); + public void setHeight(int height) { + setHeight(Double.valueOf(height)); } @Override @@ -156,6 +153,11 @@ public class ModelFullIndexed implements Model { return modelData.getElements(); } + @Override + public void setElements(Set<Element> elements) { + this.modelData.setElements(elements); + } + @SuppressWarnings("unchecked") @Override public <T extends Element> T getElementByElementId(String elementId) { @@ -205,6 +207,11 @@ public class ModelFullIndexed implements Model { } } + @Override + public String getNotes() { + return modelData.getNotes(); + } + @Override public void setNotes(String notes) { if (notes != null && notes.contains("<html")) { @@ -214,111 +221,100 @@ public class ModelFullIndexed implements Model { } @Override - public String getNotes() { - return modelData.getNotes(); + public Reaction getReactionByReactionId(String idReaction) { + return reactionByReactionId.get(idReaction); } @Override - public void setElements(Set<Element> elements) { - this.modelData.setElements(elements); + public void addLayers(Collection<Layer> layers) { + for (Layer layer : layers) { + addLayer(layer); + } } @Override - public Reaction getReactionByReactionId(String idReaction) { - return reactionByReactionId.get(idReaction); + public void addElementGroup(ElementGroup elementGroup) { + modelData.addElementGroup(elementGroup); } @Override - public Project getProject() { - return modelData.getProject(); + public void addBlockDiagream(BlockDiagram blockDiagram) { + modelData.addBlockDiagream(blockDiagram); } @Override - public void setProject(Project project) { - modelData.setProject(project); + public String getIdModel() { + return modelData.getIdModel(); } @Override - public List<Element> getElementsSortedBySize() { - List<Element> sortedElements = new ArrayList<>(); - sortedElements.addAll(getElements()); - Collections.sort(sortedElements, Element.SIZE_COMPARATOR); - return sortedElements; + public void setIdModel(String idModel) { + this.modelData.setIdModel(idModel); } @Override - public List<Compartment> getSortedCompartments() { - List<Compartment> result = getCompartments(); - Collections.sort(result, Element.SIZE_COMPARATOR); - return result; + public int getTileSize() { + return modelData.getTileSize(); } @Override - public Reaction getReactionByDbId(Integer dbId) { - return reactionByDbId.get(dbId); + public void setTileSize(int tileSize) { + this.modelData.setTileSize(tileSize); } - @SuppressWarnings("unchecked") @Override - public <T extends Element> T getElementByDbId(Integer dbId) { - return (T) elementByDbId.get(dbId); + public int getZoomLevels() { + return modelData.getZoomLevels(); } @Override - public void setWidth(int width) { - setWidth(Double.valueOf(width)); + public void setZoomLevels(int zoomLevels) { + this.modelData.setZoomLevels(zoomLevels); } @Override - public void setHeight(int height) { - setHeight(Double.valueOf(height)); + public void removeReaction(Reaction reaction) { + modelData.removeReaction(reaction); + reactionByReactionId.remove(reaction.getIdReaction()); + reactionByDbId.remove(reaction.getId()); } @Override - public Set<BioEntity> getElementsByAnnotation(MiriamData miriamData) { - Set<BioEntity> result = new HashSet<>(); - for (Element element : getElements()) { - for (MiriamData md : element.getMiriamData()) { - if (md.equals(miriamData)) { - result.add(element); - } - } - } + public void removeElement(Element element) { + modelData.removeElement(element); + elementByElementId.remove(element.getElementId()); + elementByDbId.remove(element.getId()); - for (Reaction element : getReactions()) { - for (MiriamData md : element.getMiriamData()) { - if (md.equals(miriamData)) { - result.add(element); - } - } + if (element.getCompartment() != null) { + Compartment ca = element.getCompartment(); + ca.removeElement(element); } - return result; - } - - @Override - public void addReactions(List<Reaction> reactions2) { - for (Reaction reaction : reactions2) { - addReaction(reaction); + if (element instanceof Species) { + Species al = (Species) element; + if (al.getComplex() != null) { + Complex ca = ((Species) element).getComplex(); + ca.removeElement(al); + } } } @Override - public Collection<Complex> getComplexList() { - List<Complex> result = new ArrayList<>(); + public Collection<Species> getNotComplexSpeciesList() { + List<Species> result = new ArrayList<>(); for (Element element : modelData.getElements()) { - if (element instanceof Complex) { - result.add((Complex) element); + if (element instanceof Species && !(element instanceof Complex)) { + result.add((Species) element); } } return result; } @Override - public Collection<Species> getNotComplexSpeciesList() { + public List<Species> getSpeciesList() { List<Species> result = new ArrayList<>(); for (Element element : modelData.getElements()) { - if (element instanceof Species && !(element instanceof Complex)) { + if (element instanceof Species) { result.add((Species) element); } } @@ -326,77 +322,90 @@ public class ModelFullIndexed implements Model { } @Override - public void addLayers(Collection<Layer> layers) { - for (Layer layer : layers) { - addLayer(layer); + public Collection<Complex> getComplexList() { + List<Complex> result = new ArrayList<>(); + for (Element element : modelData.getElements()) { + if (element instanceof Complex) { + result.add((Complex) element); + } } + return result; } @Override - public void addElementGroup(ElementGroup elementGroup) { - modelData.addElementGroup(elementGroup); - } - - @Override - public void addBlockDiagream(BlockDiagram blockDiagram) { - modelData.addBlockDiagream(blockDiagram); + public void addReactions(List<Reaction> reactions2) { + for (Reaction reaction : reactions2) { + addReaction(reaction); + } } @Override - public void removeElement(Element element) { - modelData.removeElement(element); - elementByElementId.remove(element.getElementId()); - elementByDbId.remove(element.getId()); - - if (element.getCompartment() != null) { - Compartment ca = element.getCompartment(); - ca.removeElement(element); + public Set<BioEntity> getElementsByAnnotation(MiriamData miriamData) { + Set<BioEntity> result = new HashSet<>(); + for (Element element : getElements()) { + for (MiriamData md : element.getMiriamData()) { + if (md.equals(miriamData)) { + result.add(element); + } + } } - if (element instanceof Species) { - Species al = (Species) element; - if (al.getComplex() != null) { - Complex ca = ((Species) element).getComplex(); - ca.removeElement(al); + for (Reaction element : getReactions()) { + for (MiriamData md : element.getMiriamData()) { + if (md.equals(miriamData)) { + result.add(element); + } } } + + return result; } @Override - public void removeReaction(Reaction reaction) { - modelData.removeReaction(reaction); - reactionByReactionId.remove(reaction.getIdReaction()); - reactionByDbId.remove(reaction.getId()); + public List<Element> getElementsByName(String name) { + List<Element> result = new ArrayList<>(); + for (Element element : getElements()) { + if (element.getName().equalsIgnoreCase(name)) { + result.add(element); + } + } + return result; } + @SuppressWarnings("unchecked") @Override - public int getZoomLevels() { - return modelData.getZoomLevels(); + public <T extends Element> T getElementByDbId(Integer dbId) { + return (T) elementByDbId.get(dbId); } @Override - public void setZoomLevels(int zoomLevels) { - this.modelData.setZoomLevels(zoomLevels); + public Reaction getReactionByDbId(Integer dbId) { + return reactionByDbId.get(dbId); } @Override - public int getTileSize() { - return modelData.getTileSize(); + public List<Compartment> getSortedCompartments() { + List<Compartment> result = getCompartments(); + Collections.sort(result, Element.SIZE_COMPARATOR); + return result; } @Override - public void setTileSize(int tileSize) { - this.modelData.setTileSize(tileSize); + public List<Element> getElementsSortedBySize() { + List<Element> sortedElements = new ArrayList<>(); + sortedElements.addAll(getElements()); + Collections.sort(sortedElements, Element.SIZE_COMPARATOR); + return sortedElements; } @Override - public String getIdModel() { - return modelData.getIdModel(); + public Project getProject() { + return modelData.getProject(); } @Override - public void setIdModel(String idModel) { - this.modelData.setIdModel(idModel); + public void setProject(Project project) { + modelData.setProject(project); } @Override @@ -409,6 +418,11 @@ public class ModelFullIndexed implements Model { return modelData.getId(); } + @Override + public void setId(int id) { + modelData.setId(id); + } + @Override public void addSubmodelConnection(ModelSubmodelConnection submodel) { modelData.addSubmodel(submodel); @@ -508,11 +522,6 @@ public class ModelFullIndexed implements Model { return null; } - @Override - public void setId(int id) { - modelData.setId(id); - } - @Override public List<BioEntity> getBioEntities() { List<BioEntity> result = new ArrayList<>(); @@ -521,28 +530,6 @@ public class ModelFullIndexed implements Model { return result; } - @Override - public List<Element> getElementsByName(String name) { - List<Element> result = new ArrayList<>(); - for (Element element : getElements()) { - if (element.getName().equalsIgnoreCase(name)) { - result.add(element); - } - } - return result; - } - - @Override - public List<Species> getSpeciesList() { - List<Species> result = new ArrayList<>(); - for (Element element : modelData.getElements()) { - if (element instanceof Species) { - result.add((Species) element); - } - } - return result; - } - @Override public Double getDefaultCenterX() { return modelData.getDefaultCenterX(); @@ -675,6 +662,18 @@ public class ModelFullIndexed implements Model { } } + @Override + public void addAuthor(Author author) { + modelData.addAuthor(author); + } + + @Override + public void addAuthors(Collection<Author> authors) { + for (Author author : authors) { + addAuthor(author); + } + } + @Override public List<Author> getAuthors() { return modelData.getAuthors(); @@ -700,18 +699,6 @@ public class ModelFullIndexed implements Model { return modelData.getModificationDates(); } - @Override - public void addAuthor(Author author) { - modelData.addAuthor(author); - } - - @Override - public void addAuthors(Collection<Author> authors) { - for (Author author : authors) { - addAuthor(author); - } - } - @Override public void addModificationDates(Collection<Calendar> modificationDates) { for (Calendar calendar : modificationDates) { @@ -723,7 +710,7 @@ public class ModelFullIndexed implements Model { public Set<Drawable> getDrawables() { Set<Drawable> result = new HashSet<>(); result.addAll(getBioEntities()); - for (Layer layer: getLayers()) { + for (Layer layer : getLayers()) { result.addAll(layer.getDrawables()); } return result; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnection.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnection.java index 2638ad9a5a..db9df4c50f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnection.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnection.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.model.map.model; import java.util.Comparator; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -20,11 +17,6 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("MODEL_SUBMODEL_LINK") public class ModelSubmodelConnection extends SubmodelConnection { - /** - * - */ - private static final long serialVersionUID = 1L; - public static final Comparator<? super ModelSubmodelConnection> ID_COMPARATOR = new Comparator<ModelSubmodelConnection>() { @Override @@ -32,7 +24,10 @@ public class ModelSubmodelConnection extends SubmodelConnection { return o1.getId() - o2.getId(); } }; - + /** + * + */ + private static final long serialVersionUID = 1L; /** * Super (parent) model. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparator.java index 2d7849907c..0ee6af2da9 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnection.java b/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnection.java index 9cf64cd9ac..3db3ce897a 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnection.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnection.java @@ -2,21 +2,10 @@ package lcsb.mapviewer.model.map.model; import java.io.Serializable; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.ManyToOne; - -import org.apache.logging.log4j.*; +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * This abstract class defines connection between models. It points to submodel @@ -171,6 +160,17 @@ public abstract class SubmodelConnection implements Serializable { submodel.getParentModels().add(this); } + /** + * Sets submodel to which this connection points to. + * + * @param submodel + * submodel to set. + * @see #submodel + */ + public void setSubmodel(Model submodel) { + setSubmodel(submodel.getModelData()); + } + /** * @return the id * @see #id @@ -188,17 +188,6 @@ public abstract class SubmodelConnection implements Serializable { this.id = id; } - /** - * Sets submodel to which this connection points to. - * - * @param submodel - * submodel to set. - * @see #submodel - */ - public void setSubmodel(Model submodel) { - setSubmodel(submodel.getModelData()); - } - /** * Creates a copy of this object. * diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparator.java index 947b83716e..155a588f5c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/model/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/model/package-info.java index 7647ab8578..ed55e999d6 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/model/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/model/package-info.java @@ -2,4 +2,3 @@ * Contains map structures and structures used for connecting maps and submaps. */ package lcsb.mapviewer.model.map.model; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/package-info.java index b5520bf31f..cf76bdb9d7 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/package-info.java @@ -1,6 +1,5 @@ /** - * Provides data structure for - * {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction} modifier. + * Provides data structure for {@link lcsb.mapviewer.model.map.reaction.Reaction + * Reaction} modifier. */ package lcsb.mapviewer.model.map.modifier; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/package-info.java index 902c25f151..33f7cc81cc 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/package-info.java @@ -4,4 +4,3 @@ * class represents fields or elements of the model (or model elements). */ package lcsb.mapviewer.model.map; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNode.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNode.java index 9edfb40959..6c9b5e8a94 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNode.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNode.java @@ -2,19 +2,7 @@ package lcsb.mapviewer.model.map.reaction; import java.io.Serializable; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.ManyToOne; -import javax.persistence.OneToOne; -import javax.persistence.Table; +import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java index 97077d96c5..c1c14cd4dc 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AndOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AndOperator.java index 53856fec5d..fe85562262 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AndOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AndOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -17,51 +18,51 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("AND_OPERATOR_NODE") public class AndOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(AndOperator.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(AndOperator.class); - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public AndOperator(AndOperator operator) { - super(operator); - } + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public AndOperator(AndOperator operator) { + super(operator); + } - /** - * Default constructor. - */ - public AndOperator() { - super(); - } + /** + * Default constructor. + */ + public AndOperator() { + super(); + } - @Override - public String getOperatorText() { - return "&"; - } + @Override + public String getOperatorText() { + return "&"; + } - @Override - public String getSBGNOperatorText() { - return "AND"; - } + @Override + public String getSBGNOperatorText() { + return "AND"; + } - @Override - public AndOperator copy() { - if (this.getClass() == AndOperator.class) { - return new AndOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public AndOperator copy() { + if (this.getClass() == AndOperator.class) { + return new AndOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AssociationOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AssociationOperator.java index 7859ae764e..3886db32c4 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AssociationOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AssociationOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -19,46 +20,46 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("ASSOCIATION_OPERATOR_NODE") public class AssociationOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(AssociationOperator.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(AssociationOperator.class); - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public AssociationOperator(AssociationOperator operator) { - super(operator); - } + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public AssociationOperator(AssociationOperator operator) { + super(operator); + } - /** - * Default constructor. - */ - public AssociationOperator() { - super(); - } + /** + * Default constructor. + */ + public AssociationOperator() { + super(); + } - @Override - public String getOperatorText() { - return "&"; - } + @Override + public String getOperatorText() { + return "&"; + } - @Override - public AssociationOperator copy() { - if (this.getClass() == AssociationOperator.class) { - return new AssociationOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public AssociationOperator copy() { + if (this.getClass() == AssociationOperator.class) { + return new AssociationOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/DissociationOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/DissociationOperator.java index 462044be1d..2c6fe8678f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/DissociationOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/DissociationOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -18,46 +19,46 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("DISSOCIATION_OPERATOR_NODE") public class DissociationOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(DissociationOperator.class); - - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public DissociationOperator(DissociationOperator operator) { - super(operator); - } - - /** - * Default constructor. - */ - public DissociationOperator() { - super(); - } - - @Override - public String getOperatorText() { - return "â—‹"; - } - - @Override - public DissociationOperator copy() { - if (this.getClass() == DissociationOperator.class) { - return new DissociationOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(DissociationOperator.class); + + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public DissociationOperator(DissociationOperator operator) { + super(operator); + } + + /** + * Default constructor. + */ + public DissociationOperator() { + super(); + } + + @Override + public String getOperatorText() { + return "â—‹"; + } + + @Override + public DissociationOperator copy() { + if (this.getClass() == DissociationOperator.class) { + return new DissociationOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Modifier.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Modifier.java index 5527d7a4e2..33999b74e5 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Modifier.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Modifier.java @@ -18,47 +18,47 @@ import lcsb.mapviewer.model.map.species.Species; @Entity @DiscriminatorValue("MODIFIER_NODE") public class Modifier extends ReactionNode { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - */ - protected Modifier() { - super(); - } + /** + * Default constructor. + */ + protected Modifier() { + super(); + } - /** - * Constructor that creates modifier for given {@link Species}. These - * elements reference to the objects in the - * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model} that - * represents this modifier. - * - * @param element - * element that represent this modifier - */ - public Modifier(Element element) { - super(element); - } + /** + * Constructor that creates modifier for given {@link Species}. These elements + * reference to the objects in the + * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model} that + * represents this modifier. + * + * @param element + * element that represent this modifier + */ + public Modifier(Element element) { + super(element); + } - /** - * Constructor that initialize the modifier with data from parameter. - * - * @param original - * original modifier used for data initialization - */ - protected Modifier(Modifier original) { - super(original); - } + /** + * Constructor that initialize the modifier with data from parameter. + * + * @param original + * original modifier used for data initialization + */ + protected Modifier(Modifier original) { + super(original); + } - @Override - public Modifier copy() { - if (this.getClass() == Modifier.class) { - return new Modifier(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public Modifier copy() { + if (this.getClass() == Modifier.class) { + return new Modifier(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/NandOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/NandOperator.java index 13a7f475f4..94c85733b3 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/NandOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/NandOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -17,46 +18,46 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @Entity @DiscriminatorValue("NAND_OPERATOR_NODE") public class NandOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(NandOperator.class); - - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public NandOperator(NandOperator operator) { - super(operator); - } - - /** - * Default constructor. - */ - public NandOperator() { - super(); - } - - @Override - public String getOperatorText() { - return "~"; - } - - @Override - public NandOperator copy() { - if (this.getClass() == NandOperator.class) { - return new NandOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(NandOperator.class); + + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public NandOperator(NandOperator operator) { + super(operator); + } + + /** + * Default constructor. + */ + public NandOperator() { + super(); + } + + @Override + public String getOperatorText() { + return "~"; + } + + @Override + public NandOperator copy() { + if (this.getClass() == NandOperator.class) { + return new NandOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperator.java index ce0d9e1412..edb31556a1 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperator.java @@ -1,16 +1,11 @@ package lcsb.mapviewer.model.map.reaction; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparator.java index 2acb49363b..2a82eab580 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -24,7 +25,7 @@ public class NodeOperatorComparator extends Comparator<NodeOperator> { * Epsilon value used for comparison of doubles. */ private double epsilon; - + private boolean ignoreLayout; /** @@ -43,10 +44,6 @@ public class NodeOperatorComparator extends Comparator<NodeOperator> { this(epsilon, false); } - protected Comparator<?> getParentComparator() { - return new AbstractNodeComparator(epsilon, ignoreLayout); - } - /** * Default constructor. */ @@ -54,6 +51,10 @@ public class NodeOperatorComparator extends Comparator<NodeOperator> { this(Configuration.EPSILON); } + protected Comparator<?> getParentComparator() { + return new AbstractNodeComparator(epsilon, ignoreLayout); + } + @Override protected int internalCompare(NodeOperator arg0, NodeOperator arg1) { AbstractNodeComparator anComparator = new AbstractNodeComparator(epsilon, ignoreLayout); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/OrOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/OrOperator.java index 21613a239b..ff4f1b4158 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/OrOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/OrOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -18,51 +19,51 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("OR_OPERATOR_NODE") public class OrOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(OrOperator.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(OrOperator.class); - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public OrOperator(OrOperator operator) { - super(operator); - } + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public OrOperator(OrOperator operator) { + super(operator); + } - /** - * Default constructor. - */ - public OrOperator() { - super(); - } + /** + * Default constructor. + */ + public OrOperator() { + super(); + } - @Override - public String getOperatorText() { - return "|"; - } - - @Override - public String getSBGNOperatorText() { - return "OR"; - } + @Override + public String getOperatorText() { + return "|"; + } - @Override - public OrOperator copy() { - if (this.getClass() == OrOperator.class) { - return new OrOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public String getSBGNOperatorText() { + return "OR"; + } + + @Override + public OrOperator copy() { + if (this.getClass() == OrOperator.class) { + return new OrOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Product.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Product.java index 110dcddb57..9c98d7a92f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Product.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Product.java @@ -18,51 +18,51 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("PRODUCT_NODE") public class Product extends ReactionNode { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - */ - public Product() { - super(); - } + /** + * Default constructor. + */ + public Product() { + super(); + } - /** - * Constructor that creates product for given {@link Species}. These - * elements reference to the objects in the - * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model} that - * represents this product. - * - * @param element - * element that represent this product - */ - public Product(Element element) { - super(element); - if (element==null) { - throw new InvalidArgumentException("Element cannot be null"); - } - } + /** + * Constructor that creates product for given {@link Species}. These elements + * reference to the objects in the + * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model} that + * represents this product. + * + * @param element + * element that represent this product + */ + public Product(Element element) { + super(element); + if (element == null) { + throw new InvalidArgumentException("Element cannot be null"); + } + } - /** - * Constructor that initialize the product with data from parameter. - * - * @param original - * original product used for data initalization - */ - protected Product(Product original) { - super(original); - } + /** + * Constructor that initialize the product with data from parameter. + * + * @param original + * original product used for data initalization + */ + protected Product(Product original) { + super(original); + } - @Override - public Product copy() { - if (this.getClass() == Product.class) { - return new Product(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public Product copy() { + if (this.getClass() == Product.class) { + return new Product(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reactant.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reactant.java index aadfb454e2..b9180904ef 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reactant.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reactant.java @@ -18,50 +18,50 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("REACTANT_NODE") public class Reactant extends ReactionNode { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - */ - public Reactant() { - super(); - } + /** + * Default constructor. + */ + public Reactant() { + super(); + } - /** - * Constructor that creates reactant for a given {@link Species}. These - * elements reference to the objects in the - * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model} that - * represents this reactant. - * - * @param element - * element that represent this reactant - */ - public Reactant(Element element) { - super(element); - if (element==null) { - throw new InvalidArgumentException("Element cannot be null"); - } - } + /** + * Constructor that creates reactant for a given {@link Species}. These elements + * reference to the objects in the + * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model} that + * represents this reactant. + * + * @param element + * element that represent this reactant + */ + public Reactant(Element element) { + super(element); + if (element == null) { + throw new InvalidArgumentException("Element cannot be null"); + } + } - /** - * Constructor that initialize the reactant with data from parameter. - * - * @param original - * original reactant used for data initalization - */ - public Reactant(Reactant original) { - super(original); - } + /** + * Constructor that initialize the reactant with data from parameter. + * + * @param original + * original reactant used for data initalization + */ + public Reactant(Reactant original) { + super(original); + } - @Override - public Reactant copy() { - if (this.getClass() == Reactant.class) { - return new Reactant(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + @Override + public Reactant copy() { + if (this.getClass() == Reactant.class) { + return new Reactant(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reaction.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reaction.java index 7288924b23..64a886593f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reaction.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/Reaction.java @@ -2,34 +2,9 @@ package lcsb.mapviewer.model.map.reaction; import java.awt.geom.Line2D; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.OrderBy; -import javax.persistence.OrderColumn; +import java.util.*; + +import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; import org.apache.logging.log4j.LogManager; @@ -45,9 +20,7 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.reaction.type.ReactionRect; -import lcsb.mapviewer.model.map.reaction.type.TwoProductReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.TwoReactantReactionInterface; +import lcsb.mapviewer.model.map.reaction.type.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -79,11 +52,6 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; @DiscriminatorValue("GENERIC_REACTION") public class Reaction implements BioEntity { - /** - * - */ - private static final long serialVersionUID = 1L; - /** * Comparator of reactions that compare them using {@link #idReaction * identifier} as a key. @@ -94,7 +62,10 @@ public class Reaction implements BioEntity { return reaction1.getIdReaction().compareTo(reaction2.getIdReaction()); } }; - + /** + * + */ + private static final long serialVersionUID = 1L; /** * Default class logger. */ @@ -443,28 +414,9 @@ public class Reaction implements BioEntity { return result; } - /** - * Returns short string describing type of the reaction. - * - * @return short string describing type of the reaction - */ - public String getStringType() { - return "Generic Reaction"; - } - - @Override - public String getVisibilityLevel() { - return visibilityLevel; - } - - @Override - public void setVisibilityLevel(String visibilityLevel) { - this.visibilityLevel = visibilityLevel; - } - /** * Returns list of nodes (producst+rectants+modifiers) in the reaction. - * + * * @return list of nodes (producst+rectants+modifiers) in the reaction */ public List<ReactionNode> getReactionNodes() { @@ -479,28 +431,34 @@ public class Reaction implements BioEntity { /** * Removes modifier. - * + * * @param modifier * modifier to remove */ public void removeModifier(Modifier modifier) { nodes.remove(modifier); + } @Override + public String getVisibilityLevel() { + return visibilityLevel; } /** * Removes {@link AbstractNode}. - * + * * @param node * node to remove */ public void removeNode(AbstractNode node) { nodes.remove(node); + } @Override + public void setVisibilityLevel(String visibilityLevel) { + this.visibilityLevel = visibilityLevel; } /** * Returns {@link ReactionRect} object that defines a small object that should * be drawn on the central line of the reaction. - * + * * @return {@link ReactionRect} object that defines a small object that should * be drawn on the central line of the reaction */ @@ -510,7 +468,7 @@ public class Reaction implements BioEntity { /** * Check if one of the nodes reference to the element. - * + * * @param element * element to be checked * @return <code>true</code> if element is part of the reaction, @@ -525,22 +483,9 @@ public class Reaction implements BioEntity { return false; } - /** - * Creates copy of the reaction. - * - * @return copy of the reaction - */ - public Reaction copy() { - if (this.getClass() == Reaction.class) { - return new Reaction(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - /** * Returns list of all {@link NodeOperator operators}. - * + * * @return list of all {@link NodeOperator operators} */ public List<NodeOperator> getOperators() { @@ -553,23 +498,6 @@ public class Reaction implements BioEntity { return result; } - /** - * @return the id - * @see #id - */ - public int getId() { - return id; - } - - /** - * @param id - * the id to set - * @see #id - */ - public void setId(int id) { - this.id = id; - } - /** * @return the nodes * @see #nodes @@ -587,27 +515,23 @@ public class Reaction implements BioEntity { this.nodes = nodes; } - @Override - public String getNotes() { - return notes; - } - - @Override - public void setNotes(String notes) { - this.notes = notes; - } - /** * @return the idReaction * @see #idReaction */ public String getIdReaction() { return idReaction; - } - - @Override - public String getElementId() { - return getIdReaction(); + } /** + * Creates copy of the reaction. + * + * @return copy of the reaction + */ + public Reaction copy() { + if (this.getClass() == Reaction.class) { + return new Reaction(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } } /** @@ -619,20 +543,6 @@ public class Reaction implements BioEntity { this.idReaction = idReaction; } - @Override - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - /** * @return the reversible * @see #reversible @@ -662,23 +572,6 @@ public class Reaction implements BioEntity { } } - /** - * @return the model - * @see #model - */ - public ModelData getModelData() { - return model; - } - - /** - * @param model - * the model to set - * @see #model - */ - public void setModelData(ModelData model) { - this.model = model; - } - @Override public void addMiriamData(MiriamData md) { if (this.miriamDataSet.contains(md)) { @@ -689,20 +582,19 @@ public class Reaction implements BioEntity { } } - /** - * Sets model where the reaction is located. - * - * @param model2 - * model where the reaction is located - */ - public void setModel(Model model2) { - this.model = model2.getModelData(); + @Override + public String getName() { + return name; } - @XmlTransient @Override - public Model getModel() { - return model.getModel(); + public String getNotes() { + return notes; + } + + @Override + public void setNotes(String notes) { + this.notes = notes; } @Override @@ -715,6 +607,23 @@ public class Reaction implements BioEntity { this.symbol = symbol; } + /** + * @return the synonyms + * @see #synonyms + */ + public List<String> getSynonyms() { + return synonyms; + } + + /** + * @param synonyms + * the synonyms to set + * @see #synonyms + */ + public void setSynonyms(List<String> synonyms) { + this.synonyms = synonyms; + } + @Override public String getAbbreviation() { return abbreviation; @@ -725,14 +634,68 @@ public class Reaction implements BioEntity { this.abbreviation = abbreviation; } - @Override - public String getFormula() { - return formula; + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; } + /** + * @return the id + * @see #id + */ + public int getId() { + return id; + } + + /** + * Returns short string describing type of the reaction. + * + * @return short string describing type of the reaction + */ + public String getStringType() { + return "Generic Reaction"; + } + + /** + * @param id + * the id to set + * @see #id + */ + public void setId(int id) { + this.id = id; + } + + /** + * @return the model + * @see #model + */ + public ModelData getModelData() { + return model; + } /** + * Sets model where the reaction is located. + * + * @param model2 + * model where the reaction is located + */ + public void setModel(Model model2) { + this.model = model2.getModelData(); + } + + /** + * @param model + * the model to set + * @see #model + */ + public void setModelData(ModelData model) { + this.model = model; + } @XmlTransient @Override - public void setFormula(String formula) { - this.formula = formula; + public Model getModel() { + return model.getModel(); } /** @@ -775,6 +738,9 @@ public class Reaction implements BioEntity { */ public Double getUpperBound() { return upperBound; + } @Override + public String getFormula() { + return formula; } /** @@ -784,6 +750,9 @@ public class Reaction implements BioEntity { */ public void setUpperBound(Double upperBound) { this.upperBound = upperBound; + } @Override + public void setFormula(String formula) { + this.formula = formula; } /** @@ -820,26 +789,9 @@ public class Reaction implements BioEntity { this.geneProteinReaction = geneProteinReaction; } - /** - * @return the synonyms - * @see #synonyms - */ - public List<String> getSynonyms() { - return synonyms; - } - - /** - * @param synonyms - * the synonyms to set - * @see #synonyms - */ - public void setSynonyms(List<String> synonyms) { - this.synonyms = synonyms; - } - /** * Adds synonym to the {@link #synonyms}. - * + * * @param synonym * new synonym to add */ @@ -847,16 +799,6 @@ public class Reaction implements BioEntity { this.synonyms.add(synonym); } - @Override - public void setVisibilityLevel(Integer zoomLevelVisibility) { - if (zoomLevelVisibility == null) { - this.visibilityLevel = null; - } else { - this.visibilityLevel = zoomLevelVisibility + ""; - } - - } - public SbmlKinetics getKinetics() { return kinetics; } @@ -875,6 +817,11 @@ public class Reaction implements BioEntity { this.z = z; } + @Override + public String getElementId() { + return getIdReaction(); + } + @Override public double getSize() { return 0; @@ -891,5 +838,29 @@ public class Reaction implements BioEntity { public void setLine(PolylineData line) { this.line = line; + } @Override + public void setVisibilityLevel(Integer zoomLevelVisibility) { + if (zoomLevelVisibility == null) { + this.visibilityLevel = null; + } else { + this.visibilityLevel = zoomLevelVisibility + ""; + } + } + + + + + + + + + + + + + + + + } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionComparator.java index 39d0259ebc..f6249b7feb 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionComparator.java @@ -5,12 +5,7 @@ import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.BooleanComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.SetComparator; -import lcsb.mapviewer.common.comparator.StringComparator; -import lcsb.mapviewer.common.comparator.StringListComparator; +import lcsb.mapviewer.common.comparator.*; import lcsb.mapviewer.model.graphics.PolylineDataComparator; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamDataComparator; @@ -32,7 +27,7 @@ public class ReactionComparator extends Comparator<Reaction> { * Epsilon value used for comparison of doubles. */ private double epsilon; - + private boolean ignoreLayout; /** @@ -46,7 +41,7 @@ public class ReactionComparator extends Comparator<Reaction> { this.epsilon = epsilon; this.ignoreLayout = ignoreLayout; } - + public ReactionComparator(double epsilon) { this(epsilon, false); } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNode.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNode.java index 85f99be6a6..f5ba4ab033 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNode.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNode.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.model.map.reaction; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -92,7 +90,7 @@ public abstract class ReactionNode extends AbstractNode { public void setStoichiometry(Double stoichiometry) { this.stoichiometry = stoichiometry; } - + @Override public String toString() { return new ElementUtils().getElementTag(this); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparator.java index 2e8323b300..72721cc921 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -47,10 +48,6 @@ public class ReactionNodeComparator extends Comparator<ReactionNode> { this(epsilon, false); } - protected Comparator<?> getParentComparator() { - return new AbstractNodeComparator(epsilon, ignoreLayout); - } - /** * Default constructor. */ @@ -58,6 +55,10 @@ public class ReactionNodeComparator extends Comparator<ReactionNode> { this(Configuration.EPSILON); } + protected Comparator<?> getParentComparator() { + return new AbstractNodeComparator(epsilon, ignoreLayout); + } + @Override protected int internalCompare(ReactionNode arg0, ReactionNode arg1) { AbstractNodeComparator anComparator = new AbstractNodeComparator(epsilon, ignoreLayout); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/SplitOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/SplitOperator.java index 4affd22bac..ca7f2f0556 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/SplitOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/SplitOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -18,46 +19,46 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("SPLIT_OPERATOR_NODE") public class SplitOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(SplitOperator.class); - - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public SplitOperator(SplitOperator operator) { - super(operator); - } - - /** - * Default constructor. - */ - public SplitOperator() { - super(); - } - - @Override - public String getOperatorText() { - return ""; - } - - @Override - public SplitOperator copy() { - if (this.getClass() == SplitOperator.class) { - return new SplitOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(SplitOperator.class); + + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public SplitOperator(SplitOperator operator) { + super(operator); + } + + /** + * Default constructor. + */ + public SplitOperator() { + super(); + } + + @Override + public String getOperatorText() { + return ""; + } + + @Override + public SplitOperator copy() { + if (this.getClass() == SplitOperator.class) { + return new SplitOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/TruncationOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/TruncationOperator.java index b9850c2681..79c25e3e29 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/TruncationOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/TruncationOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -18,46 +19,46 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("TRUNCATION_OPERATOR_NODE") public class TruncationOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(TruncationOperator.class); - - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public TruncationOperator(TruncationOperator operator) { - super(operator); - } - - /** - * Default constructor. - */ - public TruncationOperator() { - super(); - } - - @Override - public String getOperatorText() { - return ""; - } - - @Override - public TruncationOperator copy() { - if (this.getClass() == TruncationOperator.class) { - return new TruncationOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(TruncationOperator.class); + + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public TruncationOperator(TruncationOperator operator) { + super(operator); + } + + /** + * Default constructor. + */ + public TruncationOperator() { + super(); + } + + @Override + public String getOperatorText() { + return ""; + } + + @Override + public TruncationOperator copy() { + if (this.getClass() == TruncationOperator.class) { + return new TruncationOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/UnknownOperator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/UnknownOperator.java index ae3f63f81b..39fbebeceb 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/UnknownOperator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/UnknownOperator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.reaction; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; @@ -18,46 +19,46 @@ import lcsb.mapviewer.common.exception.NotImplementedException; @DiscriminatorValue("UNKNOWN_OPERATOR_NODE") public class UnknownOperator extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(UnknownOperator.class); - - /** - * Constructor that copies data from the parameter given in the argument. - * - * @param operator - * parent operator from which we copy data - */ - public UnknownOperator(UnknownOperator operator) { - super(operator); - } - - /** - * Default constructor. - */ - public UnknownOperator() { - super(); - } - - @Override - public String getOperatorText() { - return "?"; - } - - @Override - public UnknownOperator copy() { - if (this.getClass() == UnknownOperator.class) { - return new UnknownOperator(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(UnknownOperator.class); + + /** + * Constructor that copies data from the parameter given in the argument. + * + * @param operator + * parent operator from which we copy data + */ + public UnknownOperator(UnknownOperator operator) { + super(operator); + } + + /** + * Default constructor. + */ + public UnknownOperator() { + super(); + } + + @Override + public String getOperatorText() { + return "?"; + } + + @Override + public UnknownOperator copy() { + if (this.getClass() == UnknownOperator.class) { + return new UnknownOperator(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/package-info.java index bd371e82b9..518019086e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/package-info.java @@ -1,7 +1,7 @@ /** * Contains structures used for modeling reactions. Main class representing - * reaction is {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction}. - * It is extended by several different types of reactions that were put in the + * reaction is {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction}. It + * is extended by several different types of reactions that were put in the * {@link lcsb.mapviewer.model.map.reaction.type type} sub-package. * * Every reaction contains set of nodes that extend @@ -9,4 +9,3 @@ * */ package lcsb.mapviewer.model.map.reaction; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/type/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/type/package-info.java index 806f1943bb..65a2aa74a6 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/type/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/type/package-info.java @@ -3,4 +3,3 @@ * (maybe it should be transformed to a kind of enum...). */ package lcsb.mapviewer.model.map.reaction.type; - diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRna.java b/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRna.java index 088eac1a13..ef7b4e8ebe 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRna.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRna.java @@ -3,23 +3,14 @@ package lcsb.mapviewer.model.map.species; import java.util.ArrayList; import java.util.List; -import javax.persistence.DiscriminatorValue; +import javax.persistence.*; import javax.persistence.Entity; -import javax.persistence.OneToMany; -import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.SpeciesWithCodingRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationSite; -import lcsb.mapviewer.model.map.species.field.SpeciesWithProteinBindingDomain; +import lcsb.mapviewer.model.map.species.field.*; /** * Entity representing antisense rna element on the map. @@ -118,11 +109,6 @@ public class AntisenseRna extends Species return regions; } - @Override - public List<ModificationResidue> getModificationResidues() { - return getRegions(); - } - /** * @param regions * the regions to set @@ -132,6 +118,11 @@ public class AntisenseRna extends Species this.regions = regions; } + @Override + public List<ModificationResidue> getModificationResidues() { + return getRegions(); + } + @Override public String getStringType() { return "Antisense RNA"; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparator.java index d50acfca12..6d4f0be4df 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.species; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Chemical.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Chemical.java index 064397dd0e..cabe5500d3 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Chemical.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Chemical.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.model.map.species; -import javax.persistence.Column; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; +import javax.persistence.*; /** * Entity representing chemical element on the map. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/ChemicalComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/ChemicalComparator.java index b6c41465cf..960d18c77b 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/ChemicalComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/ChemicalComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -37,11 +38,6 @@ public class ChemicalComparator extends Comparator<Chemical> { addSubClassComparator(new SimpleMoleculeComparator(epsilon)); } - @Override - protected Comparator<?> getParentComparator() { - return new SpeciesComparator(epsilon); - } - /** * Default constructor. */ @@ -49,6 +45,11 @@ public class ChemicalComparator extends Comparator<Chemical> { this(Configuration.EPSILON); } + @Override + protected Comparator<?> getParentComparator() { + return new SpeciesComparator(epsilon); + } + @Override protected int internalCompare(Chemical arg0, Chemical arg1) { StringComparator stringComparator = new StringComparator(); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Complex.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Complex.java index 673f30044b..4c3e4c4e70 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Complex.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Complex.java @@ -1,16 +1,11 @@ package lcsb.mapviewer.model.map.species; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.OneToMany; +import javax.persistence.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/ComplexComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/ComplexComparator.java index 980548937b..07af665d13 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/ComplexComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/ComplexComparator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.species; import java.util.HashMap; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -39,11 +40,6 @@ public class ComplexComparator extends Comparator<Complex> { this.epsilon = epsilon; } - @Override - protected Comparator<?> getParentComparator() { - return new SpeciesComparator(epsilon); - } - /** * Default constructor. */ @@ -51,6 +47,11 @@ public class ComplexComparator extends Comparator<Complex> { this(Configuration.EPSILON); } + @Override + protected Comparator<?> getParentComparator() { + return new SpeciesComparator(epsilon); + } + @Override protected int internalCompare(Complex arg0, Complex arg1) { ElementComparator elementComparator = new ElementComparator(epsilon); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/DegradedComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/DegradedComparator.java index 533decd1db..83535c256e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/DegradedComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/DegradedComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -35,11 +36,6 @@ public class DegradedComparator extends Comparator<Degraded> { this.epsilon = epsilon; } - @Override - protected Comparator<?> getParentComparator() { - return new SpeciesComparator(epsilon); - } - /** * Default constructor. */ @@ -47,6 +43,11 @@ public class DegradedComparator extends Comparator<Degraded> { this(Configuration.EPSILON); } + @Override + protected Comparator<?> getParentComparator() { + return new SpeciesComparator(epsilon); + } + @Override protected int internalCompare(Degraded arg0, Degraded arg1) { return 0; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/DrugComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/DrugComparator.java index 3b6e6ae294..2f5ca405a8 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/DrugComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/DrugComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Element.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Element.java index b12449a841..631dc6a158 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Element.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Element.java @@ -1,52 +1,27 @@ package lcsb.mapviewer.model.map.species; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; - -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderColumn; + +import javax.persistence.*; import javax.xml.bind.annotation.XmlTransient; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.SearchIndex; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.kinetics.SbmlArgument; import lcsb.mapviewer.model.map.layout.graphics.Glyph; 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.*; /** * Abstract class representing objects in the model. Elements are objects that @@ -62,21 +37,6 @@ import lcsb.mapviewer.model.map.model.ModelData; @DiscriminatorValue("GENERIC") public abstract class Element implements BioEntity, Serializable, SbmlArgument { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default font size for element description. - */ - private static final double DEFAULT_FONT_SIZE = 12.0; - - /** - * Maximum length of the valid synonym name. - */ - private static final int MAX_SYNONYM_LENGTH = 255; - /** * Comparator of elements that takes into consideration size (width*height) of * elements. @@ -96,7 +56,18 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } } }; - + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * Default font size for element description. + */ + private static final double DEFAULT_FONT_SIZE = 12.0; + /** + * Maximum length of the valid synonym name. + */ + private static final int MAX_SYNONYM_LENGTH = 255; /** * Default class logger. */ @@ -307,16 +278,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } } - /** - * Adds list of former symbol to the object. - * - * @param formerSymbols - * list of former symbols to add - */ - public void addFormerSymbols(List<String> formerSymbols) { - this.formerSymbols.addAll(formerSymbols); - } - /** * Empty constructor required by hibernate. */ @@ -332,36 +293,13 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } /** - * Parse and set x coordinate from string. - * - * @param string - * text representing x coordinate - * @see x - */ - public void setX(String string) { - setX(Double.parseDouble(string)); - } - - /** - * Parse and set y coordinate from string. - * - * @param string - * text representing y coordinate - * @see y - */ - public void setY(String string) { - this.y = Double.parseDouble(string); - } - - /** - * Parse and set font size. + * Adds list of former symbol to the object. * - * @param string - * text representing font size - * @see fontSize + * @param formerSymbols + * list of former symbols to add */ - public void setFontSize(String string) { - this.fontSize = Double.parseDouble(string); + public void addFormerSymbols(List<String> formerSymbols) { + this.formerSymbols.addAll(formerSymbols); } /** @@ -405,56 +343,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { this.height += increaseSize * 2; } - /** - * Parse and set width. - * - * @param string - * text representing width - * @see width - */ - public void setWidth(String string) { - try { - width = Double.parseDouble(string); - } catch (NumberFormatException e) { - throw new InvalidArgumentException("Invalid width format: " + string, e); - } - } - - /** - * Parse and set height. - * - * @param string - * text representing height - * @see height - */ - public void setHeight(String string) { - try { - height = Double.parseDouble(string); - } catch (Exception e) { - throw new InvalidArgumentException("Invalid height format: " + string, e); - } - } - - /** - * - * @param width - * the width value to set - * @see #width - */ - public void setWidth(int width) { - this.width = (double) width; - } - - /** - * - * @param height - * the height value to set - * @see #height - */ - public void setHeight(int height) { - this.height = (double) height; - } - /** * This method computes the distance between point and the element. It assumes * that element is a rectangle. @@ -506,13 +394,11 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { return new Rectangle2D.Double(x, y, width, height); } - /** - * Returns size of the element in square units. - * - * @return size of the element - */ - public double getSize() { - return getWidth() * getHeight(); + public void setBorder(Rectangle2D border) { + setX(border.getX()); + setY(border.getY()); + setWidth(border.getWidth()); + setHeight(border.getHeight()); } /** @@ -540,38 +426,32 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } /** - * Makes a copy of the element. - * - * @return copy of the element + * @return the x + * @see #x */ - public abstract Element copy(); + public Double getX() { + return x; + } /** + * Parse and set x coordinate from string. * - * @param x - * the x value to set + * @param string + * text representing x coordinate * @see x */ - public void setX(int x) { - setX((double) x); + public void setX(String string) { + setX(Double.parseDouble(string)); } /** * - * @param y - * the y value to set - * @see y - */ - public void setY(int y) { - setY((double) y); - } - - /** - * @return the x - * @see #x + * @param x + * the x value to set + * @see x */ - public Double getX() { - return x; + public void setX(int x) { + setX((double) x); } /** @@ -591,6 +471,27 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { return y; } + /** + * Parse and set y coordinate from string. + * + * @param string + * text representing y coordinate + * @see y + */ + public void setY(String string) { + this.y = Double.parseDouble(string); + } + + /** + * + * @param y + * the y value to set + * @see y + */ + public void setY(int y) { + setY((double) y); + } + /** * @param y * the y to set @@ -598,7 +499,12 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { */ public void setY(Double y) { this.y = y; - } + } /** + * Makes a copy of the element. + * + * @return copy of the element + */ + public abstract Element copy(); /** * @return the width @@ -608,6 +514,31 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { return width; } + /** + * Parse and set width. + * + * @param string + * text representing width + * @see width + */ + public void setWidth(String string) { + try { + width = Double.parseDouble(string); + } catch (NumberFormatException e) { + throw new InvalidArgumentException("Invalid width format: " + string, e); + } + } + + /** + * + * @param width + * the width value to set + * @see #width + */ + public void setWidth(int width) { + this.width = (double) width; + } + /** * @param width * the width to set @@ -625,6 +556,31 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { return height; } + /** + * Parse and set height. + * + * @param string + * text representing height + * @see height + */ + public void setHeight(String string) { + try { + height = Double.parseDouble(string); + } catch (Exception e) { + throw new InvalidArgumentException("Invalid height format: " + string, e); + } + } + + /** + * + * @param height + * the height value to set + * @see #height + */ + public void setHeight(int height) { + this.height = (double) height; + } + /** * @param height * the height to set @@ -643,45 +599,32 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } /** - * @param fontSize - * the fontSize to set - * @see #fontSize + * Parse and set font size. + * + * @param string + * text representing font size + * @see fontSize */ - public void setFontSize(Double fontSize) { - this.fontSize = fontSize; - } - - @Override - public String getElementId() { - return elementId; + public void setFontSize(String string) { + this.fontSize = Double.parseDouble(string); } /** - * @param elementId - * the elementId to set - * @see #elementId + * @param fontSize + * the fontSize to set + * @see #fontSize */ - public void setElementId(String elementId) { - this.elementId = elementId; - } - - @Override - public String getVisibilityLevel() { - return visibilityLevel; - } - - @Override - public void setVisibilityLevel(String visibilityLevel) { - this.visibilityLevel = visibilityLevel; + public void setFontSize(Double fontSize) { + this.fontSize = fontSize; } - @Override - public void setVisibilityLevel(Integer visibilityLevel) { - if (visibilityLevel == null) { - this.visibilityLevel = null; - } else { - this.visibilityLevel = visibilityLevel + ""; - } + /** + * @param fontSize + * the fontSize to set + * @see #fontSize + */ + public void setFontSize(int fontSize) { + setFontSize((double) fontSize); } /** @@ -707,6 +650,9 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { */ public Compartment getCompartment() { return compartment; + } @Override + public String getVisibilityLevel() { + return visibilityLevel; } /** @@ -721,23 +667,9 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { formerCompartment.removeElement(this); } this.compartment = compartment; - } - - /** - * @return the id - * @see #id - */ - public int getId() { - return id; - } - - /** - * @param id - * the id to set - * @see #id - */ - public void setId(int id) { - this.id = id; + } @Override + public void setVisibilityLevel(String visibilityLevel) { + this.visibilityLevel = visibilityLevel; } /** @@ -746,6 +678,13 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { */ public Color getColor() { return color; + } @Override + public void setVisibilityLevel(Integer visibilityLevel) { + if (visibilityLevel == null) { + this.visibilityLevel = null; + } else { + this.visibilityLevel = visibilityLevel + ""; + } } /** @@ -774,19 +713,12 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { this.transparencyLevel = transparencyLevel; } - @XmlTransient - @Override - public Model getModel() { - return model.getModel(); - } - /** - * @param model - * the model to set - * @see #model + * @return the searchIndexes + * @see #searchIndexes */ - public void setModel(Model model) { - this.model = model.getModelData(); + public List<SearchIndex> getSearchIndexes() { + return searchIndexes; } /** @@ -802,14 +734,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { this.searchIndexes.addAll(searchIndexes); } - /** - * @return the searchIndexes - * @see #searchIndexes - */ - public List<SearchIndex> getSearchIndexes() { - return searchIndexes; - } - /** * @return the submodel * @see #submodel @@ -830,15 +754,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } } - /** - * @param fontSize - * the fontSize to set - * @see #fontSize - */ - public void setFontSize(int fontSize) { - setFontSize((double) fontSize); - } - /** * Checks if element contains a {@link LayerText}. * @@ -863,23 +778,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { searchIndexes.add(searchIndex); } - /** - * @return the symbol - * @see #symbol - */ - public String getSymbol() { - return symbol; - } - - /** - * @param symbol - * the symbol to set - * @see #symbol - */ - public void setSymbol(String symbol) { - this.symbol = symbol; - } - /** * @return the fullName * @see #fullName @@ -895,40 +793,68 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { */ public void setFullName(String fullName) { this.fullName = fullName; + } @XmlTransient + @Override + public Model getModel() { + return model.getModel(); } /** - * @return the abbreviation - * @see #abbreviation + * @return the formerSymbols + * @see #formerSymbols */ - public String getAbbreviation() { - return abbreviation; + public List<String> getFormerSymbols() { + return formerSymbols; + } /** + * @param model + * the model to set + * @see #model + */ + public void setModel(Model model) { + this.model = model.getModelData(); } /** - * @param abbreviation - * the abbreviation to set - * @see #abbreviation + * @param formerSymbols + * the formerSymbols to set + * @see #formerSymbols */ - public void setAbbreviation(String abbreviation) { - this.abbreviation = abbreviation; + public void setFormerSymbols(List<String> formerSymbols) { + this.formerSymbols = formerSymbols; } /** - * @return the formula - * @see #formula + * @return the miriamData + * @see #miriamData */ - public String getFormula() { - return formula; + public Set<MiriamData> getMiriamData() { + return miriamData; } /** - * @param formula - * the formula to set - * @see #formula + * @param miriamData + * the miriamData to set + * @see #miriamData */ - public void setFormula(String formula) { - this.formula = formula; + public void setMiriamData(Set<MiriamData> miriamData) { + this.miriamData = miriamData; + } + + @Override + public void addMiriamData(Collection<MiriamData> miriamData) { + for (MiriamData md : miriamData) { + addMiriamData(md); + } + } + + @Override + public void addMiriamData(MiriamData md) { + if (this.miriamData.contains(md)) { + logger.warn("Miriam data (" + md.getDataType() + ": " + md.getResource() + ") for " + getElementId() + + " already exists. Ignoring..."); + } else { + this.miriamData.add(md); + } } /** @@ -948,12 +874,67 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { this.name = name; } + /** + * @return the id + * @see #id + */ + public int getId() { + return id; + } + + /** + * @param id + * the id to set + * @see #id + */ + public void setId(int id) { + this.id = id; + } + + @Override + public String getNotes() { + return notes; + } + + @Override + public void setNotes(String notes) { + if (notes != null) { + if (notes.contains("</html>")) { + throw new InvalidArgumentException("Notes cannot contain html tags..."); + } + } + this.notes = notes; + } + + /** + * @return the symbol + * @see #symbol + */ + public String getSymbol() { + return symbol; + } + + /** + * @param symbol + * the symbol to set + * @see #symbol + */ + public void setSymbol(String symbol) { + this.symbol = symbol; + } + /** * @return the synonyms * @see #synonyms */ public List<String> getSynonyms() { return synonyms; + } /** + * @return the formula + * @see #formula + */ + public String getFormula() { + return formula; } /** @@ -963,40 +944,30 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { */ public void setSynonyms(List<String> synonyms) { this.synonyms = synonyms; - } - - /** - * @return the formerSymbols - * @see #formerSymbols - */ - public List<String> getFormerSymbols() { - return formerSymbols; - } - - /** - * @param formerSymbols - * the formerSymbols to set - * @see #formerSymbols + } /** + * @param formula + * the formula to set + * @see #formula */ - public void setFormerSymbols(List<String> formerSymbols) { - this.formerSymbols = formerSymbols; + public void setFormula(String formula) { + this.formula = formula; } /** - * @return the miriamData - * @see #miriamData + * @return the abbreviation + * @see #abbreviation */ - public Set<MiriamData> getMiriamData() { - return miriamData; + public String getAbbreviation() { + return abbreviation; } /** - * @param miriamData - * the miriamData to set - * @see #miriamData + * @param abbreviation + * the abbreviation to set + * @see #abbreviation */ - public void setMiriamData(Set<MiriamData> miriamData) { - this.miriamData = miriamData; + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; } /** @@ -1017,38 +988,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { } - @Override - public void addMiriamData(Collection<MiriamData> miriamData) { - for (MiriamData md : miriamData) { - addMiriamData(md); - } - } - - @Override - public void addMiriamData(MiriamData md) { - if (this.miriamData.contains(md)) { - logger.warn("Miriam data (" + md.getDataType() + ": " + md.getResource() + ") for " + getElementId() - + " already exists. Ignoring..."); - } else { - this.miriamData.add(md); - } - } - - @Override - public String getNotes() { - return notes; - } - - @Override - public void setNotes(String notes) { - if (notes != null) { - if (notes.contains("</html>")) { - throw new InvalidArgumentException("Notes cannot contain html tags..."); - } - } - this.notes = notes; - } - /** * Adds former symbol to the object. * @@ -1077,13 +1016,6 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { this.fontColor = fontColor; } - public void setBorder(Rectangle2D border) { - setX(border.getX()); - setY(border.getY()); - setWidth(border.getWidth()); - setHeight(border.getHeight()); - } - @Override public Integer getZ() { return z; @@ -1094,6 +1026,29 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { this.z = z; } + @Override + public String getElementId() { + return elementId; + } + + /** + * Returns size of the element in square units. + * + * @return size of the element + */ + public double getSize() { + return getWidth() * getHeight(); + } + + /** + * @param elementId + * the elementId to set + * @see #elementId + */ + public void setElementId(String elementId) { + this.elementId = elementId; + } + public Glyph getGlyph() { return glyph; } @@ -1101,4 +1056,20 @@ public abstract class Element implements BioEntity, Serializable, SbmlArgument { public void setGlyph(Glyph glyph) { this.glyph = glyph; } + + + + + + + + + + + + + + + + } \ No newline at end of file diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java index 4fc14abe8a..6c3485ab98 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java @@ -1,15 +1,11 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.ColorComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.SetComparator; -import lcsb.mapviewer.common.comparator.StringComparator; -import lcsb.mapviewer.common.comparator.StringListComparator; +import lcsb.mapviewer.common.comparator.*; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamDataComparator; import lcsb.mapviewer.model.map.compartment.CompartmentComparator; @@ -90,7 +86,6 @@ public class ElementComparator extends Comparator<Element> { return integerComparator.compare(arg0.getZ(), arg1.getZ()); } - if (doubleComparator.compare(arg0.getWidth(), arg1.getWidth()) != 0) { logger.debug("Width different: " + arg0.getWidth() + ", " + arg1.getWidth()); return doubleComparator.compare(arg0.getWidth(), arg1.getWidth()); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Gene.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Gene.java index 729c75d53b..61338acf7d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Gene.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Gene.java @@ -3,26 +3,16 @@ package lcsb.mapviewer.model.map.species; import java.util.ArrayList; import java.util.List; -import javax.persistence.DiscriminatorValue; +import javax.persistence.*; import javax.persistence.Entity; -import javax.persistence.OneToMany; -import org.apache.logging.log4j.*; -import org.hibernate.annotations.Cascade; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithCodingRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationSite; -import lcsb.mapviewer.model.map.species.field.SpeciesWithRegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithTranscriptionSite; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; +import lcsb.mapviewer.model.map.species.field.*; /** * Entity representing gene element on the map. @@ -32,16 +22,15 @@ import lcsb.mapviewer.model.map.species.field.TranscriptionSite; */ @Entity @DiscriminatorValue("GENE") -public class Gene extends Species implements SpeciesWithCodingRegion, SpeciesWithModificationSite, SpeciesWithRegulatoryRegion, SpeciesWithTranscriptionSite { - - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(Gene.class); +public class Gene extends Species implements SpeciesWithCodingRegion, SpeciesWithModificationSite, + SpeciesWithRegulatoryRegion, SpeciesWithTranscriptionSite { /** - * + * */ private static final long serialVersionUID = 1L; - + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(Gene.class); /** * List of modifications for the Gene. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/GeneComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/GeneComparator.java index 566af4a352..f4de2b378e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/GeneComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/GeneComparator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.species; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/GenericProteinComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/GenericProteinComparator.java index d49c07d7b0..3977bc2314 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/GenericProteinComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/GenericProteinComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparator.java index 9cd67ad455..362f1c5eeb 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/IonComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/IonComparator.java index bdcc6c159a..944fb038ae 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/IonComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/IonComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/PhenotypeComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/PhenotypeComparator.java index 398feb5823..779da7f128 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/PhenotypeComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/PhenotypeComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; @@ -47,7 +48,6 @@ public class PhenotypeComparator extends Comparator<Phenotype> { return new SpeciesComparator(epsilon); } - @Override protected int internalCompare(Phenotype arg0, Phenotype arg1) { return 0; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Protein.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Protein.java index 31d26cd609..81bec9f3e7 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Protein.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Protein.java @@ -3,20 +3,13 @@ package lcsb.mapviewer.model.map.species; import java.util.ArrayList; import java.util.List; -import javax.persistence.DiscriminatorValue; +import javax.persistence.*; import javax.persistence.Entity; -import javax.persistence.OneToMany; -import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; - -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.SpeciesWithBindingRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithResidue; + +import lcsb.mapviewer.model.map.species.field.*; /** * Entity representing protein element on the map. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/ProteinComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/ProteinComparator.java index 67140df7bb..b2930d68d8 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/ProteinComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/ProteinComparator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.species; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparator.java index d00fc3f2bb..1639255c1c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Rna.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Rna.java index d34d431b1c..31d86122f0 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Rna.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Rna.java @@ -3,23 +3,14 @@ package lcsb.mapviewer.model.map.species; import java.util.ArrayList; import java.util.List; -import javax.persistence.DiscriminatorValue; +import javax.persistence.*; import javax.persistence.Entity; -import javax.persistence.OneToMany; -import org.hibernate.annotations.Cascade; +import org.hibernate.annotations.*; import org.hibernate.annotations.CascadeType; -import org.hibernate.annotations.LazyCollection; -import org.hibernate.annotations.LazyCollectionOption; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.SpeciesWithCodingRegion; -import lcsb.mapviewer.model.map.species.field.SpeciesWithModificationSite; -import lcsb.mapviewer.model.map.species.field.SpeciesWithProteinBindingDomain; +import lcsb.mapviewer.model.map.species.field.*; /** * Entity representing rna element on the map. @@ -29,7 +20,8 @@ import lcsb.mapviewer.model.map.species.field.SpeciesWithProteinBindingDomain; */ @Entity @DiscriminatorValue("RNA") -public class Rna extends Species implements SpeciesWithCodingRegion, SpeciesWithProteinBindingDomain, SpeciesWithModificationSite { +public class Rna extends Species + implements SpeciesWithCodingRegion, SpeciesWithProteinBindingDomain, SpeciesWithModificationSite { /** * @@ -89,12 +81,12 @@ public class Rna extends Species implements SpeciesWithCodingRegion, SpeciesWith public void addCodingRegion(CodingRegion codingRegion) { this.addModificationResidue(codingRegion); } - + @Override public void addProteinBindingDomain(ProteinBindingDomain codingRegion) { this.addModificationResidue(codingRegion); } - + @Override public void addModificationSite(ModificationSite codingRegion) { this.addModificationResidue(codingRegion); @@ -116,11 +108,6 @@ public class Rna extends Species implements SpeciesWithCodingRegion, SpeciesWith public List<ModificationResidue> getRegions() { return regions; } - - @Override - public List<ModificationResidue> getModificationResidues() { - return getRegions(); - } /** * @param regions @@ -131,6 +118,11 @@ public class Rna extends Species implements SpeciesWithCodingRegion, SpeciesWith this.regions = regions; } + @Override + public List<ModificationResidue> getModificationResidues() { + return getRegions(); + } + @Override public String getStringType() { return "RNA"; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/RnaComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/RnaComparator.java index 7c98838f50..2576cc6517 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/RnaComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/RnaComparator.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.model.map.species; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparator.java index 8f812206d9..67b1a8c73c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/Species.java b/model/src/main/java/lcsb/mapviewer/model/map/species/Species.java index 819aafc076..22b065e41a 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/Species.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/Species.java @@ -3,16 +3,10 @@ package lcsb.mapviewer.model.map.species; import java.util.HashSet; import java.util.Set; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.FetchType; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; - -import org.apache.logging.log4j.*; +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -405,15 +399,6 @@ public abstract class Species extends Element { return hypothetical; } - /** - * @param uniprots - * set of uniprot records for this species - * @see #uniprots - */ - public void setUniprots(Set<UniprotRecord> uniprots) { - this.uniprots = uniprots; - } - /** * @return the uniprot * @see #uniprots @@ -423,12 +408,12 @@ public abstract class Species extends Element { } /** - * @param hypothetical - * the hypothetical to set - * @see #hypothetical + * @param uniprots + * set of uniprot records for this species + * @see #uniprots */ - public void setHypothetical(Boolean hypothetical) { - this.hypothetical = hypothetical; + public void setUniprots(Set<UniprotRecord> uniprots) { + this.uniprots = uniprots; } /** @@ -441,7 +426,7 @@ public abstract class Species extends Element { /** * Is species hypothetical or not. - * + * * @return <code>true</code> if species is hypothetical, <code>false</code> * otherwise */ @@ -452,6 +437,15 @@ public abstract class Species extends Element { return hypothetical; } + /** + * @param hypothetical + * the hypothetical to set + * @see #hypothetical + */ + public void setHypothetical(Boolean hypothetical) { + this.hypothetical = hypothetical; + } + public boolean isBoundaryCondition() { if (boundaryCondition == null) { return false; @@ -478,14 +472,14 @@ public abstract class Species extends Element { return constant; } - public SbmlUnitType getSubstanceUnits() { - return substanceUnits; - } - public void setConstant(Boolean constant) { this.constant = constant; } + public SbmlUnitType getSubstanceUnits() { + return substanceUnits; + } + public void setSubstanceUnits(SbmlUnitType substanceUnits) { this.substanceUnits = substanceUnits; } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/SpeciesComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/SpeciesComparator.java index fccb26a474..5aed73eaf2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/SpeciesComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/SpeciesComparator.java @@ -5,11 +5,7 @@ import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.comparator.BooleanComparator; -import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.EnumComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.common.comparator.StringComparator; +import lcsb.mapviewer.common.comparator.*; import lcsb.mapviewer.model.map.kinetics.SbmlUnitType; /** diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparator.java index b3c798ecb4..1b9be69249 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/UnknownComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/UnknownComparator.java index bea3bf1427..1f56fbef15 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/UnknownComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/UnknownComparator.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/AbstractSiteModification.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/AbstractSiteModification.java index 2f693653e6..e924219f67 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/AbstractSiteModification.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/AbstractSiteModification.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.model.map.species.field; import java.text.DecimalFormat; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; +import javax.persistence.*; @Entity @DiscriminatorValue("ABSTRACT_SITE_MODIFICATION") diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/BindingRegion.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/BindingRegion.java index bef43a4b25..997f416da2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/BindingRegion.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/BindingRegion.java @@ -5,7 +5,8 @@ import java.io.Serializable; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Protein; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/CodingRegion.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/CodingRegion.java index 57368aa998..7d0565be2c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/CodingRegion.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/CodingRegion.java @@ -5,13 +5,11 @@ import java.io.Serializable; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; /** * This structure contains information about Coding Region for one of the diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationResidue.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationResidue.java index c40bafa2e2..1741b30c70 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationResidue.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationResidue.java @@ -3,21 +3,10 @@ package lcsb.mapviewer.model.map.species.field; import java.awt.geom.Point2D; import java.io.Serializable; -import javax.persistence.CascadeType; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; - -import org.apache.logging.log4j.*; +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Type; import lcsb.mapviewer.common.exception.NotImplementedException; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationSite.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationSite.java index 52b13b5865..ca28fe522d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationSite.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationSite.java @@ -4,10 +4,7 @@ import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; /** * This structure contains information about Modification Site for one of the diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationState.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationState.java index 2aaa570b36..23e0415049 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationState.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ModificationState.java @@ -117,6 +117,22 @@ public enum ModificationState { this.abbreviation = abbreviation; } + /** + * Returns {@link ModificationState} identified by the full name. + * + * @param name + * full name of the state + * @return {@link ModificationState} identified by the full name + */ + public static ModificationState getByName(String name) { + for (ModificationState state : values()) { + if (state.getFullName().equalsIgnoreCase(name)) { + return state; + } + } + return null; + } + /** * @return the fullName * @see #fullName @@ -133,20 +149,4 @@ public enum ModificationState { return abbreviation; } - /** - * Returns {@link ModificationState} identified by the full name. - * - * @param name - * full name of the state - * @return {@link ModificationState} identified by the full name - */ - public static ModificationState getByName(String name) { - for (ModificationState state : values()) { - if (state.getFullName().equalsIgnoreCase(name)) { - return state; - } - } - return null; - } - } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/PositionToCompartment.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/PositionToCompartment.java index 22240b09b6..bbc560cb07 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/PositionToCompartment.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/PositionToCompartment.java @@ -51,17 +51,9 @@ public enum PositionToCompartment { this.stringName = stringName; } - /** - * @return the stringName - * @see #stringName - */ - public String getStringName() { - return stringName; - } - /** * Returns {@link PositionToCompartment} based on the {@link #stringName}. - * + * * @param string * {@link #stringName} * @return {@link PositionToCompartment} based on the {@link #stringName} @@ -74,4 +66,12 @@ public enum PositionToCompartment { } return null; } + + /** + * @return the stringName + * @see #stringName + */ + public String getStringName() { + return stringName; + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomain.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomain.java index cd1f1f3657..b9f14a7de7 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomain.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/ProteinBindingDomain.java @@ -5,12 +5,11 @@ import java.io.Serializable; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.Species; +import lcsb.mapviewer.model.map.species.*; /** * This structure contains information about Protein Binding Domain for one of diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/RegulatoryRegion.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/RegulatoryRegion.java index b6fcc4ba3f..e7d769273c 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/RegulatoryRegion.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/RegulatoryRegion.java @@ -5,7 +5,8 @@ import java.io.Serializable; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Gene; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithModificationSite.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithModificationSite.java index 2cc929dde2..eeb4446dc7 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithModificationSite.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithModificationSite.java @@ -8,6 +8,6 @@ public interface SpeciesWithModificationSite extends SpeciesWithModificationResi * @param codingRegion * {@link ModificationSite } to add */ - void addModificationSite (ModificationSite modificationSite ); + void addModificationSite(ModificationSite modificationSite); } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithResidue.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithResidue.java index 46a1c305ee..61224fee90 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithResidue.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/SpeciesWithResidue.java @@ -1,8 +1,7 @@ package lcsb.mapviewer.model.map.species.field; /** - * Interface implemented by species that support {@link Residue} - * modification. + * Interface implemented by species that support {@link Residue} modification. * * @author Piotr Gawron * diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java index 6eaa87c618..2d37bb17eb 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java @@ -4,13 +4,7 @@ import java.io.Serializable; import java.util.HashMap; import java.util.Map; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.common.exception.NotImplementedException; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/TranscriptionSite.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/TranscriptionSite.java index bf7b7f3ab1..32dfa15609 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/TranscriptionSite.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/TranscriptionSite.java @@ -5,7 +5,8 @@ import java.io.Serializable; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.species.Gene; @@ -59,20 +60,9 @@ public class TranscriptionSite extends AbstractRegionModification implements Ser this.active = original.getActive(); } - @Override - public void update(AbstractRegionModification mr) { - TranscriptionSite original = (TranscriptionSite) mr; - if (original.getDirection() != null) { - this.direction = original.getDirection(); - } - if (original.getActive() != null) { - this.active = original.getActive(); - } - } - /** * Creates a copy of current object. - * + * * @return copy of the object */ public TranscriptionSite copy() { @@ -104,4 +94,15 @@ public class TranscriptionSite extends AbstractRegionModification implements Ser public String toString() { return super.toString() + "," + getActive() + "," + getDirection(); } + + @Override + public void update(AbstractRegionModification mr) { + TranscriptionSite original = (TranscriptionSite) mr; + if (original.getDirection() != null) { + this.direction = original.getDirection(); + } + if (original.getActive() != null) { + this.active = original.getActive(); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/UniprotRecord.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/UniprotRecord.java index b735554f7a..8e13690030 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/UniprotRecord.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/UniprotRecord.java @@ -1,19 +1,9 @@ package lcsb.mapviewer.model.map.species.field; import java.io.Serializable; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; +import java.util.*; + +import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -140,6 +130,14 @@ public class UniprotRecord implements Serializable { this.uniprotId = uniprotId; } + /** + * @return the species + * @see #species + */ + public Species getSpecies() { + return species; + } + /** * @param species * species to which this uniprot record belongs @@ -150,11 +148,11 @@ public class UniprotRecord implements Serializable { } /** - * @return the species - * @see #species + * @return the structures + * @see #structures */ - public Species getSpecies() { - return species; + public Set<Structure> getStructures() { + return structures; } /** @@ -166,14 +164,6 @@ public class UniprotRecord implements Serializable { this.structures = structures; } - /** - * @return the structures - * @see #structures - */ - public Set<Structure> getStructures() { - return structures; - } - public void addStructures(Collection<Structure> structures) { this.structures.addAll(structures); } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/statistics/SearchHistory.java b/model/src/main/java/lcsb/mapviewer/model/map/statistics/SearchHistory.java index 4769fddc83..cb5feef627 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/statistics/SearchHistory.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/statistics/SearchHistory.java @@ -3,13 +3,7 @@ package lcsb.mapviewer.model.map.statistics; import java.io.Serializable; import java.util.Calendar; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; /** * This object describe single search event entry. It's used for gathering some diff --git a/model/src/main/java/lcsb/mapviewer/model/map/statistics/package-info.java b/model/src/main/java/lcsb/mapviewer/model/map/statistics/package-info.java index c1e9adffde..f67a1ed035 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/statistics/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/statistics/package-info.java @@ -2,4 +2,3 @@ * Provides data structure for statistics about the usage of the map. */ package lcsb.mapviewer.model.map.statistics; - diff --git a/model/src/main/java/lcsb/mapviewer/model/package-info.java b/model/src/main/java/lcsb/mapviewer/model/package-info.java index 76cf68c54a..7034400d7d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/package-info.java @@ -6,16 +6,15 @@ * model)</li> * <li>log - where log entries of the systems are defined</li> * <li>map - where map model is defined ( - * {@link lcsb.mapviewer.model.map.model.Model Model} is the main structure in this - * package)</li> + * {@link lcsb.mapviewer.model.map.model.Model Model} is the main structure in + * this package)</li> * <li>cache (former reactome) - where cache structure is defined</li> * <li>user - structure for user definition is kept there</li> * </ul> * <br/> - * The main structure is {@link lcsb.mapviewer.model.Project}. It defines - * single project that exists in the system. Signle project can contain few map - * {@link lcsb.mapviewer.model.map.model.Model models} (few different versions of - * the map). + * The main structure is {@link lcsb.mapviewer.model.Project}. It defines single + * project that exists in the system. Signle project can contain few map + * {@link lcsb.mapviewer.model.map.model.Model models} (few different versions + * of the map). */ package lcsb.mapviewer.model; - diff --git a/model/src/main/java/lcsb/mapviewer/model/plugin/Plugin.java b/model/src/main/java/lcsb/mapviewer/model/plugin/Plugin.java index 9a7500d061..b94d12d594 100644 --- a/model/src/main/java/lcsb/mapviewer/model/plugin/Plugin.java +++ b/model/src/main/java/lcsb/mapviewer/model/plugin/Plugin.java @@ -1,18 +1,9 @@ package lcsb.mapviewer.model.plugin; import java.io.Serializable; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.CollectionTable; -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; +import java.util.*; + +import javax.persistence.*; import lcsb.mapviewer.common.comparator.IntegerComparator; @@ -25,11 +16,6 @@ import lcsb.mapviewer.common.comparator.IntegerComparator; @Entity public class Plugin implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - public static final Comparator<? super Plugin> ID_COMPARATOR = new Comparator<Plugin>() { @Override @@ -37,7 +23,10 @@ public class Plugin implements Serializable { return new IntegerComparator().compare(o1.getId(), o2.getId()); } }; - + /** + * + */ + private static final long serialVersionUID = 1L; /** * Unique database identifier. */ diff --git a/model/src/main/java/lcsb/mapviewer/model/plugin/PluginDataEntry.java b/model/src/main/java/lcsb/mapviewer/model/plugin/PluginDataEntry.java index 057bf3f38a..dc3f631604 100644 --- a/model/src/main/java/lcsb/mapviewer/model/plugin/PluginDataEntry.java +++ b/model/src/main/java/lcsb/mapviewer/model/plugin/PluginDataEntry.java @@ -2,13 +2,7 @@ package lcsb.mapviewer.model.plugin; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.model.user.User; diff --git a/model/src/main/java/lcsb/mapviewer/model/security/Privilege.java b/model/src/main/java/lcsb/mapviewer/model/security/Privilege.java index b9e0e3731d..34679a80f5 100644 --- a/model/src/main/java/lcsb/mapviewer/model/security/Privilege.java +++ b/model/src/main/java/lcsb/mapviewer/model/security/Privilege.java @@ -34,11 +34,15 @@ public class Privilege implements Serializable { } @Override - public String toString() { + public int hashCode() { + if (type == null) { + return 0; + } + if (isObjectPrivilege()) { - return type.name() + ":" + objectId; + return Objects.hash(type, objectId); } else { - return type.name(); + return type.hashCode(); } } @@ -54,15 +58,11 @@ public class Privilege implements Serializable { } @Override - public int hashCode() { - if (type == null) { - return 0; - } - + public String toString() { if (isObjectPrivilege()) { - return Objects.hash(type, objectId); + return type.name() + ":" + objectId; } else { - return type.hashCode(); + return type.name(); } } diff --git a/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationElementType.java b/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationElementType.java index a20b2bd24d..5f0234b09d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationElementType.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationElementType.java @@ -216,7 +216,8 @@ public enum ConfigurationElementType { DEFAULT_WRITE_PROJECT("Default user privilege for: " + PrivilegeType.WRITE_PROJECT.getDescription(), "false", ConfigurationElementEditType.BOOLEAN, false, ConfigurationElementTypeGroup.DEFAULT_USER_PRIVILEGES), - DEFAULT_CAN_CREATE_OVERLAYS("Default user privilege for: " + PrivilegeType.CAN_CREATE_OVERLAYS.getDescription(), "true", + DEFAULT_CAN_CREATE_OVERLAYS("Default user privilege for: " + PrivilegeType.CAN_CREATE_OVERLAYS.getDescription(), + "true", ConfigurationElementEditType.BOOLEAN, false, ConfigurationElementTypeGroup.DEFAULT_USER_PRIVILEGES), SHOW_REACTION_TYPE("Show reaction type", "true", ConfigurationElementEditType.BOOLEAN, false, diff --git a/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationOption.java b/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationOption.java index 2c5c863b00..dacbc2c443 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationOption.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/ConfigurationOption.java @@ -2,12 +2,7 @@ package lcsb.mapviewer.model.user; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; /** * This class represents one configurable parameter of the system. diff --git a/model/src/main/java/lcsb/mapviewer/model/user/User.java b/model/src/main/java/lcsb/mapviewer/model/user/User.java index 354c2d091e..981f594fb4 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/User.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/User.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.user; -import java.awt.Color; +import java.awt.*; import java.io.Serializable; import java.util.*; diff --git a/model/src/main/java/lcsb/mapviewer/model/user/UserAnnotationSchema.java b/model/src/main/java/lcsb/mapviewer/model/user/UserAnnotationSchema.java index 0be86fc4ef..566a10e604 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/UserAnnotationSchema.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/UserAnnotationSchema.java @@ -1,21 +1,12 @@ package lcsb.mapviewer.model.user; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import javax.persistence.OrderBy; - -import org.apache.logging.log4j.*; +import java.util.*; + +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/user/UserClassAnnotators.java b/model/src/main/java/lcsb/mapviewer/model/user/UserClassAnnotators.java index a0bbe8bf31..49088f1daf 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/UserClassAnnotators.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/UserClassAnnotators.java @@ -4,13 +4,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; +import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -142,6 +136,16 @@ public class UserClassAnnotators implements Serializable { this.className = className; } + /** + * Sets {@link #className}. + * + * @param clazz + * new {@link #className} value + */ + public void setClassName(Class<?> clazz) { + setClassName(clazz.getCanonicalName()); + } + /** * @return the annotators * @see #annotators @@ -167,16 +171,6 @@ public class UserClassAnnotators implements Serializable { fixAnnotatorsOrder(); } - /** - * Sets {@link #className}. - * - * @param clazz - * new {@link #className} value - */ - public void setClassName(Class<?> clazz) { - setClassName(clazz.getCanonicalName()); - } - /** * Adds annotator to {@link #annotators list of annotators}. * diff --git a/model/src/main/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotations.java b/model/src/main/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotations.java index 65c9eea443..9d75f1d499 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotations.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/UserClassRequiredAnnotations.java @@ -1,24 +1,12 @@ package lcsb.mapviewer.model.user; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToOne; -import javax.persistence.OrderColumn; - -import org.apache.logging.log4j.*; +import java.util.*; + +import javax.persistence.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.MiriamType; @@ -136,6 +124,16 @@ public class UserClassRequiredAnnotations implements Serializable { this.className = className; } + /** + * Sets {@link #className}. + * + * @param clazz + * new {@link #className} value + */ + public void setClassName(Class<?> clazz) { + setClassName(clazz.getCanonicalName()); + } + /** * @return the id * @see #id @@ -153,16 +151,6 @@ public class UserClassRequiredAnnotations implements Serializable { this.id = id; } - /** - * Sets {@link #className}. - * - * @param clazz - * new {@link #className} value - */ - public void setClassName(Class<?> clazz) { - setClassName(clazz.getCanonicalName()); - } - /** * Adds a type into {@link #requiredMiriamTypes list of required annotations}. * diff --git a/model/src/main/java/lcsb/mapviewer/model/user/UserClassValidAnnotations.java b/model/src/main/java/lcsb/mapviewer/model/user/UserClassValidAnnotations.java index 97907dd6aa..3dfd5eeb72 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/UserClassValidAnnotations.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/UserClassValidAnnotations.java @@ -1,22 +1,9 @@ package lcsb.mapviewer.model.user; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToOne; -import javax.persistence.OrderColumn; +import java.util.*; + +import javax.persistence.*; import lcsb.mapviewer.model.map.MiriamType; @@ -132,6 +119,16 @@ public class UserClassValidAnnotations implements Serializable { this.className = className; } + /** + * Sets {@link #className} value. + * + * @param clazz + * new {@link #className} value + */ + public void setClassName(Class<?> clazz) { + setClassName(clazz.getCanonicalName()); + } + /** * @return the id * @see #id @@ -149,16 +146,6 @@ public class UserClassValidAnnotations implements Serializable { this.id = id; } - /** - * Sets {@link #className} value. - * - * @param clazz - * new {@link #className} value - */ - public void setClassName(Class<?> clazz) { - setClassName(clazz.getCanonicalName()); - } - /** * Adds new valid annotation to {@link #validMiriamTypes}. * diff --git a/model/src/main/java/lcsb/mapviewer/model/user/UserGuiPreference.java b/model/src/main/java/lcsb/mapviewer/model/user/UserGuiPreference.java index 4b1dffd79d..1d933adf9e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/UserGuiPreference.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/UserGuiPreference.java @@ -2,14 +2,7 @@ package lcsb.mapviewer.model.user; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; +import javax.persistence.*; /** * This class defines GUI preference for the {@link User}. diff --git a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorConfigParameter.java b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorConfigParameter.java index cf798a17be..1b37d2435d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorConfigParameter.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorConfigParameter.java @@ -2,10 +2,7 @@ package lcsb.mapviewer.model.user.annotator; import java.io.Serializable; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; +import javax.persistence.*; import lcsb.mapviewer.model.user.AnnotatorParamDefinition; diff --git a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorData.java b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorData.java index ee31625762..7b07e43df1 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorData.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorData.java @@ -4,14 +4,7 @@ import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToOne; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; +import javax.persistence.*; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; diff --git a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorInputParameter.java b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorInputParameter.java index 4d21e4bf7e..68e4cd2613 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorInputParameter.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorInputParameter.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.model.user.annotator; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; +import javax.persistence.*; import lcsb.mapviewer.model.map.MiriamType; diff --git a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorOutputParameter.java b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorOutputParameter.java index 1bfbaa5297..9ed5bd4f5f 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorOutputParameter.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorOutputParameter.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.model.user.annotator; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; +import javax.persistence.*; import lcsb.mapviewer.model.map.MiriamType; @@ -33,7 +30,7 @@ public class AnnotatorOutputParameter extends AnnotatorParameter { */ protected AnnotatorOutputParameter() { } - + public AnnotatorOutputParameter(BioEntityField field) { this.field = field; } @@ -51,8 +48,8 @@ public class AnnotatorOutputParameter extends AnnotatorParameter { } @Override - public String toString() { - return "[" + field + "," + identifierType + "]"; + public int hashCode() { + return this.toString().hashCode(); } @Override @@ -62,9 +59,9 @@ public class AnnotatorOutputParameter extends AnnotatorParameter { } return this.toString().equals(o.toString()); } - + @Override - public int hashCode() { - return this.toString().hashCode(); + public String toString() { + return "[" + field + "," + identifierType + "]"; } } diff --git a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameter.java b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameter.java index 431da35b7d..3e456cef74 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameter.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameter.java @@ -2,16 +2,7 @@ package lcsb.mapviewer.model.user.annotator; import java.io.Serializable; -import javax.persistence.DiscriminatorColumn; -import javax.persistence.DiscriminatorType; -import javax.persistence.DiscriminatorValue; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.ManyToOne; +import javax.persistence.*; import lcsb.mapviewer.model.user.UserAnnotationSchema; diff --git a/model/src/main/java/lcsb/mapviewer/model/user/annotator/BioEntityField.java b/model/src/main/java/lcsb/mapviewer/model/user/annotator/BioEntityField.java index 117be90f93..40d9e06b01 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/annotator/BioEntityField.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/annotator/BioEntityField.java @@ -31,7 +31,7 @@ public enum BioEntityField { private BioEntityField(String fieldName) { this.fieldName = fieldName; } - + public static String getFieldValueForBioEntity(BioEntity bioEntity, BioEntityField field) { if (field.equals(ABBREVIATION)) { return bioEntity.getAbbreviation(); diff --git a/model/src/main/java/lcsb/mapviewer/model/user/package-info.java b/model/src/main/java/lcsb/mapviewer/model/user/package-info.java index d5dd86f858..18182990e2 100644 --- a/model/src/main/java/lcsb/mapviewer/model/user/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/model/user/package-info.java @@ -2,4 +2,3 @@ * Contains structures used for modeling users, privileges, etc. */ package lcsb.mapviewer.model.user; - diff --git a/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java b/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java index 5d50a196b5..a3dbe51f35 100644 --- a/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java +++ b/model/src/main/java/lcsb/mapviewer/modelutils/map/ElementUtils.java @@ -1,12 +1,6 @@ package lcsb.mapviewer.modelutils.map; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -50,10 +44,28 @@ public final class ElementUtils { @SuppressWarnings("unused") private static Logger logger = LogManager.getLogger(ElementUtils.class); + /** + * @param elementClasses + * the elementClasses to set + * @see #elementClasses + */ + protected static void setElementClasses(Map<String, Class<? extends Element>> elementClasses) { + ElementUtils.elementClasses = elementClasses; + } + + /** + * @param reactionClasses + * the reactionClasses to set + * @see #reactionClasses + */ + protected static void setReactionClasses(Map<String, Class<? extends Reaction>> reactionClasses) { + ElementUtils.reactionClasses = reactionClasses; + } + /** * This method return tag that identifies {@link BioEntity}. This tag should be * used in warning messages. - * + * * @param element * tag for this element is created * @return tag that identifies element @@ -65,7 +77,7 @@ public final class ElementUtils { /** * This method return tag that identifies {@link BioEntity}. This tag should be * used in warning messages. - * + * * @param element * tag for this element is created * @param annotator @@ -90,7 +102,7 @@ public final class ElementUtils { /** * Returns {@link #annotatedObjectTree}. - * + * * @return {@link #annotatedObjectTree} */ public ClassTreeNode getAnnotatedElementClassTree() { @@ -146,7 +158,7 @@ public final class ElementUtils { /** * Returns list of classes that extends {@link Element} class, but don't have * children (leaves in the hierarchy tree). - * + * * @return list of classes that extends {@link Element} class, but don't have * children (leaves in the hierarchy tree) */ @@ -209,7 +221,7 @@ public final class ElementUtils { /** * Returns a {@link Class} that extends {@link BioEntity} for a given name. - * + * * @param name * name of the class * @return {@link Class} that extends {@link BioEntity} for a given name @@ -227,7 +239,7 @@ public final class ElementUtils { /** * Return list of {@link Reaction} classes that are available in the system. - * + * * @return list of {@link Reaction} classes that are available in the system */ public List<Class<? extends Reaction>> getAvailableReactionSubclasses() { @@ -240,24 +252,6 @@ public final class ElementUtils { return result; } - /** - * @param elementClasses - * the elementClasses to set - * @see #elementClasses - */ - protected static void setElementClasses(Map<String, Class<? extends Element>> elementClasses) { - ElementUtils.elementClasses = elementClasses; - } - - /** - * @param reactionClasses - * the reactionClasses to set - * @see #reactionClasses - */ - protected static void setReactionClasses(Map<String, Class<? extends Reaction>> reactionClasses) { - ElementUtils.reactionClasses = reactionClasses; - } - public String getElementTag(ReactionNode node) { String reactionPrefix = ""; if (node.getReaction() != null) { diff --git a/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java b/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java index dce61de4bc..984a8b7140 100644 --- a/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java +++ b/model/src/main/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMap.java @@ -2,14 +2,7 @@ package lcsb.mapviewer.modelutils.map; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Chemical; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; +import lcsb.mapviewer.model.map.species.*; /** * List of {@link BioEntity} that must be annotated with at least one diff --git a/model/src/main/java/lcsb/mapviewer/modelutils/map/package-info.java b/model/src/main/java/lcsb/mapviewer/modelutils/map/package-info.java index 1e96e287fb..7e3ed7cb18 100644 --- a/model/src/main/java/lcsb/mapviewer/modelutils/map/package-info.java +++ b/model/src/main/java/lcsb/mapviewer/modelutils/map/package-info.java @@ -2,4 +2,3 @@ * Contains util classe for map modeling structures. */ package lcsb.mapviewer.modelutils.map; - diff --git a/model/src/test/java/lcsb/mapviewer/AllTests.java b/model/src/test/java/lcsb/mapviewer/AllTests.java index d7ed5099a5..6ef867cda0 100644 --- a/model/src/test/java/lcsb/mapviewer/AllTests.java +++ b/model/src/test/java/lcsb/mapviewer/AllTests.java @@ -1,12 +1,12 @@ package lcsb.mapviewer; -import lcsb.mapviewer.model.AllModelTests; -import lcsb.mapviewer.modelutils.map.AllMapUtilTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.model.AllModelTests; +import lcsb.mapviewer.modelutils.map.AllMapUtilTests; + @RunWith(Suite.class) @SuiteClasses({ AllModelTests.class, AllMapUtilTests.class, diff --git a/model/src/test/java/lcsb/mapviewer/model/ProjectStatusTest.java b/model/src/test/java/lcsb/mapviewer/model/ProjectStatusTest.java index 0d4cdcdfeb..5e5d48ef9b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/ProjectStatusTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/ProjectStatusTest.java @@ -2,29 +2,27 @@ package lcsb.mapviewer.model; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ProjectStatusTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (ProjectStatus type : ProjectStatus.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (ProjectStatus type : ProjectStatus.values()) { + assertNotNull(type); - // for coverage tests - ProjectStatus.valueOf(type.name()); - type.toString(); - } - } + // for coverage tests + ProjectStatus.valueOf(type.name()); + type.toString(); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java b/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java index 6a5fb5d27d..ef69150a42 100644 --- a/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/ProjectTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/AllCacheTests.java b/model/src/test/java/lcsb/mapviewer/model/cache/AllCacheTests.java index 5eca526011..fdd791b623 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/AllCacheTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/AllCacheTests.java @@ -6,10 +6,10 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ BigFileEntryTest.class, - CacheQueryTest.class, - CacheTypeTest.class, - UploadedFileEntryTest.class, - + CacheQueryTest.class, + CacheTypeTest.class, + UploadedFileEntryTest.class, + }) public class AllCacheTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java index 049e72efca..1807d22551 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/BigFileEntryTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Calendar; diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java index 8c1daeff24..48de8af108 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/CacheQueryTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Calendar; diff --git a/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java index 77bd9d8ecc..c551027e18 100644 --- a/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/cache/CacheTypeTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/AllGraphicsTests.java b/model/src/test/java/lcsb/mapviewer/model/graphics/AllGraphicsTests.java index 8f3f0f4e75..345308362e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/AllGraphicsTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/AllGraphicsTests.java @@ -6,11 +6,11 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ArrowTypeDataComparatorTest.class, - ArrowTypeDataTest.class, - ArrowTypeTest.class, - LineTypeTest.class, - PolylineDataTest.class, - PolylineDataComparatorTest.class, + ArrowTypeDataTest.class, + ArrowTypeTest.class, + LineTypeTest.class, + PolylineDataTest.class, + PolylineDataComparatorTest.class, }) public class AllGraphicsTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java index 764446834e..dd03bcfc5f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java index 6a5dc9213e..edacbfa029 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeDataTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeTest.java index d8701436b3..82a482f222 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/ArrowTypeTest.java @@ -1,29 +1,27 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ArrowTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (ArrowType type : ArrowType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (ArrowType type : ArrowType.values()) { + assertNotNull(type); - // for coverage tests - ArrowType.valueOf(type.toString()); - } - } + // for coverage tests + ArrowType.valueOf(type.toString()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/LineTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/LineTypeTest.java index 8d16c8f510..e8f8d280b0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/LineTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/LineTypeTest.java @@ -2,29 +2,27 @@ package lcsb.mapviewer.model.graphics; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class LineTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (LineType type : LineType.values()) { - assertNotNull(type); - assertNotNull(type.getStroke()); + @Test + public void testValidValues() { + for (LineType type : LineType.values()) { + assertNotNull(type); + assertNotNull(type.getStroke()); - // for coverage tests - LineType.valueOf(type.toString()); - } - } + // for coverage tests + LineType.valueOf(type.toString()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java index e01b64d290..3572aa0414 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java index c2478f76a9..b79771ae7d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/graphics/PolylineDataTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.model.graphics; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.awt.geom.*; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java index c18826c304..b21e990c59 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/CommentTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/MiriamRelationTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/MiriamRelationTypeTest.java index 17e609addf..ff88ca6c04 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/MiriamRelationTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/MiriamRelationTypeTest.java @@ -3,36 +3,34 @@ package lcsb.mapviewer.model.map; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class MiriamRelationTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (MiriamRelationType type : MiriamRelationType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (MiriamRelationType type : MiriamRelationType.values()) { + assertNotNull(type); - // for coverage tests - MiriamRelationType.valueOf(type.toString()); - assertNotNull(type.getStringRepresentation()); + // for coverage tests + MiriamRelationType.valueOf(type.toString()); + assertNotNull(type.getStringRepresentation()); - } - } + } + } - @Test - public void testGetTypeByString() { - assertNull(MiriamRelationType.getTypeByStringRepresentation("DSfsdfs")); - assertNotNull(MiriamRelationType.getTypeByStringRepresentation("bqbiol:occures")); - } + @Test + public void testGetTypeByString() { + assertNull(MiriamRelationType.getTypeByStringRepresentation("DSfsdfs")); + assertNotNull(MiriamRelationType.getTypeByStringRepresentation("bqbiol:occures")); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java index 647b22bcc3..a3905139c5 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/MiriamTypeNameComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java index 3dd25d4491..e0956ea0be 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageComparatorTest.java @@ -1,12 +1,12 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class OverviewImageComparatorTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java index 0373063248..72a9bd49fb 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkComparatorTest.java @@ -1,12 +1,12 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class OverviewImageLinkComparatorTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java index 7d03e3da8f..355d70f952 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageLinkTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; @@ -8,7 +8,6 @@ import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class OverviewImageLinkTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java index 3de5cdfaae..7761a75329 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewImageTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; @@ -11,7 +12,6 @@ import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class OverviewImageTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java index acd59e7d1a..59fb3837c8 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java index fff035e5f8..bfffc1d1fc 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewLinkTest.java @@ -1,12 +1,11 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class OverviewLinkTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java index b6a85d55f2..d2adb4fa62 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewModelLinkComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java b/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java index 7cb33dff1a..23efe21c6d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/OverviewSearchLinkTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java b/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java index c7475b44e6..fe7f0b30e0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/SearchIndexTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/AllCompartmentTests.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/AllCompartmentTests.java index 8fab2b8b02..a3855e0d1b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/AllCompartmentTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/AllCompartmentTests.java @@ -6,14 +6,14 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ BottomSquareCompartmentTest.class, - CompartmentComparatorTest.class, - CompartmentTest.class, - LeftSquareCompartmentTest.class, - OvalCompartmentTest.class, - PathwayCompartmentTest.class, - RightSquareCompartmentTest.class, - SquareCompartmentTest.class, - TopSquareCompartmentTest.class, + CompartmentComparatorTest.class, + CompartmentTest.class, + LeftSquareCompartmentTest.class, + OvalCompartmentTest.class, + PathwayCompartmentTest.class, + RightSquareCompartmentTest.class, + SquareCompartmentTest.class, + TopSquareCompartmentTest.class, }) public class AllCompartmentTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java index 6ecb713c70..fad7793d50 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/BottomSquareCompartmentTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java index 1659c72abf..744def3b48 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/CompartmentComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import org.apache.logging.log4j.LogManager; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java index 1b079db050..ebcb694688 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/LeftSquareCompartmentTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java index afe846f021..097f5b3e20 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/OvalCompartmentTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java index a71eeb7e1b..255738b934 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/PathwayCompartmentTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java index bf76defcf6..bcc0b4c321 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/RightSquareCompartmentTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java index f01d92e601..17b8e15c30 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/SquareCompartmentTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java index 58d1b1201d..7c114cfaab 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/compartment/TopSquareCompartmentTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.compartment; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/AllKineticsTests.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/AllKineticsTests.java index 51d54bf708..339af44301 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/AllKineticsTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/AllKineticsTests.java @@ -15,7 +15,7 @@ import org.junit.runners.Suite.SuiteClasses; SbmlUnitComparatorTest.class, SbmlUnitTypeFactorTest.class, SbmlUnitTypeFactorComparatorTest.class, - }) +}) public class AllKineticsTests { } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionTest.java index f733ad8795..840a875694 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlFunctionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.kinetics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsTest.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsTest.java index 8e22d3bd72..8ff3c5fda3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlKineticsTest.java @@ -17,7 +17,7 @@ public class SbmlKineticsTest { kinetics.addParameter(parameter); assertEquals(kinetics.getParameters().iterator().next(), parameter); } - + @Test public void testAddFunction() { SbmlFunction function = new SbmlFunction(""); @@ -27,7 +27,7 @@ public class SbmlKineticsTest { assertEquals(1, kinetics.getArguments().size()); assertEquals(kinetics.getArguments().iterator().next(), function); } - + @Test public void testGetArguments() { SbmlParameter parameter = new SbmlParameter("k1"); @@ -39,16 +39,16 @@ public class SbmlKineticsTest { @Test public void testAddElement() { Element protein = new GenericProtein("s1"); - + SbmlKinetics kinetics = new SbmlKinetics(); kinetics.addElement(protein); assertEquals(kinetics.getArguments().get(0), protein); } - + @Test public void testSetDefinition() { String definition = "<lambda><bvar><ci> x </ci></bvar></lambda>"; - + SbmlKinetics kinetics = new SbmlKinetics(); kinetics.setDefinition(definition); assertEquals(definition, kinetics.getDefinition()); @@ -66,6 +66,4 @@ public class SbmlKineticsTest { assertEquals(0, comparator.compare(copy, kinetics)); } - - } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterComparatorTest.java index e803cbd9ca..d452fc291e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.kinetics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.Test; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterTest.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterTest.java index 861d98a596..17a0a82a11 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlParameterTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.kinetics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparatorTest.java index 284f89a936..e392f1a519 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.kinetics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -39,7 +40,8 @@ public class SbmlUnitComparatorTest { public void testCompareUnitTypes() { SbmlUnit parameter = createUnit(); SbmlUnit parameter2 = createUnit(); - parameter.addUnitTypeFactor(new SbmlUnitTypeFactor(SbmlUnitType.AMPERE, 1, 1, 1));; + parameter.addUnitTypeFactor(new SbmlUnitTypeFactor(SbmlUnitType.AMPERE, 1, 1, 1)); + ; assertTrue(0 != comparator.compare(parameter, parameter2)); } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorTest.java index 83ec875f1f..494e0396e2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/kinetics/SbmlUnitTypeFactorTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.kinetics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/AllLayoutTests.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/AllLayoutTests.java index a0c2e8cc67..d2c96db83c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/AllLayoutTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/AllLayoutTests.java @@ -8,17 +8,17 @@ import lcsb.mapviewer.model.map.layout.graphics.AllGraphicsTests; @RunWith(Suite.class) @SuiteClasses({ AllGraphicsTests.class, - ColorSchemaTest.class, - ElementGroupTest.class, - GenericColorSchemaTest.class, - GeneVariationTest.class, - GeneVariationColorSchemaTest.class, - InvalidColorSchemaExceptionTest.class, - LayoutStatusTest.class, - LayoutTest.class, - ReferenceGenomeGeneMappingTest.class, - ReferenceGenomeTest.class, - ReferenceGenomeTypeTest.class, + ColorSchemaTest.class, + ElementGroupTest.class, + GenericColorSchemaTest.class, + GeneVariationTest.class, + GeneVariationColorSchemaTest.class, + InvalidColorSchemaExceptionTest.class, + LayoutStatusTest.class, + LayoutTest.class, + ReferenceGenomeGeneMappingTest.class, + ReferenceGenomeTest.class, + ReferenceGenomeTypeTest.class, }) public class AllLayoutTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java index 6c57476266..591cf782ce 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ColorSchemaTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -import java.awt.Color; +import java.awt.*; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java index c362be4c24..1ecba9d5de 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ElementGroupTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java index 1077458009..0c61764e9f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationColorSchemaTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; @@ -11,7 +11,6 @@ import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class GeneVariationColorSchemaTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java index bd9c5b0f5e..aeaf2a290b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/GeneVariationTest.java @@ -1,13 +1,12 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class GeneVariationTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java index 8b8be18c9b..3de4e0dbc2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/GenericColorSchemaTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java index ecbf480532..181292d795 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/InvalidColorSchemaExceptionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutStatusTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutStatusTest.java index 7517897fd9..46aa2da065 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutStatusTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutStatusTest.java @@ -2,29 +2,27 @@ package lcsb.mapviewer.model.map.layout; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class LayoutStatusTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (LayoutStatus type : LayoutStatus.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (LayoutStatus type : LayoutStatus.values()) { + assertNotNull(type); - // for coverage tests - LayoutStatus.valueOf(type.toString()); - assertNotNull(type.getCommonName()); - } - } + // for coverage tests + LayoutStatus.valueOf(type.toString()); + assertNotNull(type.getCommonName()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java index c898f57198..cc037a25e6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/LayoutTest.java @@ -10,7 +10,6 @@ import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.cache.UploadedFileEntry; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class LayoutTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java index c914d44e5f..2b90b82c27 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeGeneMappingTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java index b9182eee56..6c1937cf0e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTypeTest.java index 1b4c5c817b..2a9bfd244b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/ReferenceGenomeTypeTest.java @@ -1,35 +1,32 @@ package lcsb.mapviewer.model.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ReferenceGenomeTypeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (ReferenceGenomeType type : ReferenceGenomeType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (ReferenceGenomeType type : ReferenceGenomeType.values()) { + assertNotNull(type); - // for coverage tests - ReferenceGenomeType.valueOf(type.toString()); - assertNotNull(type.getHomepage()); - } - } + // for coverage tests + ReferenceGenomeType.valueOf(type.toString()); + assertNotNull(type.getHomepage()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/AllGraphicsTests.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/AllGraphicsTests.java index 6c08e4c7f1..aea5168b67 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/AllGraphicsTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/AllGraphicsTests.java @@ -6,13 +6,13 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ LayerComparatorTest.class, - LayerOvalComparatorTest.class, - LayerOvalTest.class, - LayerRectComparatorTest.class, - LayerRectTest.class, - LayerTest.class, - LayerTextComparatorTest.class, - LayerTextTest.class, + LayerOvalComparatorTest.class, + LayerOvalTest.class, + LayerRectComparatorTest.class, + LayerRectTest.class, + LayerTest.class, + LayerTextComparatorTest.class, + LayerTextTest.class, }) public class AllGraphicsTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java index 70ddddbe43..56ad191b17 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java index d6f37724b1..42b7f4346f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java index 971a65b5ba..b9f6e09693 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerOvalTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.model.map.layout.graphics; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java index 5c3c1f6e84..491885d019 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java index d89cd63f29..6f5fa07785 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerRectTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.model.map.layout.graphics; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java index 6d0233362e..ba66652055 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/layout/graphics/LayerTextComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.layout.graphics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/AllModelTests.java b/model/src/test/java/lcsb/mapviewer/model/map/model/AllModelTests.java index 7251f41bdf..b0100ab974 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/AllModelTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/AllModelTests.java @@ -6,15 +6,15 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ElementSubmodelConnectionComparatorTest.class, - ElementSubmodelConnectionTest.class, - ModelComparatorTest.class, - ModelDataTest.class, - ModelFullIndexedTest.class, - ModelSubmodelConnectionComparatorTest.class, - ModelSubmodelConnectionTest.class, - ModelTest.class, - SubmodelConnectionComparatorTest.class, - SubmodelTypeTest.class, + ElementSubmodelConnectionTest.class, + ModelComparatorTest.class, + ModelDataTest.class, + ModelFullIndexedTest.class, + ModelSubmodelConnectionComparatorTest.class, + ModelSubmodelConnectionTest.class, + ModelTest.class, + SubmodelConnectionComparatorTest.class, + SubmodelTypeTest.class, }) public class AllModelTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java index cd76b150b5..66936298e4 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java index da061855ec..3f17299da5 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ElementSubmodelConnectionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; @@ -8,7 +8,6 @@ import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class ElementSubmodelConnectionTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java index 5c201cd3aa..99e40cc5a1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelComparatorTest.java @@ -1,7 +1,8 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; import java.util.Calendar; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java index 0f4f321b6c..b0fe7f6665 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelFullIndexedTest.java @@ -471,34 +471,34 @@ public class ModelFullIndexedTest extends ModelTestFunctions { public void testGetters() { Model model = new ModelFullIndexed(null); - double width = 12.0; - int widthInt = 12; - String widthStr = "12.0"; - double height = 13.0; - String heightStr = "13.0"; - int heightInt = 13; - Set<Element> elements = new HashSet<>(); - int zoomLevels = 98; - int tileSize = 1024; - String idModel = "model_ID"; - - model.setWidth(widthStr); - assertEquals(width, model.getWidth(), Configuration.EPSILON); - model.setWidth(0.0); - model.setWidth(width); - assertEquals(width, model.getWidth(), Configuration.EPSILON); - model.setWidth(0.0); - model.setWidth(widthInt); - assertEquals(width, model.getWidth(), Configuration.EPSILON); - - model.setHeight(heightStr); - assertEquals(height, model.getHeight(), Configuration.EPSILON); - model.setHeight(0.0); - model.setHeight(height); - assertEquals(height, model.getHeight(), Configuration.EPSILON); - model.setHeight(0.0); - model.setHeight(heightInt); - assertEquals(height, model.getHeight(), Configuration.EPSILON); + double width = 12.0; + int widthInt = 12; + String widthStr = "12.0"; + double height = 13.0; + String heightStr = "13.0"; + int heightInt = 13; + Set<Element> elements = new HashSet<>(); + int zoomLevels = 98; + int tileSize = 1024; + String idModel = "model_ID"; + + model.setWidth(widthStr); + assertEquals(width, model.getWidth(), Configuration.EPSILON); + model.setWidth(0.0); + model.setWidth(width); + assertEquals(width, model.getWidth(), Configuration.EPSILON); + model.setWidth(0.0); + model.setWidth(widthInt); + assertEquals(width, model.getWidth(), Configuration.EPSILON); + + model.setHeight(heightStr); + assertEquals(height, model.getHeight(), Configuration.EPSILON); + model.setHeight(0.0); + model.setHeight(height); + assertEquals(height, model.getHeight(), Configuration.EPSILON); + model.setHeight(0.0); + model.setHeight(heightInt); + assertEquals(height, model.getHeight(), Configuration.EPSILON); model.setElements(elements); assertEquals(elements, model.getElements()); diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java index 90dc66bf24..f6ad4c6110 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java index ad99e667a2..7c529ec2d0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/ModelSubmodelConnectionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; @@ -8,7 +9,6 @@ import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.layout.graphics.Layer; public class ModelSubmodelConnectionTest extends ModelTestFunctions { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java index 88330e931c..9903d48c99 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelConnectionComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelTypeTest.java index 202a2f1996..50d04b87c1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/model/SubmodelTypeTest.java @@ -2,29 +2,27 @@ package lcsb.mapviewer.model.map.model; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class SubmodelTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (SubmodelType type : SubmodelType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (SubmodelType type : SubmodelType.values()) { + assertNotNull(type); - // for coverage tests - SubmodelType.valueOf(type.toString()); - assertNotNull(type.getCommonName()); - } - } + // for coverage tests + SubmodelType.valueOf(type.toString()); + assertNotNull(type.getCommonName()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/AllModifierTests.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/AllModifierTests.java index e2533ce33f..ec897a1f83 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/AllModifierTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/AllModifierTests.java @@ -6,12 +6,12 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ CatalysisTest.class, - InhibitionTest.class, - ModulationTest.class, - PhysicalStimulationTest.class, - TriggerTest.class, - UnknownCatalysisTest.class, - UnknownInhibitionTest.class, + InhibitionTest.class, + ModulationTest.class, + PhysicalStimulationTest.class, + TriggerTest.class, + UnknownCatalysisTest.class, + UnknownInhibitionTest.class, }) public class AllModifierTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java index 5b149190ac..27f4153c13 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/CatalysisTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java index 52775701ec..d83e8e7dac 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/InhibitionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java index cb0231984a..1da8e7ec43 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/ModulationTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java index e20499a2f3..be85348aff 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulationTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java index f5c6524aef..e7c44be2a3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/TriggerTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java index e708b26dc7..0eba189132 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysisTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java index 7a9e707905..c944de9fd2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/modifier/UnknownInhibitionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.modifier; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java index a4b850daa8..eafe33164f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AllReactionTests.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AllReactionTests.java index 4f7ccaa125..91b03aba7b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AllReactionTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AllReactionTests.java @@ -1,30 +1,30 @@ package lcsb.mapviewer.model.map.reaction; -import lcsb.mapviewer.model.map.reaction.type.AllReactionTypeTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.model.map.reaction.type.AllReactionTypeTests; + @RunWith(Suite.class) @SuiteClasses({ AbstractNodeComparatorTest.class, - AllReactionTypeTests.class, - AndOperatorTest.class, - AssociationOperatorTest.class, - DissociationOperatorTest.class, - ModifierTest.class, - NandOperatorTest.class, - NodeOperatorComparatorTest.class, - NodeOperatorTest.class, - OrOperatorTest.class, - ProductTest.class, - ReactantTest.class, - ReactionComparatorTest.class, - ReactionNodeComparatorTest.class, - ReactionTest.class, - SplitOperatorTest.class, - TruncationOperatorTest.class, - UnknownOperatorTest.class, + AllReactionTypeTests.class, + AndOperatorTest.class, + AssociationOperatorTest.class, + DissociationOperatorTest.class, + ModifierTest.class, + NandOperatorTest.class, + NodeOperatorComparatorTest.class, + NodeOperatorTest.class, + OrOperatorTest.class, + ProductTest.class, + ReactantTest.class, + ReactionComparatorTest.class, + ReactionNodeComparatorTest.class, + ReactionTest.class, + SplitOperatorTest.class, + TruncationOperatorTest.class, + UnknownOperatorTest.class, }) public class AllReactionTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java index 406c3fcbca..82dc3caf4d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/AssociationOperatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java index 7738614412..772703cf78 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/DissociationOperatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java index 603d7bbe74..36b37a8411 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ModifierTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java index c5dd68f2a1..7d8d00f2c6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NandOperatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java index 8f5d37ff02..c8f648c080 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorMock.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorMock.java index 73a6e2ee50..caf7496987 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorMock.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/NodeOperatorMock.java @@ -4,27 +4,27 @@ import lcsb.mapviewer.common.exception.NotImplementedException; public class NodeOperatorMock extends NodeOperator { - /** - * - */ - private static final long serialVersionUID = 1L; - - public NodeOperatorMock(NodeOperator operator) { - super(operator); - } - - public NodeOperatorMock() { - super(); - } - - @Override - public String getOperatorText() { - return "mock string"; - } - - @Override - public AbstractNode copy() { - throw new NotImplementedException(); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + public NodeOperatorMock(NodeOperator operator) { + super(operator); + } + + public NodeOperatorMock() { + super(); + } + + @Override + public String getOperatorText() { + return "mock string"; + } + + @Override + public AbstractNode copy() { + throw new NotImplementedException(); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java index 570a5b6e98..bb47ea5eca 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/OrOperatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java index 27de69631a..11170ed9e0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ProductTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java index 3d3c1aa3a3..4c9c5aa6ab 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactantTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java index 2cb92cb915..5db7e0201d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java index 6d8ff0496c..bbecd9f08d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/ReactionNodeComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java index aea738e451..97a0533bcf 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/SplitOperatorTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java index 29b6fdfcf9..e3d67141a1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/TruncationOperatorTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java index 4e182a1413..7c9098e0bd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/UnknownOperatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java index 2a3c6954a8..cf4f510fc6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/DissociationReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java index 4c71a76c5d..32a5414546 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/HeterodimerAssociationReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java index 485be3d4df..99efaf8469 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/KnownTransitionOmittedReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java index 0e19c70bf1..4ad4a51a17 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/NegativeInfluenceReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java index 626447a36a..7c85c396e4 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/PositiveInfluenceReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReactionRectTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReactionRectTest.java index 7c4de9b4b3..e3eaad75fc 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReactionRectTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReactionRectTest.java @@ -2,28 +2,26 @@ package lcsb.mapviewer.model.map.reaction.type; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ReactionRectTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (ReactionRect type : ReactionRect.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (ReactionRect type : ReactionRect.values()) { + assertNotNull(type); - // for coverage tests - ReactionRect.valueOf(type.toString()); - assertNotNull(type.getText()); - } - } + // for coverage tests + ReactionRect.valueOf(type.toString()); + assertNotNull(type.getText()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java index 3af121e9e7..6aec927f84 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedModulationReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java index 2e36146965..f9681af47b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedPhysicalStimulationReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java index dc6e20698e..4331b85da2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/ReducedTriggerReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java index 63766df9cd..b3fd9c916f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/StateTransitionReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java index a5a0efa99e..3bb4f8c5da 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranscriptionReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java index 797f530353..8fb71e5575 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TranslationReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java index 550d971357..fcc1c8fe19 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TransportReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java index 172e3a1b5e..c4ad3b3e20 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/TruncationReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java index 41657d5ef4..d3c45b037d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownNegativeInfluenceReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java index f6064bf915..5386451043 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownPositiveInfluenceReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java index fdd9447caf..ebb0109c4a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedModulationReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java index 3a2f2787cc..3eef31750f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedPhysicalStimulationReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java index 19392e6655..b7b511b0ca 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownReducedTriggerReactionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java index 181de50eb1..90ae71aa3f 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/reaction/type/UnknownTransitionReactionTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.reaction.type; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/AllSpeciesTests.java b/model/src/test/java/lcsb/mapviewer/model/map/species/AllSpeciesTests.java index 41464b30cc..c5661e83dd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/AllSpeciesTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/AllSpeciesTests.java @@ -8,41 +8,41 @@ import lcsb.mapviewer.model.map.species.field.AllFieldTests; @RunWith(Suite.class) @SuiteClasses({ AllFieldTests.class, - AntisenseRnaComparatorTest.class, - AntisenseRnaTest.class, - ChemicalComparatorTest.class, - ComplexComparatorTest.class, - ComplexTest.class, - DegradedComparatorTest.class, - DegradedTest.class, - DrugComparatorTest.class, - DrugTest.class, - ElementComparatorTest.class, - ElementTest.class, - GeneComparatorTest.class, - GenericProteinComparatorTest.class, - GenericProteinTest.class, - GeneTest.class, - IonChannelProteinTest.class, - IonChannelProteinComparatorTest.class, - IonComparatorTest.class, - IonTest.class, - PhenotypeComparatorTest.class, - PhenotypeTest.class, - ProteinComparatorTest.class, - ProteinTest.class, - ReceptorProteinTest.class, - ReceptorProteinComparatorTest.class, - RnaComparatorTest.class, - RnaTest.class, - SimpleMoleculeComparatorTest.class, - SimpleMoleculeTest.class, - SpeciesComparatorTest.class, - SpeciesTest.class, - TruncatedProteinTest.class, - TruncatedProteinComparatorTest.class, - UnknownComparatorTest.class, - UnknownTest.class, + AntisenseRnaComparatorTest.class, + AntisenseRnaTest.class, + ChemicalComparatorTest.class, + ComplexComparatorTest.class, + ComplexTest.class, + DegradedComparatorTest.class, + DegradedTest.class, + DrugComparatorTest.class, + DrugTest.class, + ElementComparatorTest.class, + ElementTest.class, + GeneComparatorTest.class, + GenericProteinComparatorTest.class, + GenericProteinTest.class, + GeneTest.class, + IonChannelProteinTest.class, + IonChannelProteinComparatorTest.class, + IonComparatorTest.class, + IonTest.class, + PhenotypeComparatorTest.class, + PhenotypeTest.class, + ProteinComparatorTest.class, + ProteinTest.class, + ReceptorProteinTest.class, + ReceptorProteinComparatorTest.class, + RnaComparatorTest.class, + RnaTest.class, + SimpleMoleculeComparatorTest.class, + SimpleMoleculeTest.class, + SpeciesComparatorTest.class, + SpeciesTest.class, + TruncatedProteinTest.class, + TruncatedProteinComparatorTest.class, + UnknownComparatorTest.class, + UnknownTest.class, }) public class AllSpeciesTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java index 00f1684306..78c1b4efae 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java index d43b90d1bd..1c7f41e502 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/AntisenseRnaTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java index 9d509a9d6f..469f78df26 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ChemicalComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java index b0d7480a51..60ba2db455 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexComparatorTest.java @@ -1,9 +1,10 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; -import java.awt.Color; +import java.awt.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java index cb686002ab..97cd264159 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ComplexTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java index 24aff10c4b..08fcd8f987 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java index 68ee746e1e..0955b845b9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DegradedTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java index ae3b3a1b05..a6bfc06b34 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java index 70f973bfc1..642e38d177 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/DrugTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java index a9b75ad52a..48d6f03c0e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ElementComparatorTest.java @@ -1,14 +1,14 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.mockito.Mockito; import lcsb.mapviewer.ModelTestFunctions; -import lcsb.mapviewer.common.exception.InvalidClassException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.compartment.Compartment; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java index f39b00f3c9..735efdffb8 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java index ca3450c307..41a44d7b12 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GeneTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java index 7f874e1c43..ce5e45b294 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java index aa6c24c5c1..5a4ca72142 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/GenericProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java index 0ad7b0f6d4..5c9d716b5d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java index 871c361273..f079732e7b 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonChannelProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java index 9cf4a3d73f..144415e1d6 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java index 7cf6596007..9b80ff2a07 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/IonTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java index fe9d66fe14..4710736e83 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java index 5b8535329d..06ac3a0ade 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/PhenotypeTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java index 2307b594ad..a0c3b2b7f3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java index af692fc075..8fd69b5dc0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ProteinTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java index 74bc63f06c..014bce4dfe 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java index 52977e3d1b..89a40be818 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/ReceptorProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java index 7d5209461f..3ba5523be0 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; @@ -73,7 +74,7 @@ public class RnaComparatorTest extends ModelTestFunctions { return result; } - @Test(expected=NotImplementedException.class) + @Test(expected = NotImplementedException.class) public void testInvalid() { Rna object = Mockito.mock(Rna.class); diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java index 2d742662d2..d46b948073 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/RnaTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java index 06b77a459a..4c06b26fad 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java index 6d88a38983..a408c3e8d7 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SimpleMoleculeTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java index 7751e2b5fd..df3283922c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesComparatorTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.mockito.Mockito; @@ -120,7 +121,7 @@ public class SpeciesComparatorTest extends ModelTestFunctions { assertTrue(comparator.compare(species2, species1) != 0); } - @Test(expected=NotImplementedException.class) + @Test(expected = NotImplementedException.class) public void testException() { Species mock = Mockito.mock(Species.class); comparator.compare(mock, mock); diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java index 2dff3ef1f2..99130fc40e 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/SpeciesTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java index feea3071a8..f48697810c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java index fbaad1d3c1..bcd6accc0d 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/TruncatedProteinTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java index 324249ff10..5d38a4da94 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownComparatorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java index ed3e6cf75b..f62e5a00d3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/UnknownTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.species; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/AllFieldTests.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/AllFieldTests.java index 48eca26298..009b8980fc 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/AllFieldTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/AllFieldTests.java @@ -6,12 +6,12 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ CodingRegionTest.class, - ModificationStateTest.class, - ResidueTest.class, - PositionToCompartmentTest.class, - ProteinBindingDomainTest.class, - StructureTest.class, - UniprotRecordTest.class, + ModificationStateTest.class, + ResidueTest.class, + PositionToCompartmentTest.class, + ProteinBindingDomainTest.class, + StructureTest.class, + UniprotRecordTest.class, }) public class AllFieldTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java index cff6502b20..5745fa28f3 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/CodingRegionTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.awt.geom.Point2D; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/ModificationStateTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/ModificationStateTest.java index 3de4dbaae7..7bd6fa181a 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/ModificationStateTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/ModificationStateTest.java @@ -3,38 +3,34 @@ package lcsb.mapviewer.model.map.species.field; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.model.map.species.field.ModificationState; +import org.junit.*; public class ModificationStateTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testValidValues() { - for (ModificationState type : ModificationState.values()) { - assertNotNull(type); - - // for coverage tests - ModificationState.valueOf(type.toString()); - assertNotNull(type.getFullName()); - assertNotNull(type.getAbbreviation()); - } - } - - @Test - public void testGetByName() { - assertNull(ModificationState.getByName("Adasd")); - assertNotNull(ModificationState.getByName("protonated")); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testValidValues() { + for (ModificationState type : ModificationState.values()) { + assertNotNull(type); + + // for coverage tests + ModificationState.valueOf(type.toString()); + assertNotNull(type.getFullName()); + assertNotNull(type.getAbbreviation()); + } + } + + @Test + public void testGetByName() { + assertNull(ModificationState.getByName("Adasd")); + assertNotNull(ModificationState.getByName("protonated")); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/PositionToCompartmentTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/PositionToCompartmentTest.java index dabb973bd6..0383f2f6f9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/PositionToCompartmentTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/PositionToCompartmentTest.java @@ -3,37 +3,33 @@ package lcsb.mapviewer.model.map.species.field; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.model.map.species.field.PositionToCompartment; +import org.junit.*; public class PositionToCompartmentTest { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testValidValues() { - for (PositionToCompartment type : PositionToCompartment.values()) { - assertNotNull(type); - assertNotNull(type.getStringName()); - - // for coverage tests - PositionToCompartment.valueOf(type.toString()); - } - } - - @Test - public void testGetByString() { - assertNotNull(PositionToCompartment.getByString("insideOfMembrane")); - assertNull(PositionToCompartment.getByString("insideOfasdasdas")); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testValidValues() { + for (PositionToCompartment type : PositionToCompartment.values()) { + assertNotNull(type); + assertNotNull(type.getStringName()); + + // for coverage tests + PositionToCompartment.valueOf(type.toString()); + } + } + + @Test + public void testGetByString() { + assertNotNull(PositionToCompartment.getByString("insideOfMembrane")); + assertNull(PositionToCompartment.getByString("insideOfasdasdas")); + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/ResidueTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/ResidueTest.java index 4c2b7c8658..f7ab37f9e9 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/ResidueTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/ResidueTest.java @@ -3,10 +3,7 @@ package lcsb.mapviewer.model.map.species.field; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java index 2014473d37..283f273e44 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/StructureTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.HashSet; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java b/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java index 26e3aa41a8..31ca26e835 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/species/field/UniprotRecordTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.model.map.species.field; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.*; import org.mockito.Mockito; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/statistics/AllStatisticsTests.java b/model/src/test/java/lcsb/mapviewer/model/map/statistics/AllStatisticsTests.java index e212af7b9b..683daea3c1 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/statistics/AllStatisticsTests.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/statistics/AllStatisticsTests.java @@ -6,7 +6,7 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ SearchHistoryTest.class, - SearchTypeTest.class, + SearchTypeTest.class, }) public class AllStatisticsTests { diff --git a/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java b/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java index 08b7e0ee0a..60b8b0fc61 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchHistoryTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.map.statistics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.Calendar; diff --git a/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchTypeTest.java index 0d0ed2796f..f42d6430de 100644 --- a/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/map/statistics/SearchTypeTest.java @@ -2,27 +2,25 @@ package lcsb.mapviewer.model.map.statistics; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class SearchTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (SearchType type : SearchType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (SearchType type : SearchType.values()) { + assertNotNull(type); - // for coverage tests - SearchType.valueOf(type.toString()); - } - } + // for coverage tests + SearchType.valueOf(type.toString()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTypeTest.java index b2fdca855b..e205574de2 100644 --- a/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/security/PrivilegeTypeTest.java @@ -2,30 +2,27 @@ package lcsb.mapviewer.model.security; import static org.junit.Assert.assertNotNull; -import lcsb.mapviewer.model.security.PrivilegeType; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class PrivilegeTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (PrivilegeType type : PrivilegeType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (PrivilegeType type : PrivilegeType.values()) { + assertNotNull(type); - // for coverage tests - PrivilegeType.valueOf(type.toString()); - assertNotNull(type.getDescription()); - } - } + // for coverage tests + PrivilegeType.valueOf(type.toString()); + assertNotNull(type.getDescription()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementEditTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementEditTypeTest.java index 39d37832c9..2d8683dd51 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementEditTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementEditTypeTest.java @@ -1,31 +1,28 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ConfigurationElementEditTypeTest { - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValues() { - for (ConfigurationElementEditType type: ConfigurationElementEditType.values()){ - assertNotNull(ConfigurationElementEditType.valueOf(type.toString())); - } - } + @Test + public void testValues() { + for (ConfigurationElementEditType type : ConfigurationElementEditType.values()) { + assertNotNull(ConfigurationElementEditType.valueOf(type.toString())); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementTypeTest.java b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementTypeTest.java index 2c9d683b50..03f2f6a1fd 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementTypeTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationElementTypeTest.java @@ -2,30 +2,28 @@ package lcsb.mapviewer.model.user; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class ConfigurationElementTypeTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (ConfigurationElementType type : ConfigurationElementType.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (ConfigurationElementType type : ConfigurationElementType.values()) { + assertNotNull(type); - // for coverage tests - ConfigurationElementType.valueOf(type.toString()); - assertNotNull(type.getCommonName()); - assertNotNull(type.getDefaultValue()); - assertNotNull(type.getEditType()); - } - } + // for coverage tests + ConfigurationElementType.valueOf(type.toString()); + assertNotNull(type.getCommonName()); + assertNotNull(type.getDefaultValue()); + assertNotNull(type.getEditType()); + } + } } diff --git a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java index e9d088ff51..e6a1dcae75 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/ConfigurationTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.apache.commons.lang3.SerializationUtils; import org.junit.*; diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java index b5c9dba438..c09b67b2eb 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserAnnotationSchemaTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java index 3d60065c91..4d1e39ea7c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserClassAnnotatorsTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java b/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java index 3c243c43f7..1a09a76273 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/UserTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.model.user; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; -import java.awt.Color; +import java.awt.*; import java.util.HashSet; import java.util.Set; diff --git a/model/src/test/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameterTest.java b/model/src/test/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameterTest.java index 175c41627e..751e922b2c 100644 --- a/model/src/test/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameterTest.java +++ b/model/src/test/java/lcsb/mapviewer/model/user/annotator/AnnotatorParameterTest.java @@ -1,10 +1,8 @@ package lcsb.mapviewer.model.user.annotator; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import java.util.*; import org.junit.Test; @@ -19,13 +17,13 @@ public class AnnotatorParameterTest { p2.setOrderPosition(1); AnnotatorParameter p3 = new AnnotatorConfigParameter(); p3.setOrderPosition(12); - + list.add(p1); list.add(p2); list.add(p3); - + Collections.sort(list); - + assertEquals(p2, list.get(0)); assertEquals(p1, list.get(1)); assertEquals(p3, list.get(2)); diff --git a/model/src/test/java/lcsb/mapviewer/modelutils/map/AllMapUtilTests.java b/model/src/test/java/lcsb/mapviewer/modelutils/map/AllMapUtilTests.java index 16ddd95d33..662f73e50a 100644 --- a/model/src/test/java/lcsb/mapviewer/modelutils/map/AllMapUtilTests.java +++ b/model/src/test/java/lcsb/mapviewer/modelutils/map/AllMapUtilTests.java @@ -6,8 +6,8 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ClassTreeNodeTest.class, - ElementUtilsTest.class, - RequireAnnotationMapTest.class, + ElementUtilsTest.class, + RequireAnnotationMapTest.class, }) public class AllMapUtilTests { diff --git a/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java b/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java index 0b80b693bc..e80bb05371 100644 --- a/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java +++ b/model/src/test/java/lcsb/mapviewer/modelutils/map/ClassTreeNodeTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.modelutils.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; diff --git a/model/src/test/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMapTest.java b/model/src/test/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMapTest.java index 9c30c4cea4..f73ec178db 100644 --- a/model/src/test/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMapTest.java +++ b/model/src/test/java/lcsb/mapviewer/modelutils/map/RequireAnnotationMapTest.java @@ -2,28 +2,26 @@ package lcsb.mapviewer.modelutils.map; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class RequireAnnotationMapTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testValidValues() { - for (RequireAnnotationMap type : RequireAnnotationMap.values()) { - assertNotNull(type); + @Test + public void testValidValues() { + for (RequireAnnotationMap type : RequireAnnotationMap.values()) { + assertNotNull(type); - // for coverage tests - RequireAnnotationMap.valueOf(type.toString()); - } - } + // for coverage tests + RequireAnnotationMap.valueOf(type.toString()); + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/Activator.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/Activator.java index e08ed1dfa0..23dccfe8cc 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/Activator.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/Activator.java @@ -14,21 +14,21 @@ import org.pathvisio.desktop.plugin.Plugin; public class Activator implements BundleActivator { - /** - * CellDesigner plugin for pathvisio. - */ - private ImportExport plugin; + /** + * CellDesigner plugin for pathvisio. + */ + private ImportExport plugin; - @Override - public void start(BundleContext context) throws Exception { - plugin = new ImportExport(); - context.registerService(Plugin.class.getName(), plugin, null); - } + @Override + public void start(BundleContext context) throws Exception { + plugin = new ImportExport(); + context.registerService(Plugin.class.getName(), plugin, null); + } - @Override - public void stop(BundleContext context) throws Exception { - if (plugin != null) { - plugin.done(); - } - } + @Override + public void stop(BundleContext context) throws Exception { + if (plugin != null) { + plugin.done(); + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/ImportExport.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/ImportExport.java index bb5e4a1bfe..f9279eb532 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/ImportExport.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/ImportExport.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.wikipathway; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.io.PrintWriter; +import java.io.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -12,10 +9,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.LoggerContext; -import org.pathvisio.core.model.ConverterException; -import org.pathvisio.core.model.Pathway; -import org.pathvisio.core.model.PathwayExporter; -import org.pathvisio.core.model.PathwayImporter; +import org.pathvisio.core.model.*; import org.pathvisio.desktop.PvDesktop; import org.pathvisio.desktop.plugin.Plugin; @@ -33,180 +27,180 @@ import lcsb.mapviewer.wikipathway.XML.ModelToGPML; * */ public class ImportExport implements Plugin { - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(ImportExport.class); - /** - * List of extensions supported by import plugin. - */ - private final String[] importExtensions = new String[] { "xml" }; - /** - * List of extensions supported by export plugin. - */ - private final String[] exportExtensions = new String[] { "cell" }; - - @Override - public void init(PvDesktop desktop) { - try { - LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false); - File file = new File("log4j2.properties"); - context.setConfigLocation(file.toURI()); - } catch (Exception e) { - e.printStackTrace(); - } - ExportCellDesigner exportPlugin = new ExportCellDesigner(); - ImportCellDesigner importPlugin = new ImportCellDesigner(); - desktop.getSwingEngine().getEngine().addPathwayImporter(importPlugin); - desktop.getSwingEngine().getEngine().addPathwayExporter(exportPlugin); - } - - @Override - public void done() { - } - - /** - * Implementation of {@link PathwayExporter} that allows PathVisio to import - * from CellDesigner xml file. - * - * @author Piotr Gawron - * - */ - protected class ImportCellDesigner implements PathwayImporter { - - /** - * List of warnings that occured during conversion. - */ - private List<LogEvent> warnings = new ArrayList<>(); - - /** - * Default constructor. - */ - public ImportCellDesigner() { - } - - @Override - public String[] getExtensions() { - return importExtensions; - } - - @Override - public String getName() { - return "CellDesigner"; - } - - @Override - public Pathway doImport(File file) throws ConverterException { - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - try { - Pathway pathway = new Pathway(); - String fileName = file.getPath(); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = (Model) parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); - String tmp = new ModelToGPML().getGPML(model); - InputStream stream = new ByteArrayInputStream(tmp.getBytes(StandardCharsets.UTF_8)); - Boolean validate = false; - pathway.readFromXml(stream, validate); - - MinervaLoggerAppender.unregisterLogEventStorage(appender); - warnings.addAll(appender.getWarnings()); - return pathway; - } catch (Exception e) { - logger.error(e, e); - throw new ConverterException(e); - } finally { - MinervaLoggerAppender.unregisterLogEventStorage(appender); - } - } - - @Override - public boolean isCorrectType(File arg0) { - return true; - } - - @Override - public List<String> getWarnings() { - List<String> result = new ArrayList<>(); - for (LogEvent event : warnings) { - result.add(event.getMessage().getFormattedMessage()); - } - return result; - } - } - - /** - * Implementation of {@link PathwayExporter} that allows PathVisio to export - * into CellDesigner xml file. - * - * @author Piotr Gawron - * - */ - protected class ExportCellDesigner implements PathwayExporter { - - /** - * {@link Model} that was created using this {@link PathwayExporter}. - */ - private Model model = null; - - /** - * List of export warnings. - */ - private List<String> warnings = new ArrayList<>(); - - @Override - public String[] getExtensions() { - return exportExtensions; - } - - @Override - public String getName() { - return "CellDesigner"; - } - - @Override - public List<String> getWarnings() { - return warnings; - } - - @Override - public void doExport(File file, Pathway pathway) throws ConverterException { - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - try { - pathway.writeToXml(new File("tmp.gpml"), false); - model = new GPMLToModel().getModel("tmp.gpml"); - - MinervaLoggerAppender.unregisterLogEventStorage(appender); - warnings = createWarnings(appender); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - String xml = parser.model2String(model); - PrintWriter writer = new PrintWriter(file.getPath(), "UTF-8"); - writer.println(xml); - writer.close(); - - warnings.add("Please manually change extension of saved file from .cell to .xml"); - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw new ConverterException(e); - } finally { - MinervaLoggerAppender.unregisterLogEventStorage(appender); - } - } - - /** - * Creates list of warnings from log4j appender data. - * - * @param appender - * appender with the logs - * @return list of warnings from log4j appender data - */ - private List<String> createWarnings(MinervaLoggerAppender appender) { - List<String> warnings = new ArrayList<>(); - for (LogEvent event : appender.getWarnings()) { - warnings.add(event.getMessage().getFormattedMessage().replaceAll("\n", "_NEW_LINE_")); - } - return warnings; - } - } + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(ImportExport.class); + /** + * List of extensions supported by import plugin. + */ + private final String[] importExtensions = new String[] { "xml" }; + /** + * List of extensions supported by export plugin. + */ + private final String[] exportExtensions = new String[] { "cell" }; + + @Override + public void init(PvDesktop desktop) { + try { + LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false); + File file = new File("log4j2.properties"); + context.setConfigLocation(file.toURI()); + } catch (Exception e) { + e.printStackTrace(); + } + ExportCellDesigner exportPlugin = new ExportCellDesigner(); + ImportCellDesigner importPlugin = new ImportCellDesigner(); + desktop.getSwingEngine().getEngine().addPathwayImporter(importPlugin); + desktop.getSwingEngine().getEngine().addPathwayExporter(exportPlugin); + } + + @Override + public void done() { + } + + /** + * Implementation of {@link PathwayExporter} that allows PathVisio to import + * from CellDesigner xml file. + * + * @author Piotr Gawron + * + */ + protected class ImportCellDesigner implements PathwayImporter { + + /** + * List of warnings that occured during conversion. + */ + private List<LogEvent> warnings = new ArrayList<>(); + + /** + * Default constructor. + */ + public ImportCellDesigner() { + } + + @Override + public String getName() { + return "CellDesigner"; + } + + @Override + public String[] getExtensions() { + return importExtensions; + } + + @Override + public List<String> getWarnings() { + List<String> result = new ArrayList<>(); + for (LogEvent event : warnings) { + result.add(event.getMessage().getFormattedMessage()); + } + return result; + } + + @Override + public boolean isCorrectType(File arg0) { + return true; + } + + @Override + public Pathway doImport(File file) throws ConverterException { + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + try { + Pathway pathway = new Pathway(); + String fileName = file.getPath(); + + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + Model model = (Model) parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); + String tmp = new ModelToGPML().getGPML(model); + InputStream stream = new ByteArrayInputStream(tmp.getBytes(StandardCharsets.UTF_8)); + Boolean validate = false; + pathway.readFromXml(stream, validate); + + MinervaLoggerAppender.unregisterLogEventStorage(appender); + warnings.addAll(appender.getWarnings()); + return pathway; + } catch (Exception e) { + logger.error(e, e); + throw new ConverterException(e); + } finally { + MinervaLoggerAppender.unregisterLogEventStorage(appender); + } + } + } + + /** + * Implementation of {@link PathwayExporter} that allows PathVisio to export + * into CellDesigner xml file. + * + * @author Piotr Gawron + * + */ + protected class ExportCellDesigner implements PathwayExporter { + + /** + * {@link Model} that was created using this {@link PathwayExporter}. + */ + private Model model = null; + + /** + * List of export warnings. + */ + private List<String> warnings = new ArrayList<>(); + + @Override + public String getName() { + return "CellDesigner"; + } + + @Override + public String[] getExtensions() { + return exportExtensions; + } + + @Override + public List<String> getWarnings() { + return warnings; + } + + @Override + public void doExport(File file, Pathway pathway) throws ConverterException { + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + try { + pathway.writeToXml(new File("tmp.gpml"), false); + model = new GPMLToModel().getModel("tmp.gpml"); + + MinervaLoggerAppender.unregisterLogEventStorage(appender); + warnings = createWarnings(appender); + + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + String xml = parser.model2String(model); + PrintWriter writer = new PrintWriter(file.getPath(), "UTF-8"); + writer.println(xml); + writer.close(); + + warnings.add("Please manually change extension of saved file from .cell to .xml"); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new ConverterException(e); + } finally { + MinervaLoggerAppender.unregisterLogEventStorage(appender); + } + } + + /** + * Creates list of warnings from log4j appender data. + * + * @param appender + * appender with the logs + * @return list of warnings from log4j appender data + */ + private List<String> createWarnings(MinervaLoggerAppender appender) { + List<String> warnings = new ArrayList<>(); + for (LogEvent event : appender.getWarnings()) { + warnings.add(event.getMessage().getFormattedMessage().replaceAll("\n", "_NEW_LINE_")); + } + return warnings; + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/BiopaxParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/BiopaxParser.java index 877f7cf6d3..0296f8a1e1 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/BiopaxParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/BiopaxParser.java @@ -1,24 +1,16 @@ package lcsb.mapviewer.wikipathway.XML; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +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.XmlParser; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.wikipathway.model.biopax.BiopaxData; -import lcsb.mapviewer.wikipathway.model.biopax.BiopaxOpenControlledVocabulary; -import lcsb.mapviewer.wikipathway.model.biopax.BiopaxPublication; +import lcsb.mapviewer.model.map.*; +import lcsb.mapviewer.wikipathway.model.biopax.*; /** * Parser of Biopax data from the gpml file. @@ -28,237 +20,237 @@ import lcsb.mapviewer.wikipathway.model.biopax.BiopaxPublication; */ public class BiopaxParser { - /** - * Default class logger. - */ - private static Logger logger = LogManager.getLogger(BiopaxParser.class); + /** + * Default class logger. + */ + private static Logger logger = LogManager.getLogger(BiopaxParser.class); - /** - * Hash used for next {@link BiopaxPublication} processed by parser. - */ - private Integer hash = 1; + /** + * Hash used for next {@link BiopaxPublication} processed by parser. + */ + private Integer hash = 1; - /** - * Mapping between {@link MiriamData} and hash value. - */ - private Map<MiriamData, String> miriamHash = new HashMap<>(); + /** + * Mapping between {@link MiriamData} and hash value. + */ + private Map<MiriamData, String> miriamHash = new HashMap<>(); - /** - * Creates data structure from biopax xml node. - * - * @param biopax - * xml node - * @return {@link BiopaxData} structure containing biopax data - */ - public BiopaxData parse(Node biopax) { - BiopaxData result = new BiopaxData(); - NodeList nodes = biopax.getChildNodes(); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if ("bp:PublicationXref".equalsIgnoreCase(node.getNodeName())) { - BiopaxPublication publication = parsePublication(node); - if (publication.getId() == null || publication.getId().isEmpty()) { - logger.warn("No pubmed identifier defined for publication: title: " + publication.getTitle()); - } - result.addPublication(publication); - } else if ("bp:openControlledVocabulary".equalsIgnoreCase(node.getNodeName())) { - result.addOpenControlledVocabulary(parseOpenControlledVocabulary(node)); - } else { - logger.warn("Unknown biopax node: " + node.getNodeName()); - } - } - } - return result; - } + /** + * Creates data structure from biopax xml node. + * + * @param biopax + * xml node + * @return {@link BiopaxData} structure containing biopax data + */ + public BiopaxData parse(Node biopax) { + BiopaxData result = new BiopaxData(); + NodeList nodes = biopax.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if ("bp:PublicationXref".equalsIgnoreCase(node.getNodeName())) { + BiopaxPublication publication = parsePublication(node); + if (publication.getId() == null || publication.getId().isEmpty()) { + logger.warn("No pubmed identifier defined for publication: title: " + publication.getTitle()); + } + result.addPublication(publication); + } else if ("bp:openControlledVocabulary".equalsIgnoreCase(node.getNodeName())) { + result.addOpenControlledVocabulary(parseOpenControlledVocabulary(node)); + } else { + logger.warn("Unknown biopax node: " + node.getNodeName()); + } + } + } + return result; + } - /** - * Method which parse biopax vocabulary xml node. - * - * @param biopaxNode - * xml node - * @return {@link BiopaxOpenControlledVocabulary} - */ - private BiopaxOpenControlledVocabulary parseOpenControlledVocabulary(Node biopaxNode) { - BiopaxOpenControlledVocabulary result = new BiopaxOpenControlledVocabulary(); - NodeList nodes = biopaxNode.getChildNodes(); + /** + * Method which parse biopax vocabulary xml node. + * + * @param biopaxNode + * xml node + * @return {@link BiopaxOpenControlledVocabulary} + */ + private BiopaxOpenControlledVocabulary parseOpenControlledVocabulary(Node biopaxNode) { + BiopaxOpenControlledVocabulary result = new BiopaxOpenControlledVocabulary(); + NodeList nodes = biopaxNode.getChildNodes(); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if ("bp:ID".equalsIgnoreCase(node.getNodeName())) { - result.setId(node.getTextContent()); - } else if ("bp:TERM".equalsIgnoreCase(node.getNodeName())) { - result.setTerm(node.getTextContent()); - } else if ("bp:Ontology".equalsIgnoreCase(node.getNodeName())) { - result.setOntology(node.getTextContent()); - } else { - logger.warn("Unknown biopax node: " + node.getNodeName()); - } - } - } - return result; - } + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if ("bp:ID".equalsIgnoreCase(node.getNodeName())) { + result.setId(node.getTextContent()); + } else if ("bp:TERM".equalsIgnoreCase(node.getNodeName())) { + result.setTerm(node.getTextContent()); + } else if ("bp:Ontology".equalsIgnoreCase(node.getNodeName())) { + result.setOntology(node.getTextContent()); + } else { + logger.warn("Unknown biopax node: " + node.getNodeName()); + } + } + } + return result; + } - /** - * Method which parse biopax publication xml node. - * - * @param publication - * xml node - * @return {@link BiopaxPublication} - */ - protected BiopaxPublication parsePublication(Node publication) { - BiopaxPublication result = new BiopaxPublication(); - NodeList nodes = publication.getChildNodes(); + /** + * Method which parse biopax publication xml node. + * + * @param publication + * xml node + * @return {@link BiopaxPublication} + */ + protected BiopaxPublication parsePublication(Node publication) { + BiopaxPublication result = new BiopaxPublication(); + NodeList nodes = publication.getChildNodes(); - result.setReferenceId(XmlParser.getNodeAttr("rdf:id", publication)); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if ("bp:ID".equalsIgnoreCase(node.getNodeName())) { - result.setId(node.getTextContent()); - } else if ("bp:DB".equalsIgnoreCase(node.getNodeName())) { - result.setDb(node.getTextContent()); - } else if ("bp:TITLE".equalsIgnoreCase(node.getNodeName())) { - result.setTitle(node.getTextContent()); - } else if ("bp:SOURCE".equalsIgnoreCase(node.getNodeName())) { - result.setSource(node.getTextContent()); - } else if ("bp:YEAR".equalsIgnoreCase(node.getNodeName())) { - result.setYear(node.getTextContent()); - } else if ("bp:AUTHORS".equalsIgnoreCase(node.getNodeName())) { - result.setAuthors(node.getTextContent()); - } else { - logger.warn("Unknown biopax node: " + node.getNodeName()); - } - } - } - return result; - } + result.setReferenceId(XmlParser.getNodeAttr("rdf:id", publication)); + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if ("bp:ID".equalsIgnoreCase(node.getNodeName())) { + result.setId(node.getTextContent()); + } else if ("bp:DB".equalsIgnoreCase(node.getNodeName())) { + result.setDb(node.getTextContent()); + } else if ("bp:TITLE".equalsIgnoreCase(node.getNodeName())) { + result.setTitle(node.getTextContent()); + } else if ("bp:SOURCE".equalsIgnoreCase(node.getNodeName())) { + result.setSource(node.getTextContent()); + } else if ("bp:YEAR".equalsIgnoreCase(node.getNodeName())) { + result.setYear(node.getTextContent()); + } else if ("bp:AUTHORS".equalsIgnoreCase(node.getNodeName())) { + result.setAuthors(node.getTextContent()); + } else { + logger.warn("Unknown biopax node: " + node.getNodeName()); + } + } + } + return result; + } - /** - * Returns xml string representing biopax reference to set of - * {@link MiriamData} form parameters. - * - * @param miriamData - * set of {@link MiriamData} for which we want to obtain biopax - * references - * @return xml string representing biopax reference to set of - * {@link MiriamData} form parameters. Only references to - * {@link MiriamType#PUBMED} are included. - */ - public String toReferenceXml(Set<MiriamData> miriamData) { - StringBuilder sb = new StringBuilder(""); - for (MiriamData md : miriamData) { - if (md.getDataType().equals(MiriamType.PUBMED)) { - sb.append("<BiopaxRef>" + getHash(md) + "</BiopaxRef>\n"); - } - } - return sb.toString(); - } + /** + * Returns xml string representing biopax reference to set of {@link MiriamData} + * form parameters. + * + * @param miriamData + * set of {@link MiriamData} for which we want to obtain biopax + * references + * @return xml string representing biopax reference to set of {@link MiriamData} + * form parameters. Only references to {@link MiriamType#PUBMED} are + * included. + */ + public String toReferenceXml(Set<MiriamData> miriamData) { + StringBuilder sb = new StringBuilder(""); + for (MiriamData md : miriamData) { + if (md.getDataType().equals(MiriamType.PUBMED)) { + sb.append("<BiopaxRef>" + getHash(md) + "</BiopaxRef>\n"); + } + } + return sb.toString(); + } - /** - * Returns unique hash for the {@link MiriamData} that can be used as a key in - * Biopax xml. - * - * @param md - * {@link MiriamData} for which we want to have unique hash value - * @return unique hash for the {@link MiriamData} that can be used as a key in - * Biopax xml - */ - private String getHash(MiriamData md) { - if (miriamHash.get(md) == null) { - miriamHash.put(md, "ann" + hash); - hash++; - } - return miriamHash.get(md); - } + /** + * Returns unique hash for the {@link MiriamData} that can be used as a key in + * Biopax xml. + * + * @param md + * {@link MiriamData} for which we want to have unique hash value + * @return unique hash for the {@link MiriamData} that can be used as a key in + * Biopax xml + */ + private String getHash(MiriamData md) { + if (miriamHash.get(md) == null) { + miriamHash.put(md, "ann" + hash); + hash++; + } + return miriamHash.get(md); + } - /** - * Converts collection of {@link MiriamData} into an xml {@link String} - * representing this collection as a biopax data. - * - * @param miriamData - * collection of {@link MiriamData} - * @return xml {@link String} representing this collection as a biopax data - */ - public String toXml(Collection<MiriamData> miriamData) { - StringBuilder sb = new StringBuilder(""); - sb.append("<Biopax>\n"); - for (MiriamData md : miriamData) { - if (md.getDataType().equals(MiriamType.PUBMED)) { - sb.append(toXml(md)); - } - } - sb.append("</Biopax>\n"); + /** + * Converts collection of {@link MiriamData} into an xml {@link String} + * representing this collection as a biopax data. + * + * @param miriamData + * collection of {@link MiriamData} + * @return xml {@link String} representing this collection as a biopax data + */ + public String toXml(Collection<MiriamData> miriamData) { + StringBuilder sb = new StringBuilder(""); + sb.append("<Biopax>\n"); + for (MiriamData md : miriamData) { + if (md.getDataType().equals(MiriamType.PUBMED)) { + sb.append(toXml(md)); + } + } + sb.append("</Biopax>\n"); - return sb.toString(); - } + return sb.toString(); + } - /** - * Converts {@link MiriamData} into xml string in biopax format. - * - * @param md - * {@link MiriamData} to transform - * @return xml string in biopax format representing {@link MiriamData} - */ - public String toXml(MiriamData md) { - StringBuilder sb = new StringBuilder(); - sb.append( - "<bp:PublicationXref xmlns:bp=\"http://www.biopax.org/release/biopax-level3.owl#\" " - + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:id=\"" + getHash(md) + "\">\n"); - sb.append(" <bp:ID rdf:datatype=\"http://www.w3.org/2001/XMLSchema#string\">" + md.getResource() + "</bp:ID>\n"); - sb.append(" <bp:DB rdf:datatype=\"http://www.w3.org/2001/XMLSchema#string\">PubMed</bp:DB>\n"); - sb.append("</bp:PublicationXref>\n"); - return sb.toString(); - } + /** + * Converts {@link MiriamData} into xml string in biopax format. + * + * @param md + * {@link MiriamData} to transform + * @return xml string in biopax format representing {@link MiriamData} + */ + public String toXml(MiriamData md) { + StringBuilder sb = new StringBuilder(); + sb.append( + "<bp:PublicationXref xmlns:bp=\"http://www.biopax.org/release/biopax-level3.owl#\" " + + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:id=\"" + getHash(md) + "\">\n"); + sb.append(" <bp:ID rdf:datatype=\"http://www.w3.org/2001/XMLSchema#string\">" + md.getResource() + "</bp:ID>\n"); + sb.append(" <bp:DB rdf:datatype=\"http://www.w3.org/2001/XMLSchema#string\">PubMed</bp:DB>\n"); + sb.append("</bp:PublicationXref>\n"); + return sb.toString(); + } - /** - * Creates {@link MiriamData annotation} from {@link BiopaxPublication}. - * - * @param publication - * input biopax structure - * @return {@link MiriamData annotation} - */ - protected MiriamData createMiriamData(BiopaxPublication publication) { - if ("PubMed".equals(publication.getDb())) { - if (publication.getId() == null || publication.getId().equals("")) { - return null; - } else { - return new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, publication.getId()); - } - } else { - throw new InvalidArgumentException("Unknown biopax database: " + publication.getDb()); - } - } + /** + * Creates {@link MiriamData annotation} from {@link BiopaxPublication}. + * + * @param publication + * input biopax structure + * @return {@link MiriamData annotation} + */ + protected MiriamData createMiriamData(BiopaxPublication publication) { + if ("PubMed".equals(publication.getDb())) { + if (publication.getId() == null || publication.getId().equals("")) { + return null; + } else { + return new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.PUBMED, publication.getId()); + } + } else { + throw new InvalidArgumentException("Unknown biopax database: " + publication.getDb()); + } + } - /** - * Returns list of {@link MiriamData} that are refernced in {@link BiopaxData} - * with identifier given in biopaxReference. - * - * @param biopaxData - * {@link BiopaxData} where annotations are stored - * @param biopaxReference - * list of refrences (to data in {@link BiopaxData}) that we want to - * convert into {@link MiriamData} - * @return list of {@link MiriamData} that are refernced in {@link BiopaxData} - * with identifier given in biopaxReference. - */ - public Collection<MiriamData> getMiriamData(BiopaxData biopaxData, List<String> biopaxReference) { - List<MiriamData> result = new ArrayList<>(); - for (String string : biopaxReference) { - BiopaxPublication bp = biopaxData.getPublicationByReference(string); - if (bp != null) { - MiriamData md = createMiriamData(bp); - if (md != null) { - result.add(md); - } else { - logger.warn("[" + string + "]\tBiopax publication is invalid."); - } - } else { - logger.warn("[" + string + "]\tBiopax publication doesn't exist."); - } - } - return result; - } + /** + * Returns list of {@link MiriamData} that are refernced in {@link BiopaxData} + * with identifier given in biopaxReference. + * + * @param biopaxData + * {@link BiopaxData} where annotations are stored + * @param biopaxReference + * list of refrences (to data in {@link BiopaxData}) that we want to + * convert into {@link MiriamData} + * @return list of {@link MiriamData} that are refernced in {@link BiopaxData} + * with identifier given in biopaxReference. + */ + public Collection<MiriamData> getMiriamData(BiopaxData biopaxData, List<String> biopaxReference) { + List<MiriamData> result = new ArrayList<>(); + for (String string : biopaxReference) { + BiopaxPublication bp = biopaxData.getPublicationByReference(string); + if (bp != null) { + MiriamData md = createMiriamData(bp); + if (md != null) { + result.add(md); + } else { + logger.warn("[" + string + "]\tBiopax publication is invalid."); + } + } else { + logger.warn("[" + string + "]\tBiopax publication doesn't exist."); + } + } + return result; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/CyclicEdgeException.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/CyclicEdgeException.java index 46ad82cf91..1d2a3e863e 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/CyclicEdgeException.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/CyclicEdgeException.java @@ -20,19 +20,19 @@ import lcsb.mapviewer.converter.ConverterException; */ public class CyclicEdgeException extends ConverterException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public CyclicEdgeException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public CyclicEdgeException(String string) { + super(string); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/DataNodeParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/DataNodeParser.java index 96bb89c3e5..445bf4de09 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/DataNodeParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/DataNodeParser.java @@ -3,19 +3,16 @@ package lcsb.mapviewer.wikipathway.XML; import java.awt.geom.Rectangle2D; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.wikipathway.model.DataNode; -import lcsb.mapviewer.wikipathway.model.GpmlLineType; -import lcsb.mapviewer.wikipathway.model.UnknownTypeException; +import lcsb.mapviewer.wikipathway.model.*; /** * Parser class that creates {@link DataNode} objects from Xml {@link Element @@ -26,175 +23,175 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class DataNodeParser extends GraphicalPathwayElementParser<DataNode> { - /** - * Default claass logger. - */ - private final Logger logger = LogManager.getLogger(DataNodeParser.class); + /** + * Default claass logger. + */ + private final Logger logger = LogManager.getLogger(DataNodeParser.class); - /** - * PArser used to process references. - */ - private final ReferenceParser referenceParser = new ReferenceParser(); + /** + * PArser used to process references. + */ + private final ReferenceParser referenceParser = new ReferenceParser(); - @Override - public DataNode parse(Element eElement) throws UnknownTypeException { - if (!eElement.getNodeName().equals("DataNode")) { - throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only DataNode xml nodes"); - } - DataNode node = new DataNode(eElement.getAttribute("GraphId")); + @Override + public DataNode parse(Element eElement) throws UnknownTypeException { + if (!eElement.getNodeName().equals("DataNode")) { + throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only DataNode xml nodes"); + } + DataNode node = new DataNode(eElement.getAttribute("GraphId")); - for (Pair<String, String> entry : getAttributes(eElement)) { - switch (entry.getLeft()) { - case ("GraphId"): - break; - case ("TextLabel"): - node.setTextLabel(entry.getRight()); - break; - case ("GroupRef"): - node.setGroupRef(entry.getRight()); - break; - case ("Type"): - node.setType(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); - break; - } - } + for (Pair<String, String> entry : getAttributes(eElement)) { + switch (entry.getLeft()) { + case ("GraphId"): + break; + case ("TextLabel"): + node.setTextLabel(entry.getRight()); + break; + case ("GroupRef"): + node.setGroupRef(entry.getRight()); + break; + case ("Type"): + node.setType(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); + break; + } + } - NodeList tmpList = eElement.getChildNodes(); - for (int j = 0; j < tmpList.getLength(); j++) { - Node tmpNode = tmpList.item(j); - if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { - Element eTmp = (Element) tmpNode; - switch (eTmp.getNodeName()) { - case ("Comment"): - node.addComment(eTmp.getTextContent()); - break; - case ("BiopaxRef"): - node.addBiopaxReference(eTmp.getTextContent()); - break; - case ("Xref"): - MiriamData data = referenceParser.parse(eTmp); - if (data != null) { - node.addReference(data); - } - break; - case ("Graphics"): - parseGraphics(eTmp, node); - break; - case ("Attribute"): - parseAttribute(eTmp, node); - break; - default: - logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); - break; - } - } - } + NodeList tmpList = eElement.getChildNodes(); + for (int j = 0; j < tmpList.getLength(); j++) { + Node tmpNode = tmpList.item(j); + if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { + Element eTmp = (Element) tmpNode; + switch (eTmp.getNodeName()) { + case ("Comment"): + node.addComment(eTmp.getTextContent()); + break; + case ("BiopaxRef"): + node.addBiopaxReference(eTmp.getTextContent()); + break; + case ("Xref"): + MiriamData data = referenceParser.parse(eTmp); + if (data != null) { + node.addReference(data); + } + break; + case ("Graphics"): + parseGraphics(eTmp, node); + break; + case ("Attribute"): + parseAttribute(eTmp, node); + break; + default: + logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); + break; + } + } + } - return node; - } + return node; + } - /** - * Parse graphics xml node in the shape node. - * - * @param eTmp - * xml node with graphics - * @param shape - * shape where data should be added - * @throws UnknownTypeException - * thrown when node contains unknown types - */ - private void parseGraphics(Element eTmp, DataNode shape) throws UnknownTypeException { - Double centerX = null; - Double centerY = null; - Double width = null; - Double height = null; - for (Pair<String, String> entry : getAttributes(eTmp)) { - if (!parseCommonGraphicAttributes(shape, entry)) { - switch (entry.getLeft()) { - case ("CenterX"): - centerX = Double.valueOf(entry.getRight()); - break; - case ("CenterY"): - centerY = Double.valueOf(entry.getRight()); - break; - case ("Width"): - width = Double.valueOf(entry.getRight()); - break; - case ("Height"): - height = Double.valueOf(entry.getRight()); - break; - case ("ShapeType"): - shape.setType(entry.getRight()); - break; - case ("Color"): - shape.setColor(hexStringToColor(entry.getRight())); - break; - case ("FillColor"): - shape.setFillColor(hexStringToColor(entry.getRight())); - break; - case ("ZOrder"): - shape.setzOrder(Integer.valueOf(entry.getRight())); - break; - case ("LineStyle"): - shape.setLineType(GpmlLineType.getByGpmlName(entry.getRight()).getCorrespondingGlobalLineType()); - break; - case ("FontSize"): - shape.setFontSize(Double.valueOf(entry.getRight())); - break; - case ("FontWeight"): - shape.setFontWeight(entry.getRight()); - break; - case ("Valign"): - shape.setvAlign(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft()); - break; - } - } - } - shape.setRectangle(new Rectangle2D.Double(centerX - width / 2, centerY - height / 2, width, height)); - } + @Override + public String toXml(DataNode node) throws ConverterException { + throw new NotImplementedException(); + } - /** - * Method that parses {@link DataNode} xml attribute. - * - * @param eTmp - * xml node with attribute - * @param shape - * shape where data should be added - */ - private void parseAttribute(Element eTmp, DataNode shape) { - String key = eTmp.getAttribute("Key"); - String value = eTmp.getAttribute("Value"); - switch (key) { - case ("org.pathvisio.model.BackpageHead"): - // it's deprecated in PathVisio so we can skip it - break; - case ("org.pathvisio.model.GenMAPP-Xref"): - // skip it when it's empty - if (!value.isEmpty()) { - logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); - break; - } - break; - default: - logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); - break; - } - } + @Override + public String toXml(Collection<DataNode> list) throws ConverterException { + throw new NotImplementedException(); + } - @Override - public String toXml(DataNode node) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Parse graphics xml node in the shape node. + * + * @param eTmp + * xml node with graphics + * @param shape + * shape where data should be added + * @throws UnknownTypeException + * thrown when node contains unknown types + */ + private void parseGraphics(Element eTmp, DataNode shape) throws UnknownTypeException { + Double centerX = null; + Double centerY = null; + Double width = null; + Double height = null; + for (Pair<String, String> entry : getAttributes(eTmp)) { + if (!parseCommonGraphicAttributes(shape, entry)) { + switch (entry.getLeft()) { + case ("CenterX"): + centerX = Double.valueOf(entry.getRight()); + break; + case ("CenterY"): + centerY = Double.valueOf(entry.getRight()); + break; + case ("Width"): + width = Double.valueOf(entry.getRight()); + break; + case ("Height"): + height = Double.valueOf(entry.getRight()); + break; + case ("ShapeType"): + shape.setType(entry.getRight()); + break; + case ("Color"): + shape.setColor(hexStringToColor(entry.getRight())); + break; + case ("FillColor"): + shape.setFillColor(hexStringToColor(entry.getRight())); + break; + case ("ZOrder"): + shape.setzOrder(Integer.valueOf(entry.getRight())); + break; + case ("LineStyle"): + shape.setLineType(GpmlLineType.getByGpmlName(entry.getRight()).getCorrespondingGlobalLineType()); + break; + case ("FontSize"): + shape.setFontSize(Double.valueOf(entry.getRight())); + break; + case ("FontWeight"): + shape.setFontWeight(entry.getRight()); + break; + case ("Valign"): + shape.setvAlign(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft()); + break; + } + } + } + shape.setRectangle(new Rectangle2D.Double(centerX - width / 2, centerY - height / 2, width, height)); + } - @Override - public String toXml(Collection<DataNode> list) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Method that parses {@link DataNode} xml attribute. + * + * @param eTmp + * xml node with attribute + * @param shape + * shape where data should be added + */ + private void parseAttribute(Element eTmp, DataNode shape) { + String key = eTmp.getAttribute("Key"); + String value = eTmp.getAttribute("Value"); + switch (key) { + case ("org.pathvisio.model.BackpageHead"): + // it's deprecated in PathVisio so we can skip it + break; + case ("org.pathvisio.model.GenMAPP-Xref"): + // skip it when it's empty + if (!value.isEmpty()) { + logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); + break; + } + break; + default: + logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); + break; + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParser.java index d848563e24..7a534a2272 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeLineParser.java @@ -2,10 +2,9 @@ package lcsb.mapviewer.wikipathway.XML; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -22,71 +21,72 @@ import lcsb.mapviewer.wikipathway.model.Edge; */ public class EdgeLineParser extends ElementGpmlParser<Edge> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(EdgeLineParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(EdgeLineParser.class); - /** - * Parser used to parse typical {@link Edge} xml nodes. - */ - private final EdgeParser edgeParser = new EdgeParser(); + /** + * Parser used to parse typical {@link Edge} xml nodes. + */ + private final EdgeParser edgeParser = new EdgeParser(); - /** - * Creates {@link Edge} from xml line node. - * - * @return {@link Edge} from xml node - * @throws ConverterException - */ - @Override - public Edge parse(Element eElement) throws ConverterException { - if (!eElement.getNodeName().equals("GraphicalLine")) { - throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only GraphicalLine xml nodes. But " + eElement.getNodeName()); - } - Edge line = edgeParser.createEmpty(); - NodeList nodes = eElement.getChildNodes(); - for (Pair<String, String> entry : getAttributes(eElement)) { - switch (entry.getLeft()) { - case ("GraphId"): - line.setGraphId(entry.getRight()); - break; - case ("GroupRef"): - line.setGroupRef(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); - } - } + /** + * Creates {@link Edge} from xml line node. + * + * @return {@link Edge} from xml node + * @throws ConverterException + */ + @Override + public Edge parse(Element eElement) throws ConverterException { + if (!eElement.getNodeName().equals("GraphicalLine")) { + throw new InvalidArgumentException( + ShapeParser.class.getSimpleName() + " can parse only GraphicalLine xml nodes. But " + eElement.getNodeName()); + } + Edge line = edgeParser.createEmpty(); + NodeList nodes = eElement.getChildNodes(); + for (Pair<String, String> entry : getAttributes(eElement)) { + switch (entry.getLeft()) { + case ("GraphId"): + line.setGraphId(entry.getRight()); + break; + case ("GroupRef"): + line.setGroupRef(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); + } + } - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element eTmp = (Element) node; - switch (node.getNodeName()) { - case ("Graphics"): - edgeParser.parseGraphics(line, (Element) node); - break; - case ("BiopaxRef"): - line.addBiopaxReference(eTmp.getTextContent()); - break; - case ("Comment"): - line.addComment(eTmp.getTextContent()); - break; - default: - logger.warn("Unknown node in line: " + node.getNodeName()); - } - } - } - return line; - } + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eTmp = (Element) node; + switch (node.getNodeName()) { + case ("Graphics"): + edgeParser.parseGraphics(line, (Element) node); + break; + case ("BiopaxRef"): + line.addBiopaxReference(eTmp.getTextContent()); + break; + case ("Comment"): + line.addComment(eTmp.getTextContent()); + break; + default: + logger.warn("Unknown node in line: " + node.getNodeName()); + } + } + } + return line; + } - @Override - public String toXml(Edge node) throws ConverterException { - throw new NotImplementedException(); - } + @Override + public String toXml(Edge node) throws ConverterException { + throw new NotImplementedException(); + } - @Override - public String toXml(Collection<Edge> list) throws ConverterException { - throw new NotImplementedException(); - } + @Override + public String toXml(Collection<Edge> list) throws ConverterException { + throw new NotImplementedException(); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeParser.java index dc083bad42..d1d4c91cb6 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/EdgeParser.java @@ -2,14 +2,11 @@ package lcsb.mapviewer.wikipathway.XML; import java.awt.geom.Line2D; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.Pair; @@ -17,12 +14,7 @@ import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.wikipathway.model.Direction; -import lcsb.mapviewer.wikipathway.model.Edge; -import lcsb.mapviewer.wikipathway.model.GpmlLineConnectorType; -import lcsb.mapviewer.wikipathway.model.GpmlLineType; -import lcsb.mapviewer.wikipathway.model.PointData; -import lcsb.mapviewer.wikipathway.model.UnknownTypeException; +import lcsb.mapviewer.wikipathway.model.*; /** * Parser class that creates {@link Edge} objects from Xml {@link Element node}. @@ -32,548 +24,547 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class EdgeParser extends ElementGpmlParser<Edge> { - /** - * Parser used for extracting {@link lcsb.mapviewer.model.map.MiriamData - * references} from GPML model. - */ - private ReferenceParser referenceParser = new ReferenceParser(); - - /** - * Parser used for extracting {@link PointData points} from GPML xml nodes. - */ - private PointDataParser pointParser = new PointDataParser(); - - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(EdgeParser.class); - - /** - * First id value used for generating identifiers during conversion. - */ - private static final int INITIAL_ID_VALUE = 10000; - - /** - * This is default lenght of lines when lines are drawn in - * {@link GpmlLineConnectorType#ELBOW} mode, but without specifing - * coordinates. - */ - private static final double DEFAULT_DISTNACE = 20; - - /** - * Counter used for generating identifiers if identifiers aren't provided by - * the gpml model. - */ - private static int idCounter = INITIAL_ID_VALUE; - - /** - * This function get new id for interactions that don't have id. - * - * @return String - new id - */ - private String getNewId() { - idCounter++; - return "id" + idCounter; - } - - /** - * Creates {@link Edge} from xml node. - * - * @return {@link Edge} from xml node - * @throws ConverterException - * thrown when there is a problem with parsing edge - */ - @Override - public Edge parse(Element eElement) throws ConverterException { - - String graphId = eElement.getAttribute("GraphId"); - if (graphId == null || graphId.equals("")) { - graphId = getNewId(); - } - Edge edge = new Edge(graphId); - - for (Pair<String, String> entry : getAttributes(eElement)) { - switch (entry.getLeft()) { - case ("GraphId"): - break; - case ("GroupRef"): - edge.setGroupRef(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); - break; - } - } - - NodeList nodes = eElement.getChildNodes(); - boolean graphicsParsed = false; - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - Element element = (Element) node; - switch (node.getNodeName()) { - // references (annotations) - case ("Xref"): - MiriamData md = referenceParser.parse(element); - if (md != null) { - edge.addReference(md); - } - break; - case ("Comment"): - edge.addComment(node.getTextContent()); - break; - // references (annotations) - case ("BiopaxRef"): - edge.getBiopaxReferences().add(node.getTextContent()); - break; - case ("Graphics"): - graphicsParsed = true; - parseGraphics(edge, element); - break; - case ("Attribute"): - parseAttribute(element, edge); - break; - default: - logger.warn(edge.getWarningPrefix() + "Unknown edge node: " + node.getNodeName() + "."); - break; - } - } - } - if (!graphicsParsed) { - throw new ConverterException(edge.getWarningPrefix() + "No Graphics information found for edge."); - } - return edge; - } - - /** - * Parses graphics xml node that is part of edge xml node. - * - * @param edge - * edge which is parsed - * @param graphicsNode - * xml node - * @throws ConverterException - * thrown when data for the edge is invalid - */ - protected void parseGraphics(Edge edge, Element graphicsNode) throws ConverterException { - List<Element> points = new ArrayList<Element>(); - List<Element> anchors = new ArrayList<Element>(); - - GpmlLineConnectorType connectorType = GpmlLineConnectorType.STRAIGHT; - - for (Pair<String, String> entry : getAttributes(graphicsNode)) { - switch (entry.getLeft()) { - case ("ConnectorType"): - connectorType = GpmlLineConnectorType.getByGpmlName(entry.getRight()); - break; - case ("LineThickness"): - // line thicknes - edge.getLine().setWidth(entry.getRight()); - break; - case ("LineStyle"): - // line type - GpmlLineType lineType = GpmlLineType.getByGpmlName(entry.getRight()); - edge.getLine().setType(lineType.getCorrespondingGlobalLineType()); - break; - case ("ZOrder"): - edge.setzOrder(Integer.valueOf(entry.getRight())); - break; - case ("Color"): - // graphics color - edge.setColor(hexStringToColor(entry.getRight())); - break; - default: - logger.warn("Unknown attribute of " + graphicsNode.getNodeName() + " node: " + entry.getLeft()); - break; - } - } - - NodeList nodes; - nodes = graphicsNode.getChildNodes(); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if ("Point".equalsIgnoreCase(node.getNodeName())) { - points.add((Element) node); - } else if ("Anchor".equalsIgnoreCase(node.getNodeName())) { - anchors.add((Element) node); - } else { - logger.warn(edge.getWarningPrefix() + "Unknown graphics edge node: " + node.getNodeName() + "."); - } - } - } - - // lines - - List<PointData> pointDataList = new ArrayList<>(); - - for (int j = 0; j < points.size(); j++) { - Node point = points.get(j); - PointData pointData = pointParser.parse((Element) point); - - pointDataList.add(pointData); - if (j == 0 && pointData.hasGraphRef()) { - edge.setStart(pointData.getGraphRef()); - } - if (j == points.size() - 1 && pointData.hasGraphRef()) { - edge.setEnd(pointData.getGraphRef()); - } - - edge.setType(pointData.getType()); - } - - edge.getLine().setPoints(getPoints(edge.getWarningPrefix(), pointDataList, connectorType)); - if (edge.getLine().getPoints().size() < 2) { - throw new ConverterException(edge.getWarningPrefix() + "Contains too less points. At least two points are required in a line."); - } - double lineLength = 0; - for (Line2D line : edge.getLine().getLines()) { - lineLength += line.getP1().distance(line.getP2()); - } - if (lineLength <= Configuration.EPSILON) { - throw new ConverterException(edge.getWarningPrefix() + "Line cannot have 0 length."); - } - - // anchors - for (Element anchor : anchors) { - String anchorId = anchor.getAttribute("GraphId"); - String position = anchor.getAttribute("Position"); - if (anchorId != null && !anchorId.isEmpty()) { - edge.addAnchor(anchorId); - // if our edge is not connected from at first point but we have anchor - // there, then set this anchor there (so we could merge it later on) - if (edge.getStart() == null && "0.0".equals(position)) { - edge.setStart(anchorId); - } - // if our edge is not connected from at last point but we have anchor - // there, then set this anchor there (so we could merge it later on) - if (edge.getEnd() == null && "1.0".equals(position)) { - edge.setEnd(anchorId); - } - } - } - } - - /** - * This method transforms list of {@link PointData points} from gpml xml into - * list of standard {@link Point2D points}. - * - * @param warningPrefix - * prefix that should be used for warnings - * @param pointDataList - * list of points from gpml format - * @param connectorType - * {@link GpmlLineConnectorType type} defining how points are - * connected in gpml format - * @return list of standard {@link Point2D points} obtained from input data - * @throws UnknownGpmlLineConnectorTypeException - * thrown when {@link GpmlLineConnectorType type} is unknown - * @throws InvalidElbowConnectorException - * thrown when input data define invalid line - * @throws UnknownTypeException - * throw when connector type is invalid - */ - private List<Point2D> getPoints(String warningPrefix, List<PointData> pointDataList, GpmlLineConnectorType connectorType) - throws InvalidElbowConnectorException, UnknownTypeException { - List<Point2D> result = new ArrayList<>(); - switch (connectorType) { - // line is a list of perpendicular segments - case ELBOW: - Direction from = pointDataList.get(0).getDirection(); - Direction to = pointDataList.get(pointDataList.size() - 1).getDirection(); - - if (from == null) { - from = Direction.WEST; - } - if (to == null) { - to = Direction.EAST; - } - - // how many segments do we have - int lines = computeNumberOfPerpendicularSegments(warningPrefix, pointDataList.get(0), pointDataList.get(pointDataList.size() - 1)); - // now we know how many segments should be i the line - - // if segments are defined in the input the it's easy - if (lines == pointDataList.size()) { - List<Point2D> points = new ArrayList<>(); - for (PointData pd : pointDataList) { - points.add(pd.toPoint()); - } - result = preparePerpendicularLines(from, points); - - // if we know how many segments should be in the line, but we have - // only first and last point - // then we need to add missing points (some default behaviour). - } else if (pointDataList.size() == 2) { - List<Point2D> points = new ArrayList<>(); - points.add(pointDataList.get(0).toPoint()); - points.add(pointDataList.get(1).toPoint()); - // add middle point - points.add(1, computeDefaultPoint(from, points.get(0))); - // CHECKSTYLE:OFF - // if something is still missing then add defult beginning line - if (lines > 3) { - points.add(2, computeDefaultPoint(to, points.get(2))); - } - // if something is still missing then add defult end line - if (lines > 4) { - double x = (points.get(1).getX() + points.get(2).getX()) / 2; - double y = (points.get(1).getY() + points.get(2).getY()) / 2; - points.add(2, new Point2D.Double(x, y)); - } - // if something is still missing then there is something terrible - // wrong - if (lines > 5) { - throw new InvalidElbowConnectorException(warningPrefix + " Line with connector type " + connectorType + " contains too many segments: " + lines); - } - // CHECKSTYLE:ON - - // and now transform the points into perpendicular segments - result = preparePerpendicularLines(from, points); - - // if number of expectred segments is lower than number of defined - // segments then we probably missed something, let's assume that in - // gpml file the data is correct and parse it - } else if (pointDataList.size() > lines) { - List<Point2D> points = new ArrayList<>(); - for (PointData pd : pointDataList) { - points.add(pd.toPoint()); - } - result = preparePerpendicularLines(from, points); - - // if number of expectred segments is different than number of defined - // segments then something is wrong - } else { - throw new InvalidElbowConnectorException( - warningPrefix + "Don't know how to prepare lines. " + connectorType + " contains invalid number of points: " + pointDataList.size() - + ". Expected: " + lines); - } - - break; - - // if line is straight then pass input points into the output - case STRAIGHT: - for (PointData pointData : pointDataList) { - result.add(pointData.toPoint()); - } - break; - // if line is segmented then pass input points into the output - case SEGMENTED: - for (PointData pointData : pointDataList) { - result.add(pointData.toPoint()); - } - break; - // if line is curved then inform user that we don't support it and create - // a default one - case CURVED: - logger.warn(warningPrefix + "Curved connections are not supported."); - for (PointData pointData : pointDataList) { - result.add(pointData.toPoint()); - } - break; - default: - throw new UnknownTypeException(warningPrefix + "Connector type is not supported: " + connectorType); - } - return result; - } - - /** - * Method that computes number of perpendicular lines that should connect - * start point with the end point. - * - * @param warningPrefix - * string used as a prefix for warnings/errors - * @param start - * starting point - * @param end - * end point - * @return number of perpendicular lines that should connect start point with - * the end point - * @throws InvalidElbowConnectorException - * thrown when output cannot be computed because input data is - * invalid - */ - private int computeNumberOfPerpendicularSegments(String warningPrefix, PointData start, PointData end) throws InvalidElbowConnectorException { - Point2D fromPoint = start.toPoint(); - Point2D toPoint = end.toPoint(); - - Direction from = start.getDirection(); - if (from == null) { - from = Direction.WEST; - } - Direction to = end.getDirection(); - if (to == null) { - to = Direction.EAST; - } - - // result (2 is the minimu) - int lines = 2; - - // if line starts and ends i nthe same axis then number of segments - // should be at least3 - if (from.getAxis().equals(to.getAxis())) { - lines++; - } - - // if they are not starting and ending in the same direction (for - // instance they both start from NORTH) - // then check if some addition lines are needed - if (!from.equals(to)) { - int addition = 0; - // check if begining requires additional lines because the end is - // overlapping the beginning - switch (from) { - case EAST: - if (fromPoint.getX() >= toPoint.getX()) { - addition = 2; - } - break; - case WEST: - if (fromPoint.getX() <= toPoint.getX()) { - addition = 2; - } - break; - case NORTH: - if (fromPoint.getY() <= toPoint.getY()) { - addition = 2; - } - break; - case SOUTH: - if (fromPoint.getY() >= toPoint.getY()) { - addition = 2; - } - break; - default: - throw new InvalidElbowConnectorException(warningPrefix + "Unknown direction: " + from); - } - // check if emdrequires additional lines because the beginning is - // overlapping end part - switch (to) { - case EAST: - if (fromPoint.getX() <= toPoint.getX()) { - addition = 2; - } - break; - case WEST: - if (fromPoint.getX() >= toPoint.getX()) { - addition = 2; - } - break; - case NORTH: - if (fromPoint.getY() >= toPoint.getY()) { - addition = 2; - } - break; - case SOUTH: - if (fromPoint.getY() <= toPoint.getY()) { - addition = 2; - } - break; - default: - throw new InvalidElbowConnectorException(warningPrefix + "Unknown direction: " + from); - } - lines += addition; - } - return lines; - } - - /** - * Creates point that defines default perpendicular line from input point. - * - * @param from - * direction from which point is connected - * @param original - * point from where we want to have a line - * @return point that defines default perpendicular line from input point - */ - private Point2D computeDefaultPoint(Direction from, Point2D original) { - switch (from) { - case NORTH: - return new Point2D.Double(original.getX(), original.getY() - DEFAULT_DISTNACE); - case SOUTH: - return new Point2D.Double(original.getX(), original.getY() + DEFAULT_DISTNACE); - case EAST: - return new Point2D.Double(original.getX() + DEFAULT_DISTNACE, original.getY()); - case WEST: - return new Point2D.Double(original.getX() - DEFAULT_DISTNACE, original.getY()); - default: - throw new InvalidStateException("Unknown direction: " + from); - } - } - - /** - * Creates perpendicular lines going through all input points. - * - * @param from - * in which direction should go the first line - * @param points - * set of points through which perpendicular line should go - * @return perpendicular lines going through all input points - */ - private List<Point2D> preparePerpendicularLines(Direction from, List<Point2D> points) { - List<Point2D> result = new ArrayList<>(); - result.add(points.get(0)); - Point2D lastPoint = points.get(0); - for (int i = 1; i < points.size(); i++) { - Point2D point = points.get(i); - switch (from.getAxis()) { - case NORTH_SOUTH: - result.add(new Point2D.Double(lastPoint.getX(), point.getY())); - break; - case EAST_WEST: - result.add(new Point2D.Double(point.getX(), lastPoint.getY())); - break; - default: - throw new InvalidStateException("Unknown direction axis: " + from.getAxis()); - } - lastPoint = result.get(i); - from = from.nextClockwiseDirection(); - } - result.add(points.get(points.size() - 1)); - return result; - } - - /** - * Creates new {@link Edge} object with unique identifier. - * - * @return new {@link Edge} object with unique identifier - */ - public Edge createEmpty() { - return new Edge(getNewId()); - } - - /** - * Method that parses {@link Edge} xml attribute. - * - * @param eTmp - * xml node with attribute - * @param edge - * edge where data should be added - */ - private void parseAttribute(Element eTmp, Edge edge) { - String key = eTmp.getAttribute("Key"); - String value = eTmp.getAttribute("Value"); - switch (key) { - case ("org.pathvisio.core.ds"): - // skip for now (no idea what des it mean) - break; - case ("org.pathvisio.core.id"): - // skip for now (no idea what des it mean) - break; - default: - logger.warn(edge.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); - break; - } - } - - @Override - public String toXml(Edge node) throws ConverterException { - throw new NotImplementedException(); - } - - @Override - public String toXml(Collection<Edge> list) throws ConverterException { - throw new NotImplementedException(); - } + /** + * First id value used for generating identifiers during conversion. + */ + private static final int INITIAL_ID_VALUE = 10000; + /** + * This is default lenght of lines when lines are drawn in + * {@link GpmlLineConnectorType#ELBOW} mode, but without specifing coordinates. + */ + private static final double DEFAULT_DISTNACE = 20; + /** + * Counter used for generating identifiers if identifiers aren't provided by the + * gpml model. + */ + private static int idCounter = INITIAL_ID_VALUE; + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(EdgeParser.class); + /** + * Parser used for extracting {@link lcsb.mapviewer.model.map.MiriamData + * references} from GPML model. + */ + private ReferenceParser referenceParser = new ReferenceParser(); + /** + * Parser used for extracting {@link PointData points} from GPML xml nodes. + */ + private PointDataParser pointParser = new PointDataParser(); + + /** + * This function get new id for interactions that don't have id. + * + * @return String - new id + */ + private String getNewId() { + idCounter++; + return "id" + idCounter; + } + + /** + * Creates {@link Edge} from xml node. + * + * @return {@link Edge} from xml node + * @throws ConverterException + * thrown when there is a problem with parsing edge + */ + @Override + public Edge parse(Element eElement) throws ConverterException { + + String graphId = eElement.getAttribute("GraphId"); + if (graphId == null || graphId.equals("")) { + graphId = getNewId(); + } + Edge edge = new Edge(graphId); + + for (Pair<String, String> entry : getAttributes(eElement)) { + switch (entry.getLeft()) { + case ("GraphId"): + break; + case ("GroupRef"): + edge.setGroupRef(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); + break; + } + } + + NodeList nodes = eElement.getChildNodes(); + boolean graphicsParsed = false; + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node; + switch (node.getNodeName()) { + // references (annotations) + case ("Xref"): + MiriamData md = referenceParser.parse(element); + if (md != null) { + edge.addReference(md); + } + break; + case ("Comment"): + edge.addComment(node.getTextContent()); + break; + // references (annotations) + case ("BiopaxRef"): + edge.getBiopaxReferences().add(node.getTextContent()); + break; + case ("Graphics"): + graphicsParsed = true; + parseGraphics(edge, element); + break; + case ("Attribute"): + parseAttribute(element, edge); + break; + default: + logger.warn(edge.getWarningPrefix() + "Unknown edge node: " + node.getNodeName() + "."); + break; + } + } + } + if (!graphicsParsed) { + throw new ConverterException(edge.getWarningPrefix() + "No Graphics information found for edge."); + } + return edge; + } + + @Override + public String toXml(Edge node) throws ConverterException { + throw new NotImplementedException(); + } + + @Override + public String toXml(Collection<Edge> list) throws ConverterException { + throw new NotImplementedException(); + } + + /** + * Parses graphics xml node that is part of edge xml node. + * + * @param edge + * edge which is parsed + * @param graphicsNode + * xml node + * @throws ConverterException + * thrown when data for the edge is invalid + */ + protected void parseGraphics(Edge edge, Element graphicsNode) throws ConverterException { + List<Element> points = new ArrayList<Element>(); + List<Element> anchors = new ArrayList<Element>(); + + GpmlLineConnectorType connectorType = GpmlLineConnectorType.STRAIGHT; + + for (Pair<String, String> entry : getAttributes(graphicsNode)) { + switch (entry.getLeft()) { + case ("ConnectorType"): + connectorType = GpmlLineConnectorType.getByGpmlName(entry.getRight()); + break; + case ("LineThickness"): + // line thicknes + edge.getLine().setWidth(entry.getRight()); + break; + case ("LineStyle"): + // line type + GpmlLineType lineType = GpmlLineType.getByGpmlName(entry.getRight()); + edge.getLine().setType(lineType.getCorrespondingGlobalLineType()); + break; + case ("ZOrder"): + edge.setzOrder(Integer.valueOf(entry.getRight())); + break; + case ("Color"): + // graphics color + edge.setColor(hexStringToColor(entry.getRight())); + break; + default: + logger.warn("Unknown attribute of " + graphicsNode.getNodeName() + " node: " + entry.getLeft()); + break; + } + } + + NodeList nodes; + nodes = graphicsNode.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if ("Point".equalsIgnoreCase(node.getNodeName())) { + points.add((Element) node); + } else if ("Anchor".equalsIgnoreCase(node.getNodeName())) { + anchors.add((Element) node); + } else { + logger.warn(edge.getWarningPrefix() + "Unknown graphics edge node: " + node.getNodeName() + "."); + } + } + } + + // lines + + List<PointData> pointDataList = new ArrayList<>(); + + for (int j = 0; j < points.size(); j++) { + Node point = points.get(j); + PointData pointData = pointParser.parse((Element) point); + + pointDataList.add(pointData); + if (j == 0 && pointData.hasGraphRef()) { + edge.setStart(pointData.getGraphRef()); + } + if (j == points.size() - 1 && pointData.hasGraphRef()) { + edge.setEnd(pointData.getGraphRef()); + } + + edge.setType(pointData.getType()); + } + + edge.getLine().setPoints(getPoints(edge.getWarningPrefix(), pointDataList, connectorType)); + if (edge.getLine().getPoints().size() < 2) { + throw new ConverterException( + edge.getWarningPrefix() + "Contains too less points. At least two points are required in a line."); + } + double lineLength = 0; + for (Line2D line : edge.getLine().getLines()) { + lineLength += line.getP1().distance(line.getP2()); + } + if (lineLength <= Configuration.EPSILON) { + throw new ConverterException(edge.getWarningPrefix() + "Line cannot have 0 length."); + } + + // anchors + for (Element anchor : anchors) { + String anchorId = anchor.getAttribute("GraphId"); + String position = anchor.getAttribute("Position"); + if (anchorId != null && !anchorId.isEmpty()) { + edge.addAnchor(anchorId); + // if our edge is not connected from at first point but we have anchor + // there, then set this anchor there (so we could merge it later on) + if (edge.getStart() == null && "0.0".equals(position)) { + edge.setStart(anchorId); + } + // if our edge is not connected from at last point but we have anchor + // there, then set this anchor there (so we could merge it later on) + if (edge.getEnd() == null && "1.0".equals(position)) { + edge.setEnd(anchorId); + } + } + } + } + + /** + * This method transforms list of {@link PointData points} from gpml xml into + * list of standard {@link Point2D points}. + * + * @param warningPrefix + * prefix that should be used for warnings + * @param pointDataList + * list of points from gpml format + * @param connectorType + * {@link GpmlLineConnectorType type} defining how points are connected + * in gpml format + * @return list of standard {@link Point2D points} obtained from input data + * @throws UnknownGpmlLineConnectorTypeException + * thrown when {@link GpmlLineConnectorType type} is unknown + * @throws InvalidElbowConnectorException + * thrown when input data define invalid line + * @throws UnknownTypeException + * throw when connector type is invalid + */ + private List<Point2D> getPoints(String warningPrefix, List<PointData> pointDataList, + GpmlLineConnectorType connectorType) + throws InvalidElbowConnectorException, UnknownTypeException { + List<Point2D> result = new ArrayList<>(); + switch (connectorType) { + // line is a list of perpendicular segments + case ELBOW: + Direction from = pointDataList.get(0).getDirection(); + Direction to = pointDataList.get(pointDataList.size() - 1).getDirection(); + + if (from == null) { + from = Direction.WEST; + } + if (to == null) { + to = Direction.EAST; + } + + // how many segments do we have + int lines = computeNumberOfPerpendicularSegments(warningPrefix, pointDataList.get(0), + pointDataList.get(pointDataList.size() - 1)); + // now we know how many segments should be i the line + + // if segments are defined in the input the it's easy + if (lines == pointDataList.size()) { + List<Point2D> points = new ArrayList<>(); + for (PointData pd : pointDataList) { + points.add(pd.toPoint()); + } + result = preparePerpendicularLines(from, points); + + // if we know how many segments should be in the line, but we have + // only first and last point + // then we need to add missing points (some default behaviour). + } else if (pointDataList.size() == 2) { + List<Point2D> points = new ArrayList<>(); + points.add(pointDataList.get(0).toPoint()); + points.add(pointDataList.get(1).toPoint()); + // add middle point + points.add(1, computeDefaultPoint(from, points.get(0))); + // CHECKSTYLE:OFF + // if something is still missing then add defult beginning line + if (lines > 3) { + points.add(2, computeDefaultPoint(to, points.get(2))); + } + // if something is still missing then add defult end line + if (lines > 4) { + double x = (points.get(1).getX() + points.get(2).getX()) / 2; + double y = (points.get(1).getY() + points.get(2).getY()) / 2; + points.add(2, new Point2D.Double(x, y)); + } + // if something is still missing then there is something terrible + // wrong + if (lines > 5) { + throw new InvalidElbowConnectorException( + warningPrefix + " Line with connector type " + connectorType + " contains too many segments: " + lines); + } + // CHECKSTYLE:ON + + // and now transform the points into perpendicular segments + result = preparePerpendicularLines(from, points); + + // if number of expectred segments is lower than number of defined + // segments then we probably missed something, let's assume that in + // gpml file the data is correct and parse it + } else if (pointDataList.size() > lines) { + List<Point2D> points = new ArrayList<>(); + for (PointData pd : pointDataList) { + points.add(pd.toPoint()); + } + result = preparePerpendicularLines(from, points); + + // if number of expectred segments is different than number of defined + // segments then something is wrong + } else { + throw new InvalidElbowConnectorException( + warningPrefix + "Don't know how to prepare lines. " + connectorType + " contains invalid number of points: " + + pointDataList.size() + + ". Expected: " + lines); + } + + break; + + // if line is straight then pass input points into the output + case STRAIGHT: + for (PointData pointData : pointDataList) { + result.add(pointData.toPoint()); + } + break; + // if line is segmented then pass input points into the output + case SEGMENTED: + for (PointData pointData : pointDataList) { + result.add(pointData.toPoint()); + } + break; + // if line is curved then inform user that we don't support it and create + // a default one + case CURVED: + logger.warn(warningPrefix + "Curved connections are not supported."); + for (PointData pointData : pointDataList) { + result.add(pointData.toPoint()); + } + break; + default: + throw new UnknownTypeException(warningPrefix + "Connector type is not supported: " + connectorType); + } + return result; + } + + /** + * Method that computes number of perpendicular lines that should connect start + * point with the end point. + * + * @param warningPrefix + * string used as a prefix for warnings/errors + * @param start + * starting point + * @param end + * end point + * @return number of perpendicular lines that should connect start point with + * the end point + * @throws InvalidElbowConnectorException + * thrown when output cannot be computed because input data is invalid + */ + private int computeNumberOfPerpendicularSegments(String warningPrefix, PointData start, PointData end) + throws InvalidElbowConnectorException { + Point2D fromPoint = start.toPoint(); + Point2D toPoint = end.toPoint(); + + Direction from = start.getDirection(); + if (from == null) { + from = Direction.WEST; + } + Direction to = end.getDirection(); + if (to == null) { + to = Direction.EAST; + } + + // result (2 is the minimu) + int lines = 2; + + // if line starts and ends i nthe same axis then number of segments + // should be at least3 + if (from.getAxis().equals(to.getAxis())) { + lines++; + } + + // if they are not starting and ending in the same direction (for + // instance they both start from NORTH) + // then check if some addition lines are needed + if (!from.equals(to)) { + int addition = 0; + // check if begining requires additional lines because the end is + // overlapping the beginning + switch (from) { + case EAST: + if (fromPoint.getX() >= toPoint.getX()) { + addition = 2; + } + break; + case WEST: + if (fromPoint.getX() <= toPoint.getX()) { + addition = 2; + } + break; + case NORTH: + if (fromPoint.getY() <= toPoint.getY()) { + addition = 2; + } + break; + case SOUTH: + if (fromPoint.getY() >= toPoint.getY()) { + addition = 2; + } + break; + default: + throw new InvalidElbowConnectorException(warningPrefix + "Unknown direction: " + from); + } + // check if emdrequires additional lines because the beginning is + // overlapping end part + switch (to) { + case EAST: + if (fromPoint.getX() <= toPoint.getX()) { + addition = 2; + } + break; + case WEST: + if (fromPoint.getX() >= toPoint.getX()) { + addition = 2; + } + break; + case NORTH: + if (fromPoint.getY() >= toPoint.getY()) { + addition = 2; + } + break; + case SOUTH: + if (fromPoint.getY() <= toPoint.getY()) { + addition = 2; + } + break; + default: + throw new InvalidElbowConnectorException(warningPrefix + "Unknown direction: " + from); + } + lines += addition; + } + return lines; + } + + /** + * Creates point that defines default perpendicular line from input point. + * + * @param from + * direction from which point is connected + * @param original + * point from where we want to have a line + * @return point that defines default perpendicular line from input point + */ + private Point2D computeDefaultPoint(Direction from, Point2D original) { + switch (from) { + case NORTH: + return new Point2D.Double(original.getX(), original.getY() - DEFAULT_DISTNACE); + case SOUTH: + return new Point2D.Double(original.getX(), original.getY() + DEFAULT_DISTNACE); + case EAST: + return new Point2D.Double(original.getX() + DEFAULT_DISTNACE, original.getY()); + case WEST: + return new Point2D.Double(original.getX() - DEFAULT_DISTNACE, original.getY()); + default: + throw new InvalidStateException("Unknown direction: " + from); + } + } + + /** + * Creates perpendicular lines going through all input points. + * + * @param from + * in which direction should go the first line + * @param points + * set of points through which perpendicular line should go + * @return perpendicular lines going through all input points + */ + private List<Point2D> preparePerpendicularLines(Direction from, List<Point2D> points) { + List<Point2D> result = new ArrayList<>(); + result.add(points.get(0)); + Point2D lastPoint = points.get(0); + for (int i = 1; i < points.size(); i++) { + Point2D point = points.get(i); + switch (from.getAxis()) { + case NORTH_SOUTH: + result.add(new Point2D.Double(lastPoint.getX(), point.getY())); + break; + case EAST_WEST: + result.add(new Point2D.Double(point.getX(), lastPoint.getY())); + break; + default: + throw new InvalidStateException("Unknown direction axis: " + from.getAxis()); + } + lastPoint = result.get(i); + from = from.nextClockwiseDirection(); + } + result.add(points.get(points.size() - 1)); + return result; + } + + /** + * Creates new {@link Edge} object with unique identifier. + * + * @return new {@link Edge} object with unique identifier + */ + public Edge createEmpty() { + return new Edge(getNewId()); + } + + /** + * Method that parses {@link Edge} xml attribute. + * + * @param eTmp + * xml node with attribute + * @param edge + * edge where data should be added + */ + private void parseAttribute(Element eTmp, Edge edge) { + String key = eTmp.getAttribute("Key"); + String value = eTmp.getAttribute("Value"); + switch (key) { + case ("org.pathvisio.core.ds"): + // skip for now (no idea what des it mean) + break; + case ("org.pathvisio.core.id"): + // skip for now (no idea what des it mean) + break; + default: + logger.warn(edge.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); + break; + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParser.java index 7cde314e72..d1e6398aaa 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParser.java @@ -1,21 +1,17 @@ package lcsb.mapviewer.wikipathway.XML; -import java.awt.Color; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; +import java.awt.*; +import java.util.*; import java.util.List; -import java.util.Set; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.ConverterException; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; - /** * Generic parser for GPML xml structures. * @@ -26,114 +22,113 @@ import org.w3c.dom.Node; */ public abstract class ElementGpmlParser<T> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ElementGpmlParser.class); - - /** - * Color that should be used when we have transparent color. - */ - private static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0); + /** + * Color that should be used when we have transparent color. + */ + private static final Color TRANSPARENT_COLOR = new Color(0, 0, 0, 0); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ElementGpmlParser.class); - /** - * Creates object from xml node given in parameter. - * - * @param node - * xml node from which object will be created - * @return object created from xml node - * @throws ConverterException - * thrown when there is severe problem with parsing xml node - */ - public abstract T parse(Element node) throws ConverterException; + /** + * Creates object from xml node given in parameter. + * + * @param node + * xml node from which object will be created + * @return object created from xml node + * @throws ConverterException + * thrown when there is severe problem with parsing xml node + */ + public abstract T parse(Element node) throws ConverterException; - /** - * Converts object into xml string (in gpml format). - * - * @param object - * object to transform - * @return xml string representing object - * @throws ConverterException - * thrown when there is a problem with converting into xml - */ - public abstract String toXml(T object) throws ConverterException; + /** + * Converts object into xml string (in gpml format). + * + * @param object + * object to transform + * @return xml string representing object + * @throws ConverterException + * thrown when there is a problem with converting into xml + */ + public abstract String toXml(T object) throws ConverterException; - /** - * Converts list of objects into xml string (in gpml format) representing this - * list. - * - * @param list - * list objects to transform - * @return xml string representing objects - * @throws ConverterException - * thrown when there is a problem with converting into xml - */ - public abstract String toXml(Collection<T> list) throws ConverterException; + /** + * Converts list of objects into xml string (in gpml format) representing this + * list. + * + * @param list + * list objects to transform + * @return xml string representing objects + * @throws ConverterException + * thrown when there is a problem with converting into xml + */ + public abstract String toXml(Collection<T> list) throws ConverterException; - /** - * Creates list of object from list of xml nodes. - * - * @param nodes - * list of xml nodes to parse - * @return list of object from list of xml nodes - * @throws ConverterException - * thrown when there is severe problem with parsing xml node - */ - public List<T> parseCollection(Collection<Node> nodes) throws ConverterException { - List<T> result = new ArrayList<>(); - for (Node node : nodes) { - if (node.getNodeType() == Node.ELEMENT_NODE) { - T element = parse((Element) node); - // add only not null elements (null might appear when node is partially - // invalid and warnings are set) - if (element != null) { - result.add(element); - } - } - } - return result; - } + /** + * Creates list of object from list of xml nodes. + * + * @param nodes + * list of xml nodes to parse + * @return list of object from list of xml nodes + * @throws ConverterException + * thrown when there is severe problem with parsing xml node + */ + public List<T> parseCollection(Collection<Node> nodes) throws ConverterException { + List<T> result = new ArrayList<>(); + for (Node node : nodes) { + if (node.getNodeType() == Node.ELEMENT_NODE) { + T element = parse((Element) node); + // add only not null elements (null might appear when node is partially + // invalid and warnings are set) + if (element != null) { + result.add(element); + } + } + } + return result; + } - /** - * Transforms string representing color into {@link Color}. - * - * @param hex - * string representing color - * @return {@link Color} representation of input string - */ - protected Color hexStringToColor(String hex) { - if (hex == null || hex.isEmpty()) { - return null; - } - if ("Transparent".equalsIgnoreCase(hex)) { - return TRANSPARENT_COLOR; - } - // CHECKSTYLE:OFF - if (hex.length() != 6) { - throw new InvalidArgumentException("Unknown color format: " + hex); - } - return new Color(Integer.valueOf(hex, 16)); - // CHECKSTYLE:ON - } + /** + * Transforms string representing color into {@link Color}. + * + * @param hex + * string representing color + * @return {@link Color} representation of input string + */ + protected Color hexStringToColor(String hex) { + if (hex == null || hex.isEmpty()) { + return null; + } + if ("Transparent".equalsIgnoreCase(hex)) { + return TRANSPARENT_COLOR; + } + // CHECKSTYLE:OFF + if (hex.length() != 6) { + throw new InvalidArgumentException("Unknown color format: " + hex); + } + return new Color(Integer.valueOf(hex, 16)); + // CHECKSTYLE:ON + } - /** - * Returns list of {@link Node} attributes. - * - * @param node - * xml node - * @return set of pairs containing xml node attributes - */ - protected Set<Pair<String, String>> getAttributes(Node node) { - Set<Pair<String, String>> result = new HashSet<>(); - NamedNodeMap map = node.getAttributes(); - for (int k = 0; k < map.getLength(); k++) { - Node attribute = map.item(k); - String name = attribute.getNodeName(); - String value = attribute.getNodeValue(); - result.add(new Pair<String, String>(name, value)); - } - return result; - } + /** + * Returns list of {@link Node} attributes. + * + * @param node + * xml node + * @return set of pairs containing xml node attributes + */ + protected Set<Pair<String, String>> getAttributes(Node node) { + Set<Pair<String, String>> result = new HashSet<>(); + NamedNodeMap map = node.getAttributes(); + for (int k = 0; k < map.getLength(); k++) { + Node attribute = map.item(k); + String name = attribute.getNodeName(); + String value = attribute.getNodeValue(); + result.add(new Pair<String, String>(name, value)); + } + return result; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GPMLToModel.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GPMLToModel.java index 90367ca264..8b14d6f2a5 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GPMLToModel.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GPMLToModel.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.wikipathway.XML; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.model.map.model.Model; @@ -16,36 +14,36 @@ import lcsb.mapviewer.wikipathway.model.Graph; */ public class GPMLToModel { - /** - * This function creates model from gpml input stream. - * - * @param stream - * input stream that contains gpml data - * @return {@link Model} created from gpml file - * @throws IOException - * thrown when there is a problem with input file - * @throws ConverterException - * thrown when model couldn't be created - */ - public Model getModel(InputStream stream) throws IOException, ConverterException { - Graph graph = new GpmlParser().createGraph(stream); - Model model = new ModelContructor().getModel(graph); - return model; - } + /** + * This function creates model from gpml input stream. + * + * @param stream + * input stream that contains gpml data + * @return {@link Model} created from gpml file + * @throws IOException + * thrown when there is a problem with input file + * @throws ConverterException + * thrown when model couldn't be created + */ + public Model getModel(InputStream stream) throws IOException, ConverterException { + Graph graph = new GpmlParser().createGraph(stream); + Model model = new ModelContructor().getModel(graph); + return model; + } - /** - * This function creates model from gpml file. - * - * @param fileName - * name of the gpml file - * @return {@link Model} created from gpml file - * @throws IOException - * thrown when there is a problem with input file - * @throws ConverterException - * thrown when the was a problem with creating a model - */ - public Model getModel(String fileName) throws IOException, ConverterException { - FileInputStream fis = new FileInputStream(fileName); - return getModel(fis); - } + /** + * This function creates model from gpml file. + * + * @param fileName + * name of the gpml file + * @return {@link Model} created from gpml file + * @throws IOException + * thrown when there is a problem with input file + * @throws ConverterException + * thrown when the was a problem with creating a model + */ + public Model getModel(String fileName) throws IOException, ConverterException { + FileInputStream fis = new FileInputStream(fileName); + return getModel(fis); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GpmlParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GpmlParser.java index 671ebacb11..4563d839db 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GpmlParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GpmlParser.java @@ -2,42 +2,21 @@ package lcsb.mapviewer.wikipathway.XML; import java.io.IOException; import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.logging.log4j.*; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import java.util.*; + +import javax.xml.parsers.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import org.xml.sax.SAXException; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.wikipathway.model.Edge; -import lcsb.mapviewer.wikipathway.model.Graph; -import lcsb.mapviewer.wikipathway.model.Group; -import lcsb.mapviewer.wikipathway.model.Interaction; -import lcsb.mapviewer.wikipathway.model.InteractionMapping; -import lcsb.mapviewer.wikipathway.model.Label; -import lcsb.mapviewer.wikipathway.model.MergeMapping; -import lcsb.mapviewer.wikipathway.model.PointData; -import lcsb.mapviewer.wikipathway.model.Shape; -import lcsb.mapviewer.wikipathway.model.UnknownTypeException; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.wikipathway.model.*; /** * This class allows to parse @@ -48,610 +27,617 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class GpmlParser { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(GpmlParser.class); - - /** - * Parser used for creating {@link Shape shapes}. - */ - private ShapeParser shapeParser = new ShapeParser(); - - /** - * Parser used for creating {@link lcsb.mapviewer.wikipathway.model.DataNode - * data nodes}. - */ - private DataNodeParser dataNodeParser = new DataNodeParser(); - - /** - * Parser used for creating {@link Label labels}. - */ - private LabelParser labelParser = new LabelParser(); - - /** - * Parser used for creating {@link Edge edges}. - */ - private EdgeParser edgeParser = new EdgeParser(); - - /** - * Parser used for creating {@link lcsb.mapviewer.wikipathway.model.State - * states}. - */ - private StateParser stateParser = new StateParser(); - - /** - * Parser used for creating {@link Edge edges} from line xml nodes. - */ - private EdgeLineParser edgeLineParser = new EdgeLineParser(); - - /** - * Parser used for creating {@link PointData points} from line xml nodes. - */ - private PointDataParser pointParser = new PointDataParser(); - - /** - * This function returns parent interaction for edge that has anchor at one - * end. - * - * @param graph - * model where data is stored - * @param edge - * edge for which interaction is looked for - * @return {@link Interaction} that is parent reaction for given edge. - * @throws CyclicEdgeException - * thrown when parent interaction cannot be found because reactions - * are cyclic - */ - private Interaction getParentInteraction(Graph graph, Edge edge) throws CyclicEdgeException { - // remeber what we already processed (to detect cycles) - Set<Edge> processedEdges = new HashSet<>(); - processedEdges.add(edge); - while (graph.getNodeByGraphId(edge.getEnd()) == null || graph.getNodeByGraphId(edge.getStart()) == null) { - String anchor = null; - if (graph.getEdgeByAnchor(edge.getEnd()) != null) { - anchor = edge.getEnd(); - } else if (graph.getEdgeByAnchor(edge.getStart()) != null) { - anchor = edge.getStart(); - } else { - return null; - } - - edge = graph.getEdgeByAnchor(anchor); - // when we have cycle then return null - if (processedEdges.contains(edge)) { - throw new CyclicEdgeException(edge.getWarningPrefix() + " edge is a part of invalid, cyclic edge"); - } - processedEdges.add(edge); - } - return graph.getInteractionByGraphId(edge.getGraphId()); - } - - /** - * This function sets width and height in given graph. - * - * @param node - * xml node where data is stored - * @param graph - * object where data is stored - */ - protected void setSize(Node node, Graph graph) { - Element eElement = (Element) node; - String boardWidth = eElement.getAttribute("BoardWidth"); - String boardHeight = eElement.getAttribute("BoardHeight"); - graph.setBoardWidth(Math.ceil(Double.parseDouble(boardWidth))); - graph.setBoardHeight(Math.ceil(Double.parseDouble(boardHeight))); - } - - /** - * This function adds groups to graph and nest them. - * - * @param groups - * xml nodes - * @param graph - * object where data is stored - * @throws UnknownAttributeValueException - * thrown when there is a problem with xml attributes - */ - protected void addGroups(List<Node> groups, Graph graph) throws UnknownAttributeValueException { - // Adding Groups to graph - for (Node nNode : groups) { - if (nNode.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) nNode; - String graphId = eElement.getAttribute("GraphId"); - String groupId = eElement.getAttribute("GroupId"); - if (graphId.equals("") || graphId == null) { - graphId = groupId; - } - String style = eElement.getAttribute("Style"); - if ("".equals(style)) { - style = null; - } - if (style != null && - !"Complex".equalsIgnoreCase(style) && - !"Group".equalsIgnoreCase(style)) { - throw new UnknownAttributeValueException( - "Unknown value of \"style\" attribute for group node: " + style + ". Only null, Complex, Group are supported."); - } - Group group = new Group(graphId, groupId); - group.setStyle(style); - graph.addGroup(group); - } - } - // Handling nested groups - Group gr1, gr2; - for (Node nNode : groups) { - if (nNode.getNodeType() == Node.ELEMENT_NODE) { - Element eElement = (Element) nNode; - String groupRef = eElement.getAttribute("GroupRef"); - String groupId = eElement.getAttribute("GroupId"); - if (groupRef != null && !groupRef.equals("")) { - gr1 = graph.getGroupByGroupId(groupRef); - gr2 = graph.getGroupByGroupId(groupId); - gr1.addNode(gr2); - } - } - } - } - - /** - * This function adds edges to graph. It ignores edges that have no connection - * at one end and edges that connects to shapes or labels. - * - * @param nodes - * xml nodes - * @param graph - * object where data is sotred - */ - private void prepareEdges(List<Node> nodes, Graph graph) { - for (Node nNode : nodes) { - if (nNode.getNodeType() == Node.ELEMENT_NODE) { - Edge edge; - try { - edge = edgeParser.parse((Element) nNode); - - if (graph.getLabelByGraphId(edge.getStart()) != null) { - Label label = graph.getLabelByGraphId(edge.getStart()); - label.setTreatAsNode(true); - } - if (graph.getLabelByGraphId(edge.getEnd()) != null) { - Label label = graph.getLabelByGraphId(edge.getEnd()); - label.setTreatAsNode(true); - } - - if (graph.getShapeByGraphId(edge.getStart()) != null) { - Shape shape = graph.getShapeByGraphId(edge.getStart()); - shape.setTreatAsNode(true); - } - if (graph.getShapeByGraphId(edge.getEnd()) != null) { - Shape shape = graph.getShapeByGraphId(edge.getEnd()); - shape.setTreatAsNode(true); - } - if (edge.getStart() == null || edge.getEnd() == null) { - logger.warn(edge.getWarningPrefix() + "Interaction is not connected"); - - } else { - graph.addEdge(edge); - } - } catch (ConverterException e) { - logger.warn(e, e); - } - } - } - } - - /** - * This function transforms Edges into Interactions. First: Edges with - * NodeToNode connection are transformed into Interactions. Second: Edges with - * AnchorToNode connection are added to right interaction. Edges with - * AnchorToAnchor connection are ignored. - * - * @param graph - * object where data is sotred - * @throws InvalidXmlSchemaException - * thrown when the data in input file is invalid - */ - protected void addInteractions(Graph graph) throws InvalidXmlSchemaException { - for (Edge edge : graph.getEdges()) { - if (graph.getNodeByGraphId(edge.getEnd()) != null && graph.getNodeByGraphId(edge.getStart()) != null) { - if (graph.getNodeByGraphId(edge.getEnd()) instanceof Label) { - Label label = (Label) graph.getNodeByGraphId(edge.getEnd()); - label.setTreatAsNode(true); - } - if (graph.getNodeByGraphId(edge.getStart()) instanceof Label) { - Label label = (Label) graph.getNodeByGraphId(edge.getStart()); - label.setTreatAsNode(true); - } - if (graph.getShapeByGraphId(edge.getEnd()) instanceof Shape) { - Shape shape = (Shape) graph.getShapeByGraphId(edge.getEnd()); - shape.setTreatAsNode(true); - } - if (graph.getShapeByGraphId(edge.getStart()) instanceof Shape) { - Shape shape = (Shape) graph.getShapeByGraphId(edge.getStart()); - shape.setTreatAsNode(true); - } - - Interaction interaction = new Interaction(edge); - graph.addInteraction(interaction); - InteractionMapping mapping = InteractionMapping.getInteractionMapping(edge.getType(), edge.getLine().getType()); - if (mapping != null) { - if (mapping.isInteractionWarning()) { - logger.warn(edge.getWarningPrefix() + "Invalid interaction type."); - } - } else { - throw new InvalidXmlSchemaException( - edge.getWarningPrefix() + "Unknown interaction type: " + edge.getType() + " and line type: " + edge.getLine().getType()); - } - } - } - for (Edge edge : graph.getEdges()) { - try { - if (graph.getEdgeByAnchor(edge.getEnd()) != null && graph.getEdgeByAnchor(edge.getStart()) != null) { - logger.warn(edge.getWarningPrefix() + "Interaction can not connect two anchors."); - } else if (graph.getEdgeByAnchor(edge.getEnd()) != null && graph.getNodeByGraphId(edge.getStart()) != null) { - Interaction tmp = getParentInteraction(graph, edge); - if (tmp != null) { - InteractionMapping mapping = InteractionMapping.getInteractionMapping(edge.getType(), edge.getLine().getType()); - if (mapping != null) { - if (mapping.isInputWarning()) { - logger.warn(edge.getWarningPrefix() + "Invalid interaction type as an input to reaction."); - } - if (Modifier.class.isAssignableFrom(mapping.getModelInputReactionNodeType())) { - tmp.addModifier(edge); - } else if (Reactant.class.isAssignableFrom(mapping.getModelInputReactionNodeType())) { - tmp.addReactant(edge); - } else if (Product.class.isAssignableFrom(mapping.getModelInputReactionNodeType())) { - tmp.addProduct(edge); - } else { - throw new InvalidStateException("Unknown internal model type: " + mapping.getModelInputReactionNodeType()); - } - } else { - throw new InvalidXmlSchemaException("Unknown interaction type: " + edge.getType()); - } - } else { - logger.warn(edge.getWarningPrefix() + "Interaction is disconnected."); - } - } else if (graph.getEdgeByAnchor(edge.getStart()) != null && graph.getNodeByGraphId(edge.getEnd()) != null) { - Interaction tmp = getParentInteraction(graph, edge); - if (tmp != null) { - InteractionMapping mapping = InteractionMapping.getInteractionMapping(edge.getType(), edge.getLine().getType()); - if (mapping != null) { - if (mapping.isOutputWarning()) { - logger.warn(edge.getWarningPrefix() + "Invalid interaction type \"" + edge.getType() + "\" as an input to reaction."); - } - if (Modifier.class.isAssignableFrom(mapping.getModelOutputReactionNodeType())) { - tmp.addModifier(edge); - } else if (Reactant.class.isAssignableFrom(mapping.getModelOutputReactionNodeType())) { - tmp.addReactant(edge); - } else if (Product.class.isAssignableFrom(mapping.getModelOutputReactionNodeType())) { - tmp.addProduct(edge); - } else { - throw new InvalidStateException("Unknown internal model type: " + mapping.getModelOutputReactionNodeType()); - } - } else { - throw new InvalidXmlSchemaException("Unknown interaction type: " + edge.getType()); - } - } else { - logger.warn(edge.getWarningPrefix() + "Interaction is disconnected."); - } - } else if (graph.getNodeByGraphId(edge.getEnd()) == null || graph.getNodeByGraphId(edge.getStart()) == null) { - logger.warn(edge.getWarningPrefix() + "Interaction edge is invalid (one end is not connected)."); - } - } catch (CyclicEdgeException e) { - logger.warn(e, e); - } - } - } - - /** - * Creates gpml {@link Graph} model from gpml input stream. - * - * @param stream - * input stream with gpml model - * @return {@link Graph} model - * @throws IOException - * thrown when there is a problem with input file - * @throws ConverterException - * thrown when there is a problem with parsing input file - */ - public Graph createGraph(InputStream stream) throws IOException, ConverterException { - try { - DocumentBuilder builder; - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document document = builder.parse(stream); - - // Get the document's root XML node - NodeList root = document.getElementsByTagName("Pathway"); - - NodeList nodes = root.item(0).getChildNodes(); - - Node dimensionNode = null; - List<Node> dataNodes = new ArrayList<Node>(); - List<Node> interactions = new ArrayList<Node>(); - List<Node> labels = new ArrayList<Node>(); - List<Node> groups = new ArrayList<Node>(); - List<Node> shapes = new ArrayList<Node>(); - List<Node> lines = new ArrayList<Node>(); - List<Node> states = new ArrayList<Node>(); - List<Element> attributes = new ArrayList<Element>(); - Node biopax = null; - - Graph graph = new Graph(); - for (int x = 0; x < nodes.getLength(); x++) { - Node node = nodes.item(x); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equalsIgnoreCase("Graphics")) { - dimensionNode = node; - } else if (node.getNodeName().equalsIgnoreCase("DataNode")) { - dataNodes.add(node); - } else if (node.getNodeName().equalsIgnoreCase("Interaction")) { - interactions.add(node); - } else if (node.getNodeName().equalsIgnoreCase("Label")) { - labels.add(node); - } else if (node.getNodeName().equalsIgnoreCase("Group")) { - groups.add(node); - } else if (node.getNodeName().equalsIgnoreCase("Attribute")) { - attributes.add((Element) node); - } else if (node.getNodeName().equalsIgnoreCase("Shape")) { - shapes.add(node); - } else if (node.getNodeName().equalsIgnoreCase("GraphicalLine")) { - lines.add(node); - } else if (node.getNodeName().equalsIgnoreCase("Comment")) { - graph.addComment(node.getTextContent()); - } else if (node.getNodeName().equalsIgnoreCase("BiopaxRef")) { - graph.addBiopaxReferences(node.getTextContent()); - } else if (node.getNodeName().equalsIgnoreCase("State")) { - states.add(node); - } else if (node.getNodeName().equalsIgnoreCase("Biopax")) { - if (biopax != null) { - throw new ConverterException("Biopax node should appear only once"); - } - biopax = node; - } else if (node.getNodeName().equalsIgnoreCase("InfoBox")) { - // infobox can be skipped - continue; - } else if (node.getNodeName().equalsIgnoreCase("Legend")) { - // legend can be skipped - continue; - } else { - logger.warn("Unknown element of gpml file: " + node.getNodeName()); - } - } - } - graph.addLines(parseLines(lines)); - graph.addEdges(parseEdgesFromLines(lines)); - - if (dimensionNode != null) { - setSize(dimensionNode, graph); - } - addGroups(groups, graph); - - graph.addDataNodes(dataNodeParser.parseCollection(dataNodes)); - graph.addLabels(labelParser.parseCollection(labels)); - graph.addShapes(shapeParser.parseCollection(shapes)); - graph.addStates(stateParser.parseCollection(states)); - - prepareEdges(interactions, graph); - - mergeEdges(graph); - - addInteractions(graph); - if (biopax != null) { - graph.setBiopaxData(new BiopaxParser().parse(biopax)); - } - Map<String, String> attributesMap = new HashMap<String, String>(); - for (Element attribute : attributes) { - String key = attribute.getAttribute("Key"); - String value = attribute.getAttribute("Value"); - if (attributesMap.get(key) != null) { - logger.warn("Model xml contains duplicate attributes: " + key); - } else { - attributesMap.put(key, value); - } - } - graph.setAttributes(attributesMap); - return graph; - } catch (ParserConfigurationException e) { - throw new ConverterException("Problem with input data", e); - } catch (SAXException e) { - throw new ConverterException("Problem with input data", e); - } catch (InvalidXmlSchemaException e) { - throw new ConverterException("Problem with input data", e); - } - } - - /** - * This method merge edges that should be merged into single line. - * - * @param graph - * model where edges are stored - */ - private void mergeEdges(Graph graph) { - List<Edge> toExtend = new ArrayList<>(); - List<Edge> toRemove = new ArrayList<>(); - List<Edge> toAdd = new ArrayList<>(); - Map<String, List<Edge>> extendable = new HashMap<>(); - for (Edge edge : graph.getEdges()) { - if (graph.getEdgeByAnchor(edge.getStart()) == edge) { - toExtend.add(edge); - } else if (graph.getEdgeByAnchor(edge.getEnd()) == edge) { - toExtend.add(edge); - } else if (graph.getEdgeByAnchor(edge.getEnd()) != null) { - List<Edge> list = extendable.get(edge.getEnd()); - if (list == null) { - list = new ArrayList<>(); - extendable.put(edge.getEnd(), list); - } - list.add(edge); - } else if (graph.getEdgeByAnchor(edge.getStart()) != null) { - List<Edge> list = extendable.get(edge.getStart()); - if (list == null) { - list = new ArrayList<>(); - extendable.put(edge.getStart(), list); - } - list.add(edge); - } - - } - - for (Edge edge : toExtend) { - String anchor = null; - if (graph.getEdgeByAnchor(edge.getStart()) == edge) { - anchor = edge.getStart(); - } else if (graph.getEdgeByAnchor(edge.getEnd()) == edge) { - anchor = edge.getEnd(); - } - List<Edge> howExtend = extendable.get(anchor); - if (howExtend == null) { - logger.warn(edge.getWarningPrefix() + " Should be connected with another element, but nothing found."); - if (edge.getStart().equals(anchor)) { - edge.setStart(null); - } else if (edge.getEnd().equals(anchor)) { - edge.setEnd(null); - } - } else if (howExtend.size() > 0) { - try { - Edge newEdge = mergeEdges(edge, howExtend.get(0)); - toRemove.add(edge); - toRemove.add(howExtend.get(0)); - toAdd.add(newEdge); - } catch (UnknownMergingMethodException exception) { - toRemove.add(edge); - toRemove.add(howExtend.get(0)); - - logger.warn(exception, exception); - } - } - } - for (Edge e : toRemove) { - graph.removeEdge(e); - } - for (Edge e : toAdd) { - graph.addEdge(e); - } - } - - /** - * Method that merge two {@link Edge edges}. - * - * @param edge1 - * first edge to merge - * @param edge2 - * second edge to merge - * @return new edge that merges two parameters - * @throws UnknownMergingMethodException - * thrown when edges cannot be merged - */ - private Edge mergeEdges(Edge edge1, Edge edge2) throws UnknownMergingMethodException { - MergeMapping mapping = null; - if (edge1.getStart() != null && edge1.getStart().equals(edge2.getStart())) { - mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), true, edge2.getType(), false); - } else if (edge1.getStart() != null && edge1.getStart().equals(edge2.getEnd())) { - mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), true, edge2.getType(), true); - } else if (edge1.getEnd() != null && edge1.getEnd().equals(edge2.getStart())) { - mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), false, edge2.getType(), false); - } else if (edge1.getEnd() != null && edge1.getEnd().equals(edge2.getEnd())) { - mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), false, edge2.getType(), true); - } - if (mapping == null) { - String message = edge1.getWarningPrefix() + edge2.getWarningPrefix() + "Don't know how to merge interactions"; - throw new UnknownMergingMethodException(message); - } - Edge first; - if (mapping.isReversed1()) { - first = edge1.reverse(); - } else { - first = new Edge(edge1); - } - Edge second; - if (mapping.isReversed2()) { - second = edge2.reverse(); - } else { - second = new Edge(edge2); - } - first.extend(second); - - if (!first.getLine().getType().equals(second.getLine().getType())) { - logger.warn( - first.getWarningPrefix() + second.getWarningPrefix() + " merging edges with different line types: " + first.getLine().getType() + ", " - + second.getLine().getType()); - } - first.setType(mapping.getResultType()); - if (mapping.isResultReversed()) { - return first.reverse(); - } else { - return first; - } - } - - /** - * Creates edges from lines when it's possible. - * - * @param lines - * xml nodes with lines - * @return list of edges that could be created from xml nodes - */ - private Collection<Edge> parseEdgesFromLines(List<Node> lines) { - List<Edge> result = new ArrayList<Edge>(); - for (Node lNode : lines) { - try { - Edge line = edgeLineParser.parse((Element) lNode); - if (line.getStart() != null && line.getEnd() != null) { - result.add(line); - } - } catch (ConverterException e) { - logger.warn(e, e); - - } - } - return result; - } - - /** - * Creates lines from the list of gpml xml nodes. - * - * @param lines - * list of xml nodes - * @return list of {@link PolylineData lines} - * @throws UnknownTypeException - * thrown when the type of line defined in xml node is unknown - */ - private Collection<PolylineData> parseLines(List<Node> lines) throws UnknownTypeException { - List<PolylineData> result = new ArrayList<PolylineData>(); - for (Node lNode : lines) { - int refs = 0; - PolylineData line = new PolylineData(); - NodeList nodes = lNode.getChildNodes(); - for (int i = 0; i < nodes.getLength(); i++) { - Node node = nodes.item(i); - if (node.getNodeType() == Node.ELEMENT_NODE) { - if (node.getNodeName().equalsIgnoreCase("Graphics")) { - NodeList nodes2 = node.getChildNodes(); - for (int j = 0; j < nodes2.getLength(); j++) { - Node node2 = nodes2.item(j); - if (node2.getNodeType() == Node.ELEMENT_NODE) { - Element element = (Element) node2; - if (node2.getNodeName().equalsIgnoreCase("Point")) { - PointData point = pointParser.parse(element); - if (point.hasGraphRef()) { - refs++; - } - line.addPoint(point.toPoint()); - } else { - logger.warn("Unknown node in line: " + node2.getNodeName()); - } - } - } - - } else { - logger.warn("Unknown node in line: " + node.getNodeName()); - } - } - } - if (refs < 2) { - result.add(line); - } - } - return result; - } + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(GpmlParser.class); + + /** + * Parser used for creating {@link Shape shapes}. + */ + private ShapeParser shapeParser = new ShapeParser(); + + /** + * Parser used for creating {@link lcsb.mapviewer.wikipathway.model.DataNode + * data nodes}. + */ + private DataNodeParser dataNodeParser = new DataNodeParser(); + + /** + * Parser used for creating {@link Label labels}. + */ + private LabelParser labelParser = new LabelParser(); + + /** + * Parser used for creating {@link Edge edges}. + */ + private EdgeParser edgeParser = new EdgeParser(); + + /** + * Parser used for creating {@link lcsb.mapviewer.wikipathway.model.State + * states}. + */ + private StateParser stateParser = new StateParser(); + + /** + * Parser used for creating {@link Edge edges} from line xml nodes. + */ + private EdgeLineParser edgeLineParser = new EdgeLineParser(); + + /** + * Parser used for creating {@link PointData points} from line xml nodes. + */ + private PointDataParser pointParser = new PointDataParser(); + + /** + * This function returns parent interaction for edge that has anchor at one end. + * + * @param graph + * model where data is stored + * @param edge + * edge for which interaction is looked for + * @return {@link Interaction} that is parent reaction for given edge. + * @throws CyclicEdgeException + * thrown when parent interaction cannot be found because reactions + * are cyclic + */ + private Interaction getParentInteraction(Graph graph, Edge edge) throws CyclicEdgeException { + // remeber what we already processed (to detect cycles) + Set<Edge> processedEdges = new HashSet<>(); + processedEdges.add(edge); + while (graph.getNodeByGraphId(edge.getEnd()) == null || graph.getNodeByGraphId(edge.getStart()) == null) { + String anchor = null; + if (graph.getEdgeByAnchor(edge.getEnd()) != null) { + anchor = edge.getEnd(); + } else if (graph.getEdgeByAnchor(edge.getStart()) != null) { + anchor = edge.getStart(); + } else { + return null; + } + + edge = graph.getEdgeByAnchor(anchor); + // when we have cycle then return null + if (processedEdges.contains(edge)) { + throw new CyclicEdgeException(edge.getWarningPrefix() + " edge is a part of invalid, cyclic edge"); + } + processedEdges.add(edge); + } + return graph.getInteractionByGraphId(edge.getGraphId()); + } + + /** + * This function sets width and height in given graph. + * + * @param node + * xml node where data is stored + * @param graph + * object where data is stored + */ + protected void setSize(Node node, Graph graph) { + Element eElement = (Element) node; + String boardWidth = eElement.getAttribute("BoardWidth"); + String boardHeight = eElement.getAttribute("BoardHeight"); + graph.setBoardWidth(Math.ceil(Double.parseDouble(boardWidth))); + graph.setBoardHeight(Math.ceil(Double.parseDouble(boardHeight))); + } + + /** + * This function adds groups to graph and nest them. + * + * @param groups + * xml nodes + * @param graph + * object where data is stored + * @throws UnknownAttributeValueException + * thrown when there is a problem with xml attributes + */ + protected void addGroups(List<Node> groups, Graph graph) throws UnknownAttributeValueException { + // Adding Groups to graph + for (Node nNode : groups) { + if (nNode.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) nNode; + String graphId = eElement.getAttribute("GraphId"); + String groupId = eElement.getAttribute("GroupId"); + if (graphId.equals("") || graphId == null) { + graphId = groupId; + } + String style = eElement.getAttribute("Style"); + if ("".equals(style)) { + style = null; + } + if (style != null && + !"Complex".equalsIgnoreCase(style) && + !"Group".equalsIgnoreCase(style)) { + throw new UnknownAttributeValueException( + "Unknown value of \"style\" attribute for group node: " + style + + ". Only null, Complex, Group are supported."); + } + Group group = new Group(graphId, groupId); + group.setStyle(style); + graph.addGroup(group); + } + } + // Handling nested groups + Group gr1, gr2; + for (Node nNode : groups) { + if (nNode.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) nNode; + String groupRef = eElement.getAttribute("GroupRef"); + String groupId = eElement.getAttribute("GroupId"); + if (groupRef != null && !groupRef.equals("")) { + gr1 = graph.getGroupByGroupId(groupRef); + gr2 = graph.getGroupByGroupId(groupId); + gr1.addNode(gr2); + } + } + } + } + + /** + * This function adds edges to graph. It ignores edges that have no connection + * at one end and edges that connects to shapes or labels. + * + * @param nodes + * xml nodes + * @param graph + * object where data is sotred + */ + private void prepareEdges(List<Node> nodes, Graph graph) { + for (Node nNode : nodes) { + if (nNode.getNodeType() == Node.ELEMENT_NODE) { + Edge edge; + try { + edge = edgeParser.parse((Element) nNode); + + if (graph.getLabelByGraphId(edge.getStart()) != null) { + Label label = graph.getLabelByGraphId(edge.getStart()); + label.setTreatAsNode(true); + } + if (graph.getLabelByGraphId(edge.getEnd()) != null) { + Label label = graph.getLabelByGraphId(edge.getEnd()); + label.setTreatAsNode(true); + } + + if (graph.getShapeByGraphId(edge.getStart()) != null) { + Shape shape = graph.getShapeByGraphId(edge.getStart()); + shape.setTreatAsNode(true); + } + if (graph.getShapeByGraphId(edge.getEnd()) != null) { + Shape shape = graph.getShapeByGraphId(edge.getEnd()); + shape.setTreatAsNode(true); + } + if (edge.getStart() == null || edge.getEnd() == null) { + logger.warn(edge.getWarningPrefix() + "Interaction is not connected"); + + } else { + graph.addEdge(edge); + } + } catch (ConverterException e) { + logger.warn(e, e); + } + } + } + } + + /** + * This function transforms Edges into Interactions. First: Edges with + * NodeToNode connection are transformed into Interactions. Second: Edges with + * AnchorToNode connection are added to right interaction. Edges with + * AnchorToAnchor connection are ignored. + * + * @param graph + * object where data is sotred + * @throws InvalidXmlSchemaException + * thrown when the data in input file is invalid + */ + protected void addInteractions(Graph graph) throws InvalidXmlSchemaException { + for (Edge edge : graph.getEdges()) { + if (graph.getNodeByGraphId(edge.getEnd()) != null && graph.getNodeByGraphId(edge.getStart()) != null) { + if (graph.getNodeByGraphId(edge.getEnd()) instanceof Label) { + Label label = (Label) graph.getNodeByGraphId(edge.getEnd()); + label.setTreatAsNode(true); + } + if (graph.getNodeByGraphId(edge.getStart()) instanceof Label) { + Label label = (Label) graph.getNodeByGraphId(edge.getStart()); + label.setTreatAsNode(true); + } + if (graph.getShapeByGraphId(edge.getEnd()) instanceof Shape) { + Shape shape = (Shape) graph.getShapeByGraphId(edge.getEnd()); + shape.setTreatAsNode(true); + } + if (graph.getShapeByGraphId(edge.getStart()) instanceof Shape) { + Shape shape = (Shape) graph.getShapeByGraphId(edge.getStart()); + shape.setTreatAsNode(true); + } + + Interaction interaction = new Interaction(edge); + graph.addInteraction(interaction); + InteractionMapping mapping = InteractionMapping.getInteractionMapping(edge.getType(), edge.getLine().getType()); + if (mapping != null) { + if (mapping.isInteractionWarning()) { + logger.warn(edge.getWarningPrefix() + "Invalid interaction type."); + } + } else { + throw new InvalidXmlSchemaException( + edge.getWarningPrefix() + "Unknown interaction type: " + edge.getType() + " and line type: " + + edge.getLine().getType()); + } + } + } + for (Edge edge : graph.getEdges()) { + try { + if (graph.getEdgeByAnchor(edge.getEnd()) != null && graph.getEdgeByAnchor(edge.getStart()) != null) { + logger.warn(edge.getWarningPrefix() + "Interaction can not connect two anchors."); + } else if (graph.getEdgeByAnchor(edge.getEnd()) != null && graph.getNodeByGraphId(edge.getStart()) != null) { + Interaction tmp = getParentInteraction(graph, edge); + if (tmp != null) { + InteractionMapping mapping = InteractionMapping.getInteractionMapping(edge.getType(), + edge.getLine().getType()); + if (mapping != null) { + if (mapping.isInputWarning()) { + logger.warn(edge.getWarningPrefix() + "Invalid interaction type as an input to reaction."); + } + if (Modifier.class.isAssignableFrom(mapping.getModelInputReactionNodeType())) { + tmp.addModifier(edge); + } else if (Reactant.class.isAssignableFrom(mapping.getModelInputReactionNodeType())) { + tmp.addReactant(edge); + } else if (Product.class.isAssignableFrom(mapping.getModelInputReactionNodeType())) { + tmp.addProduct(edge); + } else { + throw new InvalidStateException( + "Unknown internal model type: " + mapping.getModelInputReactionNodeType()); + } + } else { + throw new InvalidXmlSchemaException("Unknown interaction type: " + edge.getType()); + } + } else { + logger.warn(edge.getWarningPrefix() + "Interaction is disconnected."); + } + } else if (graph.getEdgeByAnchor(edge.getStart()) != null && graph.getNodeByGraphId(edge.getEnd()) != null) { + Interaction tmp = getParentInteraction(graph, edge); + if (tmp != null) { + InteractionMapping mapping = InteractionMapping.getInteractionMapping(edge.getType(), + edge.getLine().getType()); + if (mapping != null) { + if (mapping.isOutputWarning()) { + logger.warn(edge.getWarningPrefix() + "Invalid interaction type \"" + edge.getType() + + "\" as an input to reaction."); + } + if (Modifier.class.isAssignableFrom(mapping.getModelOutputReactionNodeType())) { + tmp.addModifier(edge); + } else if (Reactant.class.isAssignableFrom(mapping.getModelOutputReactionNodeType())) { + tmp.addReactant(edge); + } else if (Product.class.isAssignableFrom(mapping.getModelOutputReactionNodeType())) { + tmp.addProduct(edge); + } else { + throw new InvalidStateException( + "Unknown internal model type: " + mapping.getModelOutputReactionNodeType()); + } + } else { + throw new InvalidXmlSchemaException("Unknown interaction type: " + edge.getType()); + } + } else { + logger.warn(edge.getWarningPrefix() + "Interaction is disconnected."); + } + } else if (graph.getNodeByGraphId(edge.getEnd()) == null || graph.getNodeByGraphId(edge.getStart()) == null) { + logger.warn(edge.getWarningPrefix() + "Interaction edge is invalid (one end is not connected)."); + } + } catch (CyclicEdgeException e) { + logger.warn(e, e); + } + } + } + + /** + * Creates gpml {@link Graph} model from gpml input stream. + * + * @param stream + * input stream with gpml model + * @return {@link Graph} model + * @throws IOException + * thrown when there is a problem with input file + * @throws ConverterException + * thrown when there is a problem with parsing input file + */ + public Graph createGraph(InputStream stream) throws IOException, ConverterException { + try { + DocumentBuilder builder; + builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document document = builder.parse(stream); + + // Get the document's root XML node + NodeList root = document.getElementsByTagName("Pathway"); + + NodeList nodes = root.item(0).getChildNodes(); + + Node dimensionNode = null; + List<Node> dataNodes = new ArrayList<Node>(); + List<Node> interactions = new ArrayList<Node>(); + List<Node> labels = new ArrayList<Node>(); + List<Node> groups = new ArrayList<Node>(); + List<Node> shapes = new ArrayList<Node>(); + List<Node> lines = new ArrayList<Node>(); + List<Node> states = new ArrayList<Node>(); + List<Element> attributes = new ArrayList<Element>(); + Node biopax = null; + + Graph graph = new Graph(); + for (int x = 0; x < nodes.getLength(); x++) { + Node node = nodes.item(x); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equalsIgnoreCase("Graphics")) { + dimensionNode = node; + } else if (node.getNodeName().equalsIgnoreCase("DataNode")) { + dataNodes.add(node); + } else if (node.getNodeName().equalsIgnoreCase("Interaction")) { + interactions.add(node); + } else if (node.getNodeName().equalsIgnoreCase("Label")) { + labels.add(node); + } else if (node.getNodeName().equalsIgnoreCase("Group")) { + groups.add(node); + } else if (node.getNodeName().equalsIgnoreCase("Attribute")) { + attributes.add((Element) node); + } else if (node.getNodeName().equalsIgnoreCase("Shape")) { + shapes.add(node); + } else if (node.getNodeName().equalsIgnoreCase("GraphicalLine")) { + lines.add(node); + } else if (node.getNodeName().equalsIgnoreCase("Comment")) { + graph.addComment(node.getTextContent()); + } else if (node.getNodeName().equalsIgnoreCase("BiopaxRef")) { + graph.addBiopaxReferences(node.getTextContent()); + } else if (node.getNodeName().equalsIgnoreCase("State")) { + states.add(node); + } else if (node.getNodeName().equalsIgnoreCase("Biopax")) { + if (biopax != null) { + throw new ConverterException("Biopax node should appear only once"); + } + biopax = node; + } else if (node.getNodeName().equalsIgnoreCase("InfoBox")) { + // infobox can be skipped + continue; + } else if (node.getNodeName().equalsIgnoreCase("Legend")) { + // legend can be skipped + continue; + } else { + logger.warn("Unknown element of gpml file: " + node.getNodeName()); + } + } + } + graph.addLines(parseLines(lines)); + graph.addEdges(parseEdgesFromLines(lines)); + + if (dimensionNode != null) { + setSize(dimensionNode, graph); + } + addGroups(groups, graph); + + graph.addDataNodes(dataNodeParser.parseCollection(dataNodes)); + graph.addLabels(labelParser.parseCollection(labels)); + graph.addShapes(shapeParser.parseCollection(shapes)); + graph.addStates(stateParser.parseCollection(states)); + + prepareEdges(interactions, graph); + + mergeEdges(graph); + + addInteractions(graph); + if (biopax != null) { + graph.setBiopaxData(new BiopaxParser().parse(biopax)); + } + Map<String, String> attributesMap = new HashMap<String, String>(); + for (Element attribute : attributes) { + String key = attribute.getAttribute("Key"); + String value = attribute.getAttribute("Value"); + if (attributesMap.get(key) != null) { + logger.warn("Model xml contains duplicate attributes: " + key); + } else { + attributesMap.put(key, value); + } + } + graph.setAttributes(attributesMap); + return graph; + } catch (ParserConfigurationException e) { + throw new ConverterException("Problem with input data", e); + } catch (SAXException e) { + throw new ConverterException("Problem with input data", e); + } catch (InvalidXmlSchemaException e) { + throw new ConverterException("Problem with input data", e); + } + } + + /** + * This method merge edges that should be merged into single line. + * + * @param graph + * model where edges are stored + */ + private void mergeEdges(Graph graph) { + List<Edge> toExtend = new ArrayList<>(); + List<Edge> toRemove = new ArrayList<>(); + List<Edge> toAdd = new ArrayList<>(); + Map<String, List<Edge>> extendable = new HashMap<>(); + for (Edge edge : graph.getEdges()) { + if (graph.getEdgeByAnchor(edge.getStart()) == edge) { + toExtend.add(edge); + } else if (graph.getEdgeByAnchor(edge.getEnd()) == edge) { + toExtend.add(edge); + } else if (graph.getEdgeByAnchor(edge.getEnd()) != null) { + List<Edge> list = extendable.get(edge.getEnd()); + if (list == null) { + list = new ArrayList<>(); + extendable.put(edge.getEnd(), list); + } + list.add(edge); + } else if (graph.getEdgeByAnchor(edge.getStart()) != null) { + List<Edge> list = extendable.get(edge.getStart()); + if (list == null) { + list = new ArrayList<>(); + extendable.put(edge.getStart(), list); + } + list.add(edge); + } + + } + + for (Edge edge : toExtend) { + String anchor = null; + if (graph.getEdgeByAnchor(edge.getStart()) == edge) { + anchor = edge.getStart(); + } else if (graph.getEdgeByAnchor(edge.getEnd()) == edge) { + anchor = edge.getEnd(); + } + List<Edge> howExtend = extendable.get(anchor); + if (howExtend == null) { + logger.warn(edge.getWarningPrefix() + " Should be connected with another element, but nothing found."); + if (edge.getStart().equals(anchor)) { + edge.setStart(null); + } else if (edge.getEnd().equals(anchor)) { + edge.setEnd(null); + } + } else if (howExtend.size() > 0) { + try { + Edge newEdge = mergeEdges(edge, howExtend.get(0)); + toRemove.add(edge); + toRemove.add(howExtend.get(0)); + toAdd.add(newEdge); + } catch (UnknownMergingMethodException exception) { + toRemove.add(edge); + toRemove.add(howExtend.get(0)); + + logger.warn(exception, exception); + } + } + } + for (Edge e : toRemove) { + graph.removeEdge(e); + } + for (Edge e : toAdd) { + graph.addEdge(e); + } + } + + /** + * Method that merge two {@link Edge edges}. + * + * @param edge1 + * first edge to merge + * @param edge2 + * second edge to merge + * @return new edge that merges two parameters + * @throws UnknownMergingMethodException + * thrown when edges cannot be merged + */ + private Edge mergeEdges(Edge edge1, Edge edge2) throws UnknownMergingMethodException { + MergeMapping mapping = null; + if (edge1.getStart() != null && edge1.getStart().equals(edge2.getStart())) { + mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), true, edge2.getType(), false); + } else if (edge1.getStart() != null && edge1.getStart().equals(edge2.getEnd())) { + mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), true, edge2.getType(), true); + } else if (edge1.getEnd() != null && edge1.getEnd().equals(edge2.getStart())) { + mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), false, edge2.getType(), false); + } else if (edge1.getEnd() != null && edge1.getEnd().equals(edge2.getEnd())) { + mapping = MergeMapping.getMergeMappingByInteractions(edge1.getType(), false, edge2.getType(), true); + } + if (mapping == null) { + String message = edge1.getWarningPrefix() + edge2.getWarningPrefix() + "Don't know how to merge interactions"; + throw new UnknownMergingMethodException(message); + } + Edge first; + if (mapping.isReversed1()) { + first = edge1.reverse(); + } else { + first = new Edge(edge1); + } + Edge second; + if (mapping.isReversed2()) { + second = edge2.reverse(); + } else { + second = new Edge(edge2); + } + first.extend(second); + + if (!first.getLine().getType().equals(second.getLine().getType())) { + logger.warn( + first.getWarningPrefix() + second.getWarningPrefix() + " merging edges with different line types: " + + first.getLine().getType() + ", " + + second.getLine().getType()); + } + first.setType(mapping.getResultType()); + if (mapping.isResultReversed()) { + return first.reverse(); + } else { + return first; + } + } + + /** + * Creates edges from lines when it's possible. + * + * @param lines + * xml nodes with lines + * @return list of edges that could be created from xml nodes + */ + private Collection<Edge> parseEdgesFromLines(List<Node> lines) { + List<Edge> result = new ArrayList<Edge>(); + for (Node lNode : lines) { + try { + Edge line = edgeLineParser.parse((Element) lNode); + if (line.getStart() != null && line.getEnd() != null) { + result.add(line); + } + } catch (ConverterException e) { + logger.warn(e, e); + + } + } + return result; + } + + /** + * Creates lines from the list of gpml xml nodes. + * + * @param lines + * list of xml nodes + * @return list of {@link PolylineData lines} + * @throws UnknownTypeException + * thrown when the type of line defined in xml node is unknown + */ + private Collection<PolylineData> parseLines(List<Node> lines) throws UnknownTypeException { + List<PolylineData> result = new ArrayList<PolylineData>(); + for (Node lNode : lines) { + int refs = 0; + PolylineData line = new PolylineData(); + NodeList nodes = lNode.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + Node node = nodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE) { + if (node.getNodeName().equalsIgnoreCase("Graphics")) { + NodeList nodes2 = node.getChildNodes(); + for (int j = 0; j < nodes2.getLength(); j++) { + Node node2 = nodes2.item(j); + if (node2.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node2; + if (node2.getNodeName().equalsIgnoreCase("Point")) { + PointData point = pointParser.parse(element); + if (point.hasGraphRef()) { + refs++; + } + line.addPoint(point.toPoint()); + } else { + logger.warn("Unknown node in line: " + node2.getNodeName()); + } + } + } + + } else { + logger.warn("Unknown node in line: " + node.getNodeName()); + } + } + } + if (refs < 2) { + result.add(line); + } + } + return result; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GraphicalPathwayElementParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GraphicalPathwayElementParser.java index 3e6d5c26f5..bfb0819c05 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GraphicalPathwayElementParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/GraphicalPathwayElementParser.java @@ -2,13 +2,12 @@ package lcsb.mapviewer.wikipathway.XML; import java.awt.font.TextAttribute; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.geometry.TextAlignment; -import lcsb.mapviewer.wikipathway.model.GpmlLineType; -import lcsb.mapviewer.wikipathway.model.GraphicalPathwayElement; -import lcsb.mapviewer.wikipathway.model.UnknownTypeException; +import lcsb.mapviewer.wikipathway.model.*; /** * Parser used for extracting common data (from gpml file) for all elements @@ -20,58 +19,59 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public abstract class GraphicalPathwayElementParser<T extends GraphicalPathwayElement> extends ElementGpmlParser<T> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(GraphicalPathwayElementParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(GraphicalPathwayElementParser.class); - /** - * Parse font attributes that might appear. - * - * @param element - * element where data should be put - * @param attribute - * attribute to parse - * @return true if element was parsed properly - * @throws UnknownTypeException - * thrown when some elements contains unknown values - */ - protected boolean parseCommonGraphicAttributes(GraphicalPathwayElement element, Pair<String, String> attribute) throws UnknownTypeException { - switch (attribute.getLeft()) { - case ("LineThickness"): - try { - Double value = Double.valueOf(attribute.getRight()); - element.setLineThickness(value); - } catch (NumberFormatException e) { - logger.warn("Invalid LineThickness: " + attribute.getRight()); - } - break; - case ("LineStyle"): - element.setLineType(GpmlLineType.getByGpmlName(attribute.getRight()).getCorrespondingGlobalLineType()); - break; - case ("FontStyle"): - element.addFontAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); - break; - case ("FontName"): - element.setFontName(attribute.getRight()); - break; - case ("Align"): - switch (attribute.getRight()) { - case ("Right"): - element.setTextAlignment(TextAlignment.RIGHT); - break; - case ("Left"): - element.setTextAlignment(TextAlignment.LEFT); - break; - default: - logger.warn("Unknown value of attribute: " + attribute.getLeft() + " - " + attribute.getRight()); - break; - } - break; - default: - return false; - } - return true; - } + /** + * Parse font attributes that might appear. + * + * @param element + * element where data should be put + * @param attribute + * attribute to parse + * @return true if element was parsed properly + * @throws UnknownTypeException + * thrown when some elements contains unknown values + */ + protected boolean parseCommonGraphicAttributes(GraphicalPathwayElement element, Pair<String, String> attribute) + throws UnknownTypeException { + switch (attribute.getLeft()) { + case ("LineThickness"): + try { + Double value = Double.valueOf(attribute.getRight()); + element.setLineThickness(value); + } catch (NumberFormatException e) { + logger.warn("Invalid LineThickness: " + attribute.getRight()); + } + break; + case ("LineStyle"): + element.setLineType(GpmlLineType.getByGpmlName(attribute.getRight()).getCorrespondingGlobalLineType()); + break; + case ("FontStyle"): + element.addFontAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE); + break; + case ("FontName"): + element.setFontName(attribute.getRight()); + break; + case ("Align"): + switch (attribute.getRight()) { + case ("Right"): + element.setTextAlignment(TextAlignment.RIGHT); + break; + case ("Left"): + element.setTextAlignment(TextAlignment.LEFT); + break; + default: + logger.warn("Unknown value of attribute: " + attribute.getLeft() + " - " + attribute.getRight()); + break; + } + break; + default: + return false; + } + return true; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/InvalidElbowConnectorException.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/InvalidElbowConnectorException.java index ed81e3e0ae..0382aefb37 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/InvalidElbowConnectorException.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/InvalidElbowConnectorException.java @@ -12,19 +12,19 @@ import lcsb.mapviewer.converter.ConverterException; */ public class InvalidElbowConnectorException extends ConverterException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public InvalidElbowConnectorException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public InvalidElbowConnectorException(String string) { + super(string); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/LabelParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/LabelParser.java index 82af92ce1b..c3c91d277e 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/LabelParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/LabelParser.java @@ -3,10 +3,9 @@ package lcsb.mapviewer.wikipathway.XML; import java.awt.geom.Rectangle2D; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -24,155 +23,156 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class LabelParser extends GraphicalPathwayElementParser<Label> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(LabelParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(LabelParser.class); - @Override - public Label parse(Element eElement) throws UnknownTypeException { - if (!eElement.getNodeName().equals("Label")) { - throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only Label xml nodes"); - } - Label label = new Label(eElement.getAttribute("GraphId")); + @Override + public Label parse(Element eElement) throws UnknownTypeException { + if (!eElement.getNodeName().equals("Label")) { + throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only Label xml nodes"); + } + Label label = new Label(eElement.getAttribute("GraphId")); - for (Pair<String, String> entry : getAttributes(eElement)) { - switch (entry.getLeft()) { - case ("GraphId"): - break; - case ("TextLabel"): - label.setTextLabel(entry.getRight()); - break; - case ("GroupRef"): - label.setGroupRef(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); - break; - } - } + for (Pair<String, String> entry : getAttributes(eElement)) { + switch (entry.getLeft()) { + case ("GraphId"): + break; + case ("TextLabel"): + label.setTextLabel(entry.getRight()); + break; + case ("GroupRef"): + label.setGroupRef(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); + break; + } + } - NodeList tmpList = eElement.getChildNodes(); - for (int j = 0; j < tmpList.getLength(); j++) { - Node tmpNode = tmpList.item(j); - if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { - Element eTmp = (Element) tmpNode; - switch (eTmp.getNodeName()) { - case ("Comment"): - label.addComment(eTmp.getTextContent()); - break; - case ("BiopaxRef"): - label.addBiopaxReference(eTmp.getTextContent()); - break; - case ("Graphics"): - parseGraphics(eTmp, label); - break; - case ("Attribute"): - parseAttribute(eTmp, label); - break; - default: - logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); - break; - } - } - } + NodeList tmpList = eElement.getChildNodes(); + for (int j = 0; j < tmpList.getLength(); j++) { + Node tmpNode = tmpList.item(j); + if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { + Element eTmp = (Element) tmpNode; + switch (eTmp.getNodeName()) { + case ("Comment"): + label.addComment(eTmp.getTextContent()); + break; + case ("BiopaxRef"): + label.addBiopaxReference(eTmp.getTextContent()); + break; + case ("Graphics"): + parseGraphics(eTmp, label); + break; + case ("Attribute"): + parseAttribute(eTmp, label); + break; + default: + logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); + break; + } + } + } - return label; - } + return label; + } - /** - * Parse graphics xml node in the shape node. - * - * @param eTmp - * xml node with graphics - * @param shape - * shape where data should be added - * @throws UnknownTypeException - * thrown when some elements contain unknown typevalues - */ - protected void parseGraphics(Element eTmp, Label shape) throws UnknownTypeException { - Double centerX = null; - Double centerY = null; - Double width = null; - Double height = null; - for (Pair<String, String> entry : getAttributes(eTmp)) { - if (!parseCommonGraphicAttributes(shape, entry)) { - switch (entry.getLeft()) { - case ("CenterX"): - centerX = Double.valueOf(entry.getRight()); - break; - case ("CenterY"): - centerY = Double.valueOf(entry.getRight()); - break; - case ("Width"): - width = Double.valueOf(entry.getRight()); - break; - case ("Height"): - height = Double.valueOf(entry.getRight()); - break; - case ("Color"): - shape.setColor(hexStringToColor(entry.getRight())); - break; - case ("FillColor"): - shape.setFillColor(hexStringToColor(entry.getRight())); - break; - case ("ZOrder"): - shape.setzOrder(Integer.valueOf(entry.getRight())); - break; - case ("FontSize"): - shape.setFontSize(Double.valueOf(entry.getRight())); - break; - case ("FontWeight"): - shape.setFontWeight(entry.getRight()); - break; - case ("Valign"): - shape.setvAlign(entry.getRight()); - break; - case ("ShapeType"): - shape.setShape(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft() + "; value: " + entry.getRight()); - break; - } - } - } - shape.setRectangle(new Rectangle2D.Double(centerX - width / 2, centerY - height / 2, width, height)); - } + @Override + public String toXml(Label node) throws ConverterException { + throw new NotImplementedException(); + } - /** - * Method that parses {@link Label} xml attribute. - * - * @param eTmp - * xml node with attribute - * @param shape - * shape where data should be added - */ - private void parseAttribute(Element eTmp, Label shape) { - String key = eTmp.getAttribute("Key"); - String value = eTmp.getAttribute("Value"); - switch (key) { - case ("org.pathvisio.model.GenMAPP-Xref"): - // skip it when it's empty - if (!value.isEmpty()) { - logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); - break; - } - break; - default: - logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key:" + key + "; value: " + value); - break; - } - } + @Override + public String toXml(Collection<Label> list) throws ConverterException { + throw new NotImplementedException(); + } - @Override - public String toXml(Label node) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Parse graphics xml node in the shape node. + * + * @param eTmp + * xml node with graphics + * @param shape + * shape where data should be added + * @throws UnknownTypeException + * thrown when some elements contain unknown typevalues + */ + protected void parseGraphics(Element eTmp, Label shape) throws UnknownTypeException { + Double centerX = null; + Double centerY = null; + Double width = null; + Double height = null; + for (Pair<String, String> entry : getAttributes(eTmp)) { + if (!parseCommonGraphicAttributes(shape, entry)) { + switch (entry.getLeft()) { + case ("CenterX"): + centerX = Double.valueOf(entry.getRight()); + break; + case ("CenterY"): + centerY = Double.valueOf(entry.getRight()); + break; + case ("Width"): + width = Double.valueOf(entry.getRight()); + break; + case ("Height"): + height = Double.valueOf(entry.getRight()); + break; + case ("Color"): + shape.setColor(hexStringToColor(entry.getRight())); + break; + case ("FillColor"): + shape.setFillColor(hexStringToColor(entry.getRight())); + break; + case ("ZOrder"): + shape.setzOrder(Integer.valueOf(entry.getRight())); + break; + case ("FontSize"): + shape.setFontSize(Double.valueOf(entry.getRight())); + break; + case ("FontWeight"): + shape.setFontWeight(entry.getRight()); + break; + case ("Valign"): + shape.setvAlign(entry.getRight()); + break; + case ("ShapeType"): + shape.setShape(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft() + "; value: " + + entry.getRight()); + break; + } + } + } + shape.setRectangle(new Rectangle2D.Double(centerX - width / 2, centerY - height / 2, width, height)); + } - @Override - public String toXml(Collection<Label> list) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Method that parses {@link Label} xml attribute. + * + * @param eTmp + * xml node with attribute + * @param shape + * shape where data should be added + */ + private void parseAttribute(Element eTmp, Label shape) { + String key = eTmp.getAttribute("Key"); + String value = eTmp.getAttribute("Value"); + switch (key) { + case ("org.pathvisio.model.GenMAPP-Xref"): + // skip it when it's empty + if (!value.isEmpty()) { + logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key: " + key + "; value: " + value); + break; + } + break; + default: + logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key:" + key + "; value: " + value); + break; + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java index 2f335d27f1..8b56cec964 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelContructor.java @@ -1,16 +1,9 @@ package lcsb.mapviewer.wikipathway.XML; -import java.awt.Color; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; +import java.awt.*; +import java.awt.geom.*; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; import org.apache.commons.text.StringEscapeUtils; import org.apache.logging.log4j.LogManager; @@ -29,55 +22,18 @@ import lcsb.mapviewer.converter.model.celldesigner.types.ModifierType; import lcsb.mapviewer.converter.model.celldesigner.types.ModifierTypeUtils; 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.OvalCompartment; -import lcsb.mapviewer.model.map.compartment.SquareCompartment; -import lcsb.mapviewer.model.map.layout.graphics.Layer; -import lcsb.mapviewer.model.map.layout.graphics.LayerOval; -import lcsb.mapviewer.model.map.layout.graphics.LayerRect; -import lcsb.mapviewer.model.map.layout.graphics.LayerText; +import lcsb.mapviewer.model.map.compartment.*; +import lcsb.mapviewer.model.map.layout.graphics.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.AbstractNode; -import lcsb.mapviewer.model.map.reaction.AndOperator; -import lcsb.mapviewer.model.map.reaction.AssociationOperator; -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.reaction.SplitOperator; -import lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedNotation; -import lcsb.mapviewer.model.map.reaction.type.TwoReactantReactionInterface; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; -import lcsb.mapviewer.model.map.species.field.AbstractSiteModification; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.Residue; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; import lcsb.mapviewer.modelutils.map.ElementUtils; -import lcsb.mapviewer.wikipathway.model.DataNode; -import lcsb.mapviewer.wikipathway.model.Edge; -import lcsb.mapviewer.wikipathway.model.Graph; -import lcsb.mapviewer.wikipathway.model.GraphicalPathwayElement; -import lcsb.mapviewer.wikipathway.model.Group; -import lcsb.mapviewer.wikipathway.model.Interaction; -import lcsb.mapviewer.wikipathway.model.InteractionMapping; +import lcsb.mapviewer.wikipathway.model.*; import lcsb.mapviewer.wikipathway.model.Label; -import lcsb.mapviewer.wikipathway.model.PathwayElement; import lcsb.mapviewer.wikipathway.model.Shape; -import lcsb.mapviewer.wikipathway.model.State; import lcsb.mapviewer.wikipathway.model.biopax.BiopaxPublication; import lcsb.mapviewer.wikipathway.utils.Geo; @@ -89,44 +45,22 @@ import lcsb.mapviewer.wikipathway.utils.Geo; */ public class ModelContructor { - /** - * CellDesigner util class used for retrieving information about modifier - * graphics. - */ - private ModifierTypeUtils mtu = new ModifierTypeUtils(); - /** * Default color used by complexes. */ private static final Color DEFAULT_COMPLEX_ALIAS_COLOR = new Color(102, 255, 255); - /** * How much of central line is used by and operator that joins reactants. */ private static final int AND_OPERATOR_CENTRAL_LINE_RATIO = 10; - /** * How much of central line is used by split operator that split products. */ private static final int SPLIT_OPERATOR_CENTRAL_LINE_RATIO = 10; - /** * Epsilon used for double comparison. */ private static final double EPSILON = 1e-6; - - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(ModelContructor.class); - - /** - * Parser used for extracting {@link MiriamData references} from GPML model. - */ - private BiopaxParser biopaxParser = new BiopaxParser(); - - private PointTransformation pt = new PointTransformation(); - /** * List of {@link Shape#shape shapes} that are not supported to be part of a * {@link Complex complex}. @@ -147,6 +81,21 @@ public class ModelContructor { INALID_COMPLEX_SHAPE_CHILDREN.add("Hexagon"); } + /** + * CellDesigner util class used for retrieving information about modifier + * graphics. + */ + private ModifierTypeUtils mtu = new ModifierTypeUtils(); + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(ModelContructor.class); + /** + * Parser used for extracting {@link MiriamData references} from GPML model. + */ + private BiopaxParser biopaxParser = new BiopaxParser(); + private PointTransformation pt = new PointTransformation(); + /** * This function splits {@link PolylineData} into two parts. It also assumes * that last segment on the left part is equal to the length of the first @@ -222,37 +171,9 @@ public class ModelContructor { return new Pair<PolylineData, PolylineData>(p1, p2); } - /** - * Support class to send less parameters in functions. - * - * @author Jan Badura - */ - private final class Data { - /** - * Map between graphId and aliases created from gpml elements. - */ - private Map<String, Element> id2alias; - - /** - * Default layer. - */ - private Layer layer; - - /** - * Default constructor. - */ - private Data() { - id2alias = new HashMap<String, Element>(); - layer = new Layer(); - layer.setVisible(true); - layer.setLayerId("1"); - layer.setName("defaultLayer"); - } - } - /** * This function creates Species from DataNode. - * + * * @param dataNode * object from which species is created * @param data @@ -294,7 +215,7 @@ public class ModelContructor { /** * This function adds ComplexSpecies to model from graph. ComplexName is set as * groupId from .gpml - * + * * @param model * to this model complexes will be added * @param graph @@ -329,7 +250,7 @@ public class ModelContructor { /** * This function adds Species, TextLabels, Compartments and Shapes from graph. - * + * * @param model * model to which species will be added * @param graph @@ -433,7 +354,7 @@ public class ModelContructor { * {@link ModificationResidue} in element might have slightly off coordinates * (due to different symbol shapes). For that we need to align them to match our * model. - * + * * @param species */ protected void adjustModificationCoordinates(Element species) { @@ -461,7 +382,7 @@ public class ModelContructor { /** * Creates {@link LayerRect} object from {@link Shape}. - * + * * @param shape * source gpml object to be transformed * @return {@link LayerRect} obtained from {@link Shape} object @@ -479,7 +400,7 @@ public class ModelContructor { /** * Creates {@link LayerOval} object from {@link Shape}. - * + * * @param shape * source gpml object to be transformed * @return {@link LayerOval} obtained from {@link Shape} object @@ -497,7 +418,7 @@ public class ModelContructor { /** * Creates {@link LayerText} from {@link Label}. - * + * * @param label * object from which result will be created * @return {@link LayerText} from {@link Label} @@ -521,7 +442,7 @@ public class ModelContructor { /** * Creates alias for {@link GraphicalPathwayElement}. Type of the alias is * defined by the parameter {@link Species} - * + * * @param gpmlElement * object from which alias will be create * @param alias @@ -553,7 +474,7 @@ public class ModelContructor { /** * Creates {@link Unknown species} from {@link Label}. - * + * * @param label * original label from which output should be created * @return {@link Unknown} object created from input {@link Label} @@ -568,7 +489,7 @@ public class ModelContructor { /** * Creates {@link Unknown species} from {@link Shape}. - * + * * @param shape * original label from which output should be created * @return {@link Unknown} object created from input {@link Label} @@ -583,7 +504,7 @@ public class ModelContructor { /** * This function add Species to right Complexes. - * + * * @param graph * gpml data model * @param data @@ -632,7 +553,7 @@ public class ModelContructor { /** * This function creates {@link Reaction} from {@link Interaction} from graph. - * + * * @param interaction * gpml interaction * @param graph @@ -812,7 +733,7 @@ public class ModelContructor { /** * Creates {@link Reactant} from gpml edge. - * + * * @param data * ... * @param e @@ -845,7 +766,7 @@ public class ModelContructor { /** * Creates {@link Product} from gpml edge. - * + * * @param data * ... * @param e @@ -876,7 +797,7 @@ public class ModelContructor { /** * Creates {@link Modifier} from gpml edge. - * + * * @param data * ... * @param e @@ -914,7 +835,7 @@ public class ModelContructor { /** * Creates {@link Reaction} for a given class type. - * + * * @param reactionType * type of reaction to create * @return new instance of the reactionType @@ -930,7 +851,7 @@ public class ModelContructor { /** * Creates {@link Modifier} for a given class type. - * + * * @param modifierType * type of modifier in reaction to create * @param alias @@ -948,13 +869,13 @@ public class ModelContructor { /** * This function creates {@link Model} from {@link Graph}. - * + * * @param graph * object with data obtained from gpml * @return {@link Model} object representing gpml * @throws ConverterException * exception thrown when conversion from graph couldn't be performed - * + * */ public Model getModel(Graph graph) throws ConverterException { try { @@ -1019,7 +940,7 @@ public class ModelContructor { /** * Method that put {@link Species aliases} that are not assigned into any * {@link Compartment} into a proper compartment. - * + * * @param model * model where aliases will be modified */ @@ -1049,7 +970,7 @@ public class ModelContructor { /** * Removes empty complexes (with size 0) from model. - * + * * @param model * model where operation is performed */ @@ -1082,7 +1003,7 @@ public class ModelContructor { /** * Tries to find a name to assign to complexes if complexes don't contain them. - * + * * @param model * model where complexes are placed */ @@ -1112,7 +1033,7 @@ public class ModelContructor { /** * Tries to find a name to assign to compartments if comparments don't contain * them. - * + * * @param model * model where compartments are placed */ @@ -1141,7 +1062,7 @@ public class ModelContructor { /** * Creates list of {@link LayerLine} in the model from gpml model. - * + * * @param graph * gpml model * @return list of {@link LayerLine} @@ -1157,7 +1078,7 @@ public class ModelContructor { /** * By default gpml doesn't offer information about compartments structure. This * function fixes assignments to compartment and compartment aliases. - * + * * @param model * model where assignments are fixed. */ @@ -1191,4 +1112,32 @@ public class ModelContructor { } } } + + /** + * Support class to send less parameters in functions. + * + * @author Jan Badura + */ + private final class Data { + /** + * Map between graphId and aliases created from gpml elements. + */ + private Map<String, Element> id2alias; + + /** + * Default layer. + */ + private Layer layer; + + /** + * Default constructor. + */ + private Data() { + id2alias = new HashMap<String, Element>(); + layer = new Layer(); + layer.setVisible(true); + layer.setLayerId("1"); + layer.setName("defaultLayer"); + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java index 0e4ba28f7e..929b4db2df 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ModelToGPML.java @@ -5,7 +5,8 @@ import java.awt.geom.Rectangle2D; import java.util.HashSet; import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.converter.ConverterException; @@ -15,25 +16,8 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.compartment.OvalCompartment; import lcsb.mapviewer.model.map.model.Model; -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.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.wikipathway.utils.Geo; /** @@ -44,39 +28,33 @@ import lcsb.mapviewer.wikipathway.utils.Geo; */ public class ModelToGPML { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final Logger logger = LogManager.getLogger(ModelToGPML.class); - /** * Maximum distance between point and line. ??? */ private static final double DIS_FOR_LINE = 3.0; - /** * This value define margin of the group border. Rectangle border will be * resized by this value in every direction. */ private static final int GROUP_RECTANGLE_BORDER_MARGIN = 8; - /** * First id value used for generating identifiers during conversion. */ private static final int INITIAL_ID_VALUE = 10000; - + /** + * Maximum distance between point and rectangle. ??? + */ + private static final double DIS_FOR_REP = 9.0; + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final Logger logger = LogManager.getLogger(ModelToGPML.class); /** * Counter used for generating identifiers if identifiers aren't provided by the * gpml model. */ private int idCounter = INITIAL_ID_VALUE; - - /** - * Maximum distance between point and rectangle. ??? - */ - private static final double DIS_FOR_REP = 9.0; - /** * Parser used to convert from/to xml {@link MiriamData} annotations. */ diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/PointDataParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/PointDataParser.java index 1d1e037c73..614829c670 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/PointDataParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/PointDataParser.java @@ -2,15 +2,14 @@ package lcsb.mapviewer.wikipathway.XML; import java.util.Collection; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.w3c.dom.Element; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.ConverterException; -import lcsb.mapviewer.wikipathway.model.GpmlInteractionType; -import lcsb.mapviewer.wikipathway.model.PointData; -import lcsb.mapviewer.wikipathway.model.UnknownTypeException; +import lcsb.mapviewer.wikipathway.model.*; /** * Parser class that creates {@link PointData} objects from Xml {@link Element @@ -21,48 +20,48 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class PointDataParser extends ElementGpmlParser<PointData> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(PointDataParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(PointDataParser.class); - @Override - public PointData parse(Element element) throws UnknownTypeException { - PointData result = new PointData(); - for (Pair<String, String> entry : getAttributes(element)) { - switch (entry.getLeft()) { - case ("X"): - result.setX(Double.valueOf(entry.getRight())); - break; - case ("Y"): - result.setY(Double.valueOf(entry.getRight())); - break; - case ("GraphRef"): - result.setGraphRef(entry.getRight()); - break; - case ("ArrowHead"): - result.setType(GpmlInteractionType.getTypeByGpmlString(entry.getRight())); - break; - case ("RelX"): - result.setRelX(entry.getRight()); - break; - case ("RelY"): - result.setRelY(entry.getRight()); - break; - default: - logger.warn("Unknown point attribute: " + entry.getLeft()); - } - } - return result; - } + @Override + public PointData parse(Element element) throws UnknownTypeException { + PointData result = new PointData(); + for (Pair<String, String> entry : getAttributes(element)) { + switch (entry.getLeft()) { + case ("X"): + result.setX(Double.valueOf(entry.getRight())); + break; + case ("Y"): + result.setY(Double.valueOf(entry.getRight())); + break; + case ("GraphRef"): + result.setGraphRef(entry.getRight()); + break; + case ("ArrowHead"): + result.setType(GpmlInteractionType.getTypeByGpmlString(entry.getRight())); + break; + case ("RelX"): + result.setRelX(entry.getRight()); + break; + case ("RelY"): + result.setRelY(entry.getRight()); + break; + default: + logger.warn("Unknown point attribute: " + entry.getLeft()); + } + } + return result; + } - @Override - public String toXml(PointData node) throws ConverterException { - throw new NotImplementedException(); - } + @Override + public String toXml(PointData node) throws ConverterException { + throw new NotImplementedException(); + } - @Override - public String toXml(Collection<PointData> list) throws ConverterException { - throw new NotImplementedException(); - } + @Override + public String toXml(Collection<PointData> list) throws ConverterException { + throw new NotImplementedException(); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ReferenceParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ReferenceParser.java index ec6a06d01e..f2efd4e5da 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ReferenceParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ReferenceParser.java @@ -2,20 +2,16 @@ package lcsb.mapviewer.wikipathway.XML; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.MinervaLoggerAppender; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.ConverterException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.wikipathway.model.ReferenceMapping; /** @@ -27,136 +23,137 @@ import lcsb.mapviewer.wikipathway.model.ReferenceMapping; */ public class ReferenceParser extends ElementGpmlParser<MiriamData> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(ReferenceParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(ReferenceParser.class); - /** - * This function creates MiriamData from database name and id. - * - * @param id - * - resource identifier - * @param db - * -database type - * @return {@link MiriamData} object referenceing to the resource - */ - protected MiriamData createMiriamData(String id, String db) { - if (db == null || db.equals("")) { - throw new InvalidArgumentException("Invalid db type: " + db); - } else if (id == null || id.trim().equals("")) { - throw new InvalidArgumentException("Invalid db resource value: " + id); - } - ReferenceMapping mapping = ReferenceMapping.getMappingByGpmlString(db); - MiriamType type = null; - if (mapping != null) { - type = mapping.getType(); - } else { - for (MiriamType t : MiriamType.values()) { - if (t.getCommonName().equalsIgnoreCase(db)) { - type = t; - } else { - for (String uri : t.getUris()) { - if (uri.endsWith(db)) { - type = t; - } - } - } - } - } - if (type != null) { - return new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, type, id); - } else { - throw new NotImplementedException("This database type is not implemented yet: " + db + "; resource: " + id); - } - } + /** + * This function creates MiriamData from database name and id. + * + * @param id + * - resource identifier + * @param db + * -database type + * @return {@link MiriamData} object referenceing to the resource + */ + protected MiriamData createMiriamData(String id, String db) { + if (db == null || db.equals("")) { + throw new InvalidArgumentException("Invalid db type: " + db); + } else if (id == null || id.trim().equals("")) { + throw new InvalidArgumentException("Invalid db resource value: " + id); + } + ReferenceMapping mapping = ReferenceMapping.getMappingByGpmlString(db); + MiriamType type = null; + if (mapping != null) { + type = mapping.getType(); + } else { + for (MiriamType t : MiriamType.values()) { + if (t.getCommonName().equalsIgnoreCase(db)) { + type = t; + } else { + for (String uri : t.getUris()) { + if (uri.endsWith(db)) { + type = t; + } + } + } + } + } + if (type != null) { + return new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, type, id); + } else { + throw new NotImplementedException("This database type is not implemented yet: " + db + "; resource: " + id); + } + } - @Override - public MiriamData parse(Element node) { - String id = null; - String db = null; - for (Pair<String, String> entry : getAttributes(node)) { - switch (entry.getLeft()) { - case ("ID"): - id = entry.getRight(); - break; - case ("Database"): - db = entry.getRight(); - break; - default: - logger.warn("Unknown attribute of " + node.getNodeName() + " node: " + entry.getLeft()); - break; - } - } + @Override + public MiriamData parse(Element node) { + String id = null; + String db = null; + for (Pair<String, String> entry : getAttributes(node)) { + switch (entry.getLeft()) { + case ("ID"): + id = entry.getRight(); + break; + case ("Database"): + db = entry.getRight(); + break; + default: + logger.warn("Unknown attribute of " + node.getNodeName() + " node: " + entry.getLeft()); + break; + } + } - NodeList tmpList = node.getChildNodes(); - for (int j = 0; j < tmpList.getLength(); j++) { - Node tmpNode = tmpList.item(j); - if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { - Element eTmp = (Element) tmpNode; - switch (eTmp.getNodeName()) { - default: - logger.warn("Unknown sub-node of " + node.getNodeName() + " node: " + eTmp.getNodeName()); - break; - } - } - } + NodeList tmpList = node.getChildNodes(); + for (int j = 0; j < tmpList.getLength(); j++) { + Node tmpNode = tmpList.item(j); + if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { + Element eTmp = (Element) tmpNode; + switch (eTmp.getNodeName()) { + default: + logger.warn("Unknown sub-node of " + node.getNodeName() + " node: " + eTmp.getNodeName()); + break; + } + } + } - if (id != null && !id.isEmpty()) { - if (db == null || db.isEmpty()) { - logger.warn("Reference is invalid. Database identifier exists (" + id + "), but no database type is set."); - } else { - MiriamData md = createMiriamData(id, db); - return md; - } - } - return null; - } + if (id != null && !id.isEmpty()) { + if (db == null || db.isEmpty()) { + logger.warn("Reference is invalid. Database identifier exists (" + id + "), but no database type is set."); + } else { + MiriamData md = createMiriamData(id, db); + return md; + } + } + return null; + } - @Override - public String toXml(MiriamData md) throws ConverterException { - if (md == null) { - return "<Xref ID=\"\" Database=\"\"/>\n"; - } else if (MiriamType.PUBMED.equals(md.getDataType())) { - throw new InvalidArgumentException("Pubmed cannot be exported to XRef node."); - } else { - ReferenceMapping mapping = ReferenceMapping.getMappingByMiriamType(md.getDataType()); - if (mapping == null) { - throw new InvalidArgumentException("Don't know how to export " + md.getDataType() + " annotation."); - } else if (mapping.getGpmlString() == null) { - logger.warn(md.getDataType().getCommonName() + " annotation is not supported by GPML"); - return ""; - } else { - return "<Xref ID=\"" + md.getResource() + "\" Database=\"" + mapping.getGpmlString() + "\"/>\n"; - } - } - } + @Override + public String toXml(MiriamData md) throws ConverterException { + if (md == null) { + return "<Xref ID=\"\" Database=\"\"/>\n"; + } else if (MiriamType.PUBMED.equals(md.getDataType())) { + throw new InvalidArgumentException("Pubmed cannot be exported to XRef node."); + } else { + ReferenceMapping mapping = ReferenceMapping.getMappingByMiriamType(md.getDataType()); + if (mapping == null) { + throw new InvalidArgumentException("Don't know how to export " + md.getDataType() + " annotation."); + } else if (mapping.getGpmlString() == null) { + logger.warn(md.getDataType().getCommonName() + " annotation is not supported by GPML"); + return ""; + } else { + return "<Xref ID=\"" + md.getResource() + "\" Database=\"" + mapping.getGpmlString() + "\"/>\n"; + } + } + } - @Override - public String toXml(Collection<MiriamData> miriamData) throws ConverterException { - StringBuilder result = new StringBuilder(""); - int counter = 0; - for (MiriamData md : miriamData) { - if (!md.getDataType().equals(MiriamType.PUBMED)) { - counter++; - if (counter == 1) { - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - try { - result.append(toXml(md)); - if (appender.getWarnings().size() > 0) { - counter--; - } - } finally { - MinervaLoggerAppender.unregisterLogEventStorage(appender); - } - } else { - logger.warn("Annotation ommited - gpml support only one annotation per element: " + md.getDataType() + ": " + md.getResource()); - } - } - } - if (counter == 0) { - return toXml((MiriamData) null); - } - return result.toString(); - } + @Override + public String toXml(Collection<MiriamData> miriamData) throws ConverterException { + StringBuilder result = new StringBuilder(""); + int counter = 0; + for (MiriamData md : miriamData) { + if (!md.getDataType().equals(MiriamType.PUBMED)) { + counter++; + if (counter == 1) { + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + try { + result.append(toXml(md)); + if (appender.getWarnings().size() > 0) { + counter--; + } + } finally { + MinervaLoggerAppender.unregisterLogEventStorage(appender); + } + } else { + logger.warn("Annotation ommited - gpml support only one annotation per element: " + md.getDataType() + ": " + + md.getResource()); + } + } + } + if (counter == 0) { + return toXml((MiriamData) null); + } + return result.toString(); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ShapeParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ShapeParser.java index 21aa6c627f..532fdd97c2 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ShapeParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/ShapeParser.java @@ -4,10 +4,9 @@ import java.awt.font.TextAttribute; import java.awt.geom.Rectangle2D; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; @@ -26,171 +25,171 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class ShapeParser extends GraphicalPathwayElementParser<Shape> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(ShapeParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(ShapeParser.class); - @Override - public Shape parse(Element eElement) throws ConverterException { - if (!eElement.getNodeName().equals("Shape")) { - throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only Shape xml nodes"); - } - Shape shape = new Shape(eElement.getAttribute("GraphId")); - for (Pair<String, String> entry : getAttributes(eElement)) { - switch (entry.getLeft()) { - case ("GraphId"): - break; - case ("TextLabel"): - shape.setTextLabel(entry.getRight()); - break; - case ("GroupRef"): - shape.setGroupRef(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); - break; - } - } + @Override + public Shape parse(Element eElement) throws ConverterException { + if (!eElement.getNodeName().equals("Shape")) { + throw new InvalidArgumentException(ShapeParser.class.getSimpleName() + " can parse only Shape xml nodes"); + } + Shape shape = new Shape(eElement.getAttribute("GraphId")); + for (Pair<String, String> entry : getAttributes(eElement)) { + switch (entry.getLeft()) { + case ("GraphId"): + break; + case ("TextLabel"): + shape.setTextLabel(entry.getRight()); + break; + case ("GroupRef"): + shape.setGroupRef(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); + break; + } + } - NodeList tmpList = eElement.getChildNodes(); - for (int j = 0; j < tmpList.getLength(); j++) { - Node tmpNode = tmpList.item(j); - if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { - Element eTmp = (Element) tmpNode; - switch (eTmp.getNodeName()) { - case ("Graphics"): - parseGraphics(eTmp, shape); - break; - case ("Attribute"): - parseAttribute(eTmp, shape); - break; - case ("Comment"): - shape.addComment(eTmp.getTextContent()); - break; - case ("BiopaxRef"): - shape.addBiopaxReference(eTmp.getTextContent()); - break; - default: - logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); - break; - } - } - } - return shape; - } + NodeList tmpList = eElement.getChildNodes(); + for (int j = 0; j < tmpList.getLength(); j++) { + Node tmpNode = tmpList.item(j); + if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { + Element eTmp = (Element) tmpNode; + switch (eTmp.getNodeName()) { + case ("Graphics"): + parseGraphics(eTmp, shape); + break; + case ("Attribute"): + parseAttribute(eTmp, shape); + break; + case ("Comment"): + shape.addComment(eTmp.getTextContent()); + break; + case ("BiopaxRef"): + shape.addBiopaxReference(eTmp.getTextContent()); + break; + default: + logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); + break; + } + } + } + return shape; + } - /** - * Method that parses {@link Shape} xml attribute. - * - * @param eTmp - * xml node with attribute - * @param shape - * shape where data should be added - */ - private void parseAttribute(Element eTmp, Shape shape) { - String key = eTmp.getAttribute("Key"); - String value = eTmp.getAttribute("Value"); - switch (key) { - case ("org.pathvisio.CellularComponentProperty"): - shape.setCompartment(true); - break; - case ("org.pathvisio.DoubleLineProperty"): - switch (value) { - case ("Double"): - shape.setLineType(LineType.DOUBLE); - break; - default: - logger.warn(shape.getWarningPrefix() + "Unknown line type: " + value); - break; - } - break; - default: - logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key:" + key + "; value: " + value); - break; - } - } + @Override + public String toXml(Shape node) throws ConverterException { + throw new NotImplementedException(); + } - /** - * Parse graphics xml node in the shape node. - * - * @param eTmp - * xml node with graphics - * @param shape - * shape where data should be added - * @throws UnknownTypeException - * thrown when some types in the xml node are unknown - */ - private void parseGraphics(Element eTmp, Shape shape) throws UnknownTypeException { - Double centerX = null; - Double centerY = null; - Double width = null; - Double height = null; - for (Pair<String, String> entry : getAttributes(eTmp)) { - if (!parseCommonGraphicAttributes(shape, entry)) { - switch (entry.getLeft()) { - case ("CenterX"): - centerX = Double.valueOf(entry.getRight()); - break; - case ("CenterY"): - centerY = Double.valueOf(entry.getRight()); - break; - case ("Width"): - width = Double.valueOf(entry.getRight()); - break; - case ("Height"): - height = Double.valueOf(entry.getRight()); - break; - case ("ShapeType"): - shape.setShape(entry.getRight()); - break; - case ("Color"): - shape.setColor(hexStringToColor(entry.getRight())); - break; - case ("FillColor"): - shape.setFillColor(hexStringToColor(entry.getRight())); - break; - case ("ZOrder"): - shape.setzOrder(Integer.valueOf(entry.getRight())); - break; - case ("FontSize"): - shape.setFontSize(Double.valueOf(entry.getRight())); - break; - case ("LineThickness"): - shape.setLineThickness(Double.valueOf(entry.getRight())); - break; - case ("Valign"): - shape.setvAlign(entry.getRight()); - break; - case ("FontWeight"): - switch (entry.getRight()) { - case ("Bold"): - shape.addFontAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); - break; - default: - logger.warn("Unknown value of attribute: " + entry.getLeft() + " - " + entry.getRight()); - break; - } - break; - case ("Rotation"): - shape.setRotation(Double.valueOf(entry.getRight())); - break; - default: - logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft()); - break; - } - } - } - shape.setRectangle(new Rectangle2D.Double(centerX - width / 2, centerY - height / 2, width, height)); - } + @Override + public String toXml(Collection<Shape> list) throws ConverterException { + throw new NotImplementedException(); + } - @Override - public String toXml(Shape node) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Method that parses {@link Shape} xml attribute. + * + * @param eTmp + * xml node with attribute + * @param shape + * shape where data should be added + */ + private void parseAttribute(Element eTmp, Shape shape) { + String key = eTmp.getAttribute("Key"); + String value = eTmp.getAttribute("Value"); + switch (key) { + case ("org.pathvisio.CellularComponentProperty"): + shape.setCompartment(true); + break; + case ("org.pathvisio.DoubleLineProperty"): + switch (value) { + case ("Double"): + shape.setLineType(LineType.DOUBLE); + break; + default: + logger.warn(shape.getWarningPrefix() + "Unknown line type: " + value); + break; + } + break; + default: + logger.warn(shape.getWarningPrefix() + "Unknown attribute of node. Key:" + key + "; value: " + value); + break; + } + } - @Override - public String toXml(Collection<Shape> list) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Parse graphics xml node in the shape node. + * + * @param eTmp + * xml node with graphics + * @param shape + * shape where data should be added + * @throws UnknownTypeException + * thrown when some types in the xml node are unknown + */ + private void parseGraphics(Element eTmp, Shape shape) throws UnknownTypeException { + Double centerX = null; + Double centerY = null; + Double width = null; + Double height = null; + for (Pair<String, String> entry : getAttributes(eTmp)) { + if (!parseCommonGraphicAttributes(shape, entry)) { + switch (entry.getLeft()) { + case ("CenterX"): + centerX = Double.valueOf(entry.getRight()); + break; + case ("CenterY"): + centerY = Double.valueOf(entry.getRight()); + break; + case ("Width"): + width = Double.valueOf(entry.getRight()); + break; + case ("Height"): + height = Double.valueOf(entry.getRight()); + break; + case ("ShapeType"): + shape.setShape(entry.getRight()); + break; + case ("Color"): + shape.setColor(hexStringToColor(entry.getRight())); + break; + case ("FillColor"): + shape.setFillColor(hexStringToColor(entry.getRight())); + break; + case ("ZOrder"): + shape.setzOrder(Integer.valueOf(entry.getRight())); + break; + case ("FontSize"): + shape.setFontSize(Double.valueOf(entry.getRight())); + break; + case ("LineThickness"): + shape.setLineThickness(Double.valueOf(entry.getRight())); + break; + case ("Valign"): + shape.setvAlign(entry.getRight()); + break; + case ("FontWeight"): + switch (entry.getRight()) { + case ("Bold"): + shape.addFontAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); + break; + default: + logger.warn("Unknown value of attribute: " + entry.getLeft() + " - " + entry.getRight()); + break; + } + break; + case ("Rotation"): + shape.setRotation(Double.valueOf(entry.getRight())); + break; + default: + logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft()); + break; + } + } + } + shape.setRectangle(new Rectangle2D.Double(centerX - width / 2, centerY - height / 2, width, height)); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/StateParser.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/StateParser.java index c31cf5f56b..99deb50bad 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/StateParser.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/StateParser.java @@ -2,20 +2,16 @@ package lcsb.mapviewer.wikipathway.XML; import java.util.Collection; -import org.apache.logging.log4j.*; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.w3c.dom.*; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.wikipathway.model.GpmlModificationType; -import lcsb.mapviewer.wikipathway.model.GpmlStateType; -import lcsb.mapviewer.wikipathway.model.State; -import lcsb.mapviewer.wikipathway.model.UnknownTypeException; +import lcsb.mapviewer.wikipathway.model.*; /** * Parser class that creates {@link State} objects from Xml {@link Element node} @@ -26,146 +22,146 @@ import lcsb.mapviewer.wikipathway.model.UnknownTypeException; */ public class StateParser extends ElementGpmlParser<State> { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(StateParser.class); + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(StateParser.class); - /** - * Parser used for extracting {@link lcsb.mapviewer.model.map.MiriamData - * references} from GPML model. - */ - private ReferenceParser referenceParser = new ReferenceParser(); + /** + * Parser used for extracting {@link lcsb.mapviewer.model.map.MiriamData + * references} from GPML model. + */ + private ReferenceParser referenceParser = new ReferenceParser(); - @Override - public State parse(Element eElement) throws ConverterException { - if (!eElement.getNodeName().equals("State")) { - throw new InvalidArgumentException(StateParser.class.getSimpleName() + " can parse only State xml nodes"); - } - State state = new State(eElement.getAttribute("GraphId")); - for (Pair<String, String> entry : getAttributes(eElement)) { - switch (entry.getLeft()) { - case ("GraphId"): - break; - case ("TextLabel"): - try { - GpmlModificationType type = GpmlModificationType.getByGpmlName(entry.getRight()); - state.setType(type.getCorrespondingModificationState()); - } catch (UnknownTypeException e) { - try { - GpmlStateType type = GpmlStateType.getByGpmlName(entry.getRight()); - state.setStructuralState(type.getStringRepresenation()); - } catch (UnknownTypeException e2) { - throw new ConverterException("Unknown state type: " + entry.getRight()); - } - } - break; - case ("GraphRef"): - state.setGraphRef(entry.getRight()); - break; - default: - logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); - break; - } - } + @Override + public State parse(Element eElement) throws ConverterException { + if (!eElement.getNodeName().equals("State")) { + throw new InvalidArgumentException(StateParser.class.getSimpleName() + " can parse only State xml nodes"); + } + State state = new State(eElement.getAttribute("GraphId")); + for (Pair<String, String> entry : getAttributes(eElement)) { + switch (entry.getLeft()) { + case ("GraphId"): + break; + case ("TextLabel"): + try { + GpmlModificationType type = GpmlModificationType.getByGpmlName(entry.getRight()); + state.setType(type.getCorrespondingModificationState()); + } catch (UnknownTypeException e) { + try { + GpmlStateType type = GpmlStateType.getByGpmlName(entry.getRight()); + state.setStructuralState(type.getStringRepresenation()); + } catch (UnknownTypeException e2) { + throw new ConverterException("Unknown state type: " + entry.getRight()); + } + } + break; + case ("GraphRef"): + state.setGraphRef(entry.getRight()); + break; + default: + logger.warn("Unknown attribute of " + eElement.getNodeName() + " node: " + entry.getLeft()); + break; + } + } - NodeList tmpList = eElement.getChildNodes(); - for (int j = 0; j < tmpList.getLength(); j++) { - Node tmpNode = tmpList.item(j); - if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { - Element eTmp = (Element) tmpNode; - switch (eTmp.getNodeName()) { - case ("Comment"): - state.addComment(eTmp.getTextContent()); - break; - case ("Graphics"): - parseGraphics(eTmp, state); - break; - case ("Attribute"): - parseAttribute(eTmp, state); - break; - case ("BiopaxRef"): - state.addBiopaxReference(eTmp.getTextContent()); - break; - case ("Xref"): - MiriamData md = referenceParser.parse(eTmp); - if (md != null) { - state.addReference(md); - } - break; - default: - logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); - break; - } - } - } - return state; - } + NodeList tmpList = eElement.getChildNodes(); + for (int j = 0; j < tmpList.getLength(); j++) { + Node tmpNode = tmpList.item(j); + if (tmpNode.getNodeType() == Node.ELEMENT_NODE) { + Element eTmp = (Element) tmpNode; + switch (eTmp.getNodeName()) { + case ("Comment"): + state.addComment(eTmp.getTextContent()); + break; + case ("Graphics"): + parseGraphics(eTmp, state); + break; + case ("Attribute"): + parseAttribute(eTmp, state); + break; + case ("BiopaxRef"): + state.addBiopaxReference(eTmp.getTextContent()); + break; + case ("Xref"): + MiriamData md = referenceParser.parse(eTmp); + if (md != null) { + state.addReference(md); + } + break; + default: + logger.warn("Unknown sub-node of " + eElement.getNodeName() + " node: " + eTmp.getNodeName()); + break; + } + } + } + return state; + } - /** - * Parse graphics xml node in the state node. - * - * @param eTmp - * xml node with graphics - * @param state - * state where data should be added - * @throws UnknownTypeException - * thrown when some types in the xml node are unknown - */ - private void parseGraphics(Element eTmp, State state) throws UnknownTypeException { - for (Pair<String, String> entry : getAttributes(eTmp)) { - switch (entry.getLeft()) { - case ("RelX"): - state.setRelX(Double.valueOf(entry.getRight())); - break; - case ("RelY"): - state.setRelY(Double.valueOf(entry.getRight())); - break; - case ("Width"): - state.setWidth(Double.valueOf(entry.getRight())); - break; - case ("Height"): - state.setHeight(Double.valueOf(entry.getRight())); - break; - case ("ShapeType"): - state.setShape(entry.getRight()); - break; - case ("FillColor"): - state.setFillColor(hexStringToColor(entry.getRight())); - break; - default: - logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft()); - break; - } - } - } + @Override + public String toXml(State node) throws ConverterException { + throw new NotImplementedException(); + } - /** - * Method that parses {@link State} xml attribute. - * - * @param eTmp - * xml node with attribute - * @param state - * state where data should be added - */ - private void parseAttribute(Element eTmp, State state) { - String key = eTmp.getAttribute("Key"); - String value = eTmp.getAttribute("Value"); - switch (key) { - default: - logger.warn(state.getWarningPrefix() + "Unknown attribute of node. Key:" + key + "; value: " + value); - break; - } - } + @Override + public String toXml(Collection<State> list) throws ConverterException { + throw new NotImplementedException(); + } - @Override - public String toXml(State node) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Parse graphics xml node in the state node. + * + * @param eTmp + * xml node with graphics + * @param state + * state where data should be added + * @throws UnknownTypeException + * thrown when some types in the xml node are unknown + */ + private void parseGraphics(Element eTmp, State state) throws UnknownTypeException { + for (Pair<String, String> entry : getAttributes(eTmp)) { + switch (entry.getLeft()) { + case ("RelX"): + state.setRelX(Double.valueOf(entry.getRight())); + break; + case ("RelY"): + state.setRelY(Double.valueOf(entry.getRight())); + break; + case ("Width"): + state.setWidth(Double.valueOf(entry.getRight())); + break; + case ("Height"): + state.setHeight(Double.valueOf(entry.getRight())); + break; + case ("ShapeType"): + state.setShape(entry.getRight()); + break; + case ("FillColor"): + state.setFillColor(hexStringToColor(entry.getRight())); + break; + default: + logger.warn("Unknown attribute of " + eTmp.getNodeName() + " node: " + entry.getLeft()); + break; + } + } + } - @Override - public String toXml(Collection<State> list) throws ConverterException { - throw new NotImplementedException(); - } + /** + * Method that parses {@link State} xml attribute. + * + * @param eTmp + * xml node with attribute + * @param state + * state where data should be added + */ + private void parseAttribute(Element eTmp, State state) { + String key = eTmp.getAttribute("Key"); + String value = eTmp.getAttribute("Value"); + switch (key) { + default: + logger.warn(state.getWarningPrefix() + "Unknown attribute of node. Key:" + key + "; value: " + value); + break; + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownAttributeValueException.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownAttributeValueException.java index f531fc0925..b4d755fd5b 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownAttributeValueException.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownAttributeValueException.java @@ -3,27 +3,27 @@ package lcsb.mapviewer.wikipathway.XML; import lcsb.mapviewer.converter.ConverterException; /** - * Exception that shold be thrown when the value of the attribute in xml is invalid. + * Exception that shold be thrown when the value of the attribute in xml is + * invalid. * * @author Piotr Gawron * */ public class UnknownAttributeValueException extends ConverterException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public UnknownAttributeValueException(String string) { - super(string); - } + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public UnknownAttributeValueException(String string) { + super(string); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownChildClassException.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownChildClassException.java index c070d7c60a..cd281aac89 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownChildClassException.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownChildClassException.java @@ -11,20 +11,19 @@ import lcsb.mapviewer.converter.ConverterException; */ public class UnknownChildClassException extends ConverterException { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public UnknownChildClassException(String string) { - super(string); - } + /** + * + */ + private static final long serialVersionUID = 1L; + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public UnknownChildClassException(String string) { + super(string); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownMergingMethodException.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownMergingMethodException.java index 6cc97d1d02..27a270b765 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownMergingMethodException.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/UnknownMergingMethodException.java @@ -11,19 +11,19 @@ import lcsb.mapviewer.converter.ConverterException; */ public class UnknownMergingMethodException extends ConverterException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public UnknownMergingMethodException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public UnknownMergingMethodException(String string) { + super(string); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/package-info.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/package-info.java index 1cbdfb96fc..c7465a0f2a 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/package-info.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/XML/package-info.java @@ -2,4 +2,3 @@ * Contains xml parser for gpml model. */ package lcsb.mapviewer.wikipathway.XML; - diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/DataNode.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/DataNode.java index 73f39e5788..480dfef4fe 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/DataNode.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/DataNode.java @@ -14,201 +14,201 @@ import lcsb.mapviewer.model.map.MiriamData; */ public class DataNode extends GraphicalPathwayElement { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * References. - */ - private List<MiriamData> references = new ArrayList<>(); - - /** - * ??? - */ - private String type; - - /** - * Type o line used to draw element. - */ - private LineType lineType = LineType.SOLID; - - /** - * ??? - */ - private String textLabel; - - /** - * Where this node belongs to. - */ - private String groupRef; - - /** - * Font weight (like italic, bold) that should be used. - */ - private String fontWeight; - - /** - * Align of the description. - */ - private String vAlign; - - /** - * Default constructor. - * - * @param graphId - * {@link PathwayElement#graphId} - */ - public DataNode(String graphId) { - super(graphId); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected DataNode() { - super(); - } - - @Override - public String toString() { - return textLabel + " " + getGraphId() + " " + groupRef + " " + type; - } - - @Override - public String getName() { - return getTextLabel(); - } - - /** - * @return the type - * @see #type - */ - public String getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(String type) { - this.type = type; - } - - /** - * @return the textLabel - * @see #textLabel - */ - public String getTextLabel() { - return textLabel; - } - - /** - * @param textLabel - * the textLabel to set - * @see #textLabel - */ - public void setTextLabel(String textLabel) { - this.textLabel = textLabel; - } - - /** - * @return the groupRef - * @see #groupRef - */ - public String getGroupRef() { - return groupRef; - } - - /** - * @param groupRef - * the groupRef to set - * @see #groupRef - */ - public void setGroupRef(String groupRef) { - this.groupRef = groupRef; - } - - /** - * @return the references - * @see #references - */ - public List<MiriamData> getReferences() { - return references; - } - - /** - * @param references - * the references to set - * @see #references - */ - public void setReferences(List<MiriamData> references) { - this.references = references; - } - - /** - * @return the vAlign - * @see #vAlign - */ - public String getvAlign() { - return vAlign; - } - - /** - * @param vAlign - * the vAlign to set - * @see #vAlign - */ - public void setvAlign(String vAlign) { - this.vAlign = vAlign; - } - - /** - * Adds reference to node. - * - * @param md - * objet to add - */ - public void addReference(MiriamData md) { - references.add(md); - } - - /** - * @return the lineType - * @see #lineType - */ - public LineType getLineType() { - return lineType; - } - - /** - * @param lineType - * the lineType to set - * @see #lineType - */ - public void setLineType(LineType lineType) { - this.lineType = lineType; - } - - /** - * @return the fontWeight - * @see #fontWeight - */ - public String getFontWeight() { - return fontWeight; - } - - /** - * @param fontWeight - * the fontWeight to set - * @see #fontWeight - */ - public void setFontWeight(String fontWeight) { - this.fontWeight = fontWeight; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * References. + */ + private List<MiriamData> references = new ArrayList<>(); + + /** + * ??? + */ + private String type; + + /** + * Type o line used to draw element. + */ + private LineType lineType = LineType.SOLID; + + /** + * ??? + */ + private String textLabel; + + /** + * Where this node belongs to. + */ + private String groupRef; + + /** + * Font weight (like italic, bold) that should be used. + */ + private String fontWeight; + + /** + * Align of the description. + */ + private String vAlign; + + /** + * Default constructor. + * + * @param graphId + * {@link PathwayElement#graphId} + */ + public DataNode(String graphId) { + super(graphId); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected DataNode() { + super(); + } + + @Override + public String toString() { + return textLabel + " " + getGraphId() + " " + groupRef + " " + type; + } + + @Override + public String getName() { + return getTextLabel(); + } + + /** + * @return the type + * @see #type + */ + public String getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return the textLabel + * @see #textLabel + */ + public String getTextLabel() { + return textLabel; + } + + /** + * @param textLabel + * the textLabel to set + * @see #textLabel + */ + public void setTextLabel(String textLabel) { + this.textLabel = textLabel; + } + + /** + * @return the groupRef + * @see #groupRef + */ + public String getGroupRef() { + return groupRef; + } + + /** + * @param groupRef + * the groupRef to set + * @see #groupRef + */ + public void setGroupRef(String groupRef) { + this.groupRef = groupRef; + } + + /** + * @return the references + * @see #references + */ + public List<MiriamData> getReferences() { + return references; + } + + /** + * @param references + * the references to set + * @see #references + */ + public void setReferences(List<MiriamData> references) { + this.references = references; + } + + /** + * @return the vAlign + * @see #vAlign + */ + public String getvAlign() { + return vAlign; + } + + /** + * @param vAlign + * the vAlign to set + * @see #vAlign + */ + public void setvAlign(String vAlign) { + this.vAlign = vAlign; + } + + /** + * Adds reference to node. + * + * @param md + * objet to add + */ + public void addReference(MiriamData md) { + references.add(md); + } + + /** + * @return the lineType + * @see #lineType + */ + public LineType getLineType() { + return lineType; + } + + /** + * @param lineType + * the lineType to set + * @see #lineType + */ + public void setLineType(LineType lineType) { + this.lineType = lineType; + } + + /** + * @return the fontWeight + * @see #fontWeight + */ + public String getFontWeight() { + return fontWeight; + } + + /** + * @param fontWeight + * the fontWeight to set + * @see #fontWeight + */ + public void setFontWeight(String fontWeight) { + this.fontWeight = fontWeight; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Direction.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Direction.java index 53e55ce336..2fddb3e568 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Direction.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Direction.java @@ -9,72 +9,72 @@ package lcsb.mapviewer.wikipathway.model; */ public enum Direction { - /** - * North. - */ - NORTH(Axis.NORTH_SOUTH), + /** + * North. + */ + NORTH(Axis.NORTH_SOUTH), - /** - * East. - */ - EAST(Axis.EAST_WEST), + /** + * East. + */ + EAST(Axis.EAST_WEST), - /** - * South. - */ - SOUTH(Axis.NORTH_SOUTH), + /** + * South. + */ + SOUTH(Axis.NORTH_SOUTH), - /** - * West. - */ - WEST(Axis.EAST_WEST); + /** + * West. + */ + WEST(Axis.EAST_WEST); - /** - * Defines axis in which direction lies (either {@link Axis#NORTH_SOUTH} or - * {@link Axis#EAST_WEST}). - */ - private Axis axis; + /** + * Defines axis in which direction lies (either {@link Axis#NORTH_SOUTH} or + * {@link Axis#EAST_WEST}). + */ + private Axis axis; - /** - * Default cosntructor. - * - * @param axis - * {@link #axis} - */ - Direction(Axis axis) { - this.axis = axis; - } + /** + * Default cosntructor. + * + * @param axis + * {@link #axis} + */ + Direction(Axis axis) { + this.axis = axis; + } - /** - * Defines axis in which {@link Direction} can lie (either - * {@link Axis#NORTH_SOUTH} or {@link Axis#EAST_WEST}). - */ - public enum Axis { - /** - * Axis going from NORTH to SOUTH (or from SOUTH to NORTH). - */ - NORTH_SOUTH, - /** - * Axis going from WEST to EAST (or from EAST to WEST). - */ + /** + * @return the axis + * @see #axis + */ + public Axis getAxis() { + return axis; + } - EAST_WEST; - } + /** + * Returns next direction (by 90 degrees) in clockwise order. + * + * @return next direction (by 90 degrees) in clockwise order + */ + public Direction nextClockwiseDirection() { + return values()[(this.ordinal() + 1) % values().length]; + } - /** - * @return the axis - * @see #axis - */ - public Axis getAxis() { - return axis; - } + /** + * Defines axis in which {@link Direction} can lie (either + * {@link Axis#NORTH_SOUTH} or {@link Axis#EAST_WEST}). + */ + public enum Axis { + /** + * Axis going from NORTH to SOUTH (or from SOUTH to NORTH). + */ + NORTH_SOUTH, + /** + * Axis going from WEST to EAST (or from EAST to WEST). + */ - /** - * Returns next direction (by 90 degrees) in clockwise order. - * - * @return next direction (by 90 degrees) in clockwise order - */ - public Direction nextClockwiseDirection() { - return values()[(this.ordinal() + 1) % values().length]; - } + EAST_WEST; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Edge.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Edge.java index 062fbb0090..7baa8a54aa 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Edge.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Edge.java @@ -1,14 +1,13 @@ package lcsb.mapviewer.wikipathway.model; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.graphics.PolylineData; @@ -24,446 +23,448 @@ import lcsb.mapviewer.model.map.MiriamData; */ public class Edge implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Epsilon valu used for comparison of doubles. - */ - private static final Double EPSILON = 1e-6; - - /** - * Default class logger. - */ - private final transient Logger logger = LogManager.getLogger(Edge.class); - - /** - * Identifier in gpml model. - */ - private String graphId; - - /** - * In which group this edge is located. - */ - private String groupRef; - - /** - * Where this {@link Edge} starts (in which {@link Edge}/{@link Interaction}). - */ - private String start; - - /** - * Where this {@link Edge} ends (in which {@link Edge}/{@link Interaction}). - */ - private String end; - - /** - * Z-order of the line (how much to front it should be located). - */ - private Integer zOrder; - - /** - * Line representing this edge. - */ - private PolylineData line = new PolylineData(); - - /** - * Gpml interaction type (arrow). - */ - private GpmlInteractionType type = GpmlInteractionType.LINE; - - /** - * References for given edge. - */ - private List<MiriamData> references = new ArrayList<>(); - - /** - * List of anchors placed on the edge. - */ - private Set<String> anchors = new HashSet<>(); - - /** - * Comments. - */ - private List<String> comments = new ArrayList<>(); - - /** - * List of identifiers used by biopax nodes that are inside gpml. These biopax - * nodes contain annotations. - */ - private List<String> biopaxReferences = new ArrayList<String>(); - - /** - * Default constructor. - * - * @param graphId - * {@link #graphId} - */ - public Edge(String graphId) { - this.graphId = graphId; - } - - /** - * Creates new instance that contains the same data as the parameter object. - * - * @param original - * original object from which data is being copied - */ - public Edge(Edge original) { - this.graphId = original.getGraphId(); - this.groupRef = original.getGroupRef(); - this.start = original.getStart(); - this.end = original.getEnd(); - this.line = new PolylineData(original.getLine()); - this.type = original.getType(); - for (MiriamData md : original.getReferences()) { - addReference(new MiriamData(md)); - } - this.anchors.addAll(original.getAnchors()); - this.comments.addAll(original.getComments()); - this.biopaxReferences.addAll(original.getBiopaxReferences()); - this.zOrder = original.getzOrder(); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected Edge() { - } - - /** - * Adds reference to the object. - * - * @param reference - * reference to add - */ - public void addReference(MiriamData reference) { - references.add(reference); - } - - /** - * Adds anchor to {@link #anchors}. - * - * @param anchor - * object to add - */ - public void addAnchor(String anchor) { - this.anchors.add(anchor); - } - - /** - * @return the graphId - * @see #graphId - */ - public String getGraphId() { - return graphId; - } - - /** - * @param graphId - * the graphId to set - * @see #graphId - */ - public void setGraphId(String graphId) { - this.graphId = graphId; - } - - /** - * @return the start - * @see #start - */ - public String getStart() { - return start; - } - - /** - * @param start - * the start to set - * @see #start - */ - public void setStart(String start) { - this.start = start; - } - - /** - * @return the end - * @see #end - */ - public String getEnd() { - return end; - } - - /** - * @param end - * the end to set - * @see #end - */ - public void setEnd(String end) { - this.end = end; - } - - /** - * @return the line - * @see #line - */ - public PolylineData getLine() { - return line; - } - - /** - * @param line - * the line to set - * @see #line - */ - public void setLine(PolylineData line) { - this.line = line; - } - - /** - * @return the anchors - * @see #anchors - */ - public Set<String> getAnchors() { - return anchors; - } - - /** - * @param anchors - * the anchors to set - * @see #anchors - */ - public void setAnchors(Set<String> anchors) { - this.anchors = anchors; - } - - /** - * @return the comments - * @see #comments - */ - public List<String> getComments() { - return comments; - } - - /** - * @param comment - * the comment to add - * @see #comment - */ - public void addComment(String comment) { - this.comments.add(comment); - } - - /** - * @return the biopaxReferences - * @see #biopaxReferences - */ - public List<String> getBiopaxReferences() { - return biopaxReferences; - } - - /** - * @param biopaxReferences - * the biopaxReferences to set - * @see #biopaxReferences - */ - public void setBiopaxReferences(List<String> biopaxReferences) { - this.biopaxReferences = biopaxReferences; - } - - /** - * Returns a prefix that should be used in warnings. - * - * @return string that identifies element in logs - */ - public String getWarningPrefix() { - return "[" + getType() + ", id: " + getGraphId() + "]\t"; - } - - /** - * @return the type - * @see #type - */ - public GpmlInteractionType getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(GpmlInteractionType type) { - if (type != null) { - this.type = type; - } - } - - /** - * Reverse direction of edge (order of elements). - * - * @return copy of the object that is reversed - */ - public Edge reverse() { - Edge result = new Edge(this); - result.setLine(result.getLine().reverse()); - String tmp = result.getStart(); - result.setStart(result.getEnd()); - result.setEnd(tmp); - - return result; - } - - /** - * @return the references - * @see #references - */ - public List<MiriamData> getReferences() { - return references; - } - - /** - * @param references - * the references to set - * @see #references - */ - public void setReferences(List<MiriamData> references) { - this.references = references; - } - - /** - * Adds set of references. - * - * @param references - * references to add - */ - public void addReferences(List<MiriamData> references) { - for (MiriamData miriamData : references) { - addReference(miriamData); - } - } - - /** - * This method extend edge (the line) by adding data from the edge in - * parameter. - * - * @param edge2 - * edge that should be used for extension - */ - public void extend(Edge edge2) { - // check if extension make sense (they should point to the same identifier) - if (!getEnd().equals(edge2.getStart())) { - throw new InvalidArgumentException( - getWarningPrefix() + edge2.getWarningPrefix() + " Cannot merge - anchor points doesn't match: " + getEnd() + "," + edge2.getStart()); - } - - if (line.getEndPoint().distance(edge2.getLine().getBeginPoint()) > EPSILON) { - throw new InvalidArgumentException( - getWarningPrefix() + edge2.getWarningPrefix() + " Cannot merge - edges are far from each other: " + line.getEndPoint() + "," - + edge2.getLine().getBeginPoint()); - } - - // graphId should be the same - - // start should be taken from the original - - // end should be taken from the extension - setEnd(edge2.getEnd()); - - // add points - for (int i = 1; i < edge2.getLine().getPoints().size(); i++) { - Point2D p = (Point2D) edge2.getLine().getPoints().get(i).clone(); - line.addPoint(p); - } - - // skip type - - for (MiriamData md : edge2.getReferences()) { - addReference(new MiriamData(md)); - } - anchors.addAll(edge2.getAnchors()); - List<String> toAdd = new ArrayList<>(); - for (String comment : edge2.getComments()) { - if (!comments.contains(comment)) { - toAdd.add(comment); - } - } - comments.addAll(toAdd); - - // color should be skipped - if (!getColor().equals(edge2.getColor())) { - logger.warn(getWarningPrefix() + edge2.getWarningPrefix() + " Problem with merging. Edges have different colors."); - } - - // add biopax references - biopaxReferences.addAll(edge2.getBiopaxReferences()); - - } - - /** - * @return the color - * @see #color - */ - public Color getColor() { - return line.getColor(); - } - - /** - * @param color - * the color to set - * @see #color - */ - public void setColor(Color color) { - if (color != null) { - line.setColor(color); - } - } - - /** - * @return the zOrder - * @see #zOrder - */ - public Integer getzOrder() { - return zOrder; - } - - /** - * @param zOrder - * the zOrder to set - * @see #zOrder - */ - public void setzOrder(Integer zOrder) { - this.zOrder = zOrder; - } - - /** - * Adds element to {@link #biopaxReferences}. - * - * @param reference - * reference to add - */ - public void addBiopaxReference(String reference) { - biopaxReferences.add(reference); - - } - - /** - * @return the groupRef - * @see #groupRef - */ - public String getGroupRef() { - return groupRef; - } - - /** - * @param groupRef - * the groupRef to set - * @see #groupRef - */ - public void setGroupRef(String groupRef) { - this.groupRef = groupRef; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Epsilon valu used for comparison of doubles. + */ + private static final Double EPSILON = 1e-6; + + /** + * Default class logger. + */ + private final transient Logger logger = LogManager.getLogger(Edge.class); + + /** + * Identifier in gpml model. + */ + private String graphId; + + /** + * In which group this edge is located. + */ + private String groupRef; + + /** + * Where this {@link Edge} starts (in which {@link Edge}/{@link Interaction}). + */ + private String start; + + /** + * Where this {@link Edge} ends (in which {@link Edge}/{@link Interaction}). + */ + private String end; + + /** + * Z-order of the line (how much to front it should be located). + */ + private Integer zOrder; + + /** + * Line representing this edge. + */ + private PolylineData line = new PolylineData(); + + /** + * Gpml interaction type (arrow). + */ + private GpmlInteractionType type = GpmlInteractionType.LINE; + + /** + * References for given edge. + */ + private List<MiriamData> references = new ArrayList<>(); + + /** + * List of anchors placed on the edge. + */ + private Set<String> anchors = new HashSet<>(); + + /** + * Comments. + */ + private List<String> comments = new ArrayList<>(); + + /** + * List of identifiers used by biopax nodes that are inside gpml. These biopax + * nodes contain annotations. + */ + private List<String> biopaxReferences = new ArrayList<String>(); + + /** + * Default constructor. + * + * @param graphId + * {@link #graphId} + */ + public Edge(String graphId) { + this.graphId = graphId; + } + + /** + * Creates new instance that contains the same data as the parameter object. + * + * @param original + * original object from which data is being copied + */ + public Edge(Edge original) { + this.graphId = original.getGraphId(); + this.groupRef = original.getGroupRef(); + this.start = original.getStart(); + this.end = original.getEnd(); + this.line = new PolylineData(original.getLine()); + this.type = original.getType(); + for (MiriamData md : original.getReferences()) { + addReference(new MiriamData(md)); + } + this.anchors.addAll(original.getAnchors()); + this.comments.addAll(original.getComments()); + this.biopaxReferences.addAll(original.getBiopaxReferences()); + this.zOrder = original.getzOrder(); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected Edge() { + } + + /** + * Adds reference to the object. + * + * @param reference + * reference to add + */ + public void addReference(MiriamData reference) { + references.add(reference); + } + + /** + * Adds anchor to {@link #anchors}. + * + * @param anchor + * object to add + */ + public void addAnchor(String anchor) { + this.anchors.add(anchor); + } + + /** + * @return the graphId + * @see #graphId + */ + public String getGraphId() { + return graphId; + } + + /** + * @param graphId + * the graphId to set + * @see #graphId + */ + public void setGraphId(String graphId) { + this.graphId = graphId; + } + + /** + * @return the start + * @see #start + */ + public String getStart() { + return start; + } + + /** + * @param start + * the start to set + * @see #start + */ + public void setStart(String start) { + this.start = start; + } + + /** + * @return the end + * @see #end + */ + public String getEnd() { + return end; + } + + /** + * @param end + * the end to set + * @see #end + */ + public void setEnd(String end) { + this.end = end; + } + + /** + * @return the line + * @see #line + */ + public PolylineData getLine() { + return line; + } + + /** + * @param line + * the line to set + * @see #line + */ + public void setLine(PolylineData line) { + this.line = line; + } + + /** + * @return the anchors + * @see #anchors + */ + public Set<String> getAnchors() { + return anchors; + } + + /** + * @param anchors + * the anchors to set + * @see #anchors + */ + public void setAnchors(Set<String> anchors) { + this.anchors = anchors; + } + + /** + * @return the comments + * @see #comments + */ + public List<String> getComments() { + return comments; + } + + /** + * @param comment + * the comment to add + * @see #comment + */ + public void addComment(String comment) { + this.comments.add(comment); + } + + /** + * @return the biopaxReferences + * @see #biopaxReferences + */ + public List<String> getBiopaxReferences() { + return biopaxReferences; + } + + /** + * @param biopaxReferences + * the biopaxReferences to set + * @see #biopaxReferences + */ + public void setBiopaxReferences(List<String> biopaxReferences) { + this.biopaxReferences = biopaxReferences; + } + + /** + * Returns a prefix that should be used in warnings. + * + * @return string that identifies element in logs + */ + public String getWarningPrefix() { + return "[" + getType() + ", id: " + getGraphId() + "]\t"; + } + + /** + * @return the type + * @see #type + */ + public GpmlInteractionType getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(GpmlInteractionType type) { + if (type != null) { + this.type = type; + } + } + + /** + * Reverse direction of edge (order of elements). + * + * @return copy of the object that is reversed + */ + public Edge reverse() { + Edge result = new Edge(this); + result.setLine(result.getLine().reverse()); + String tmp = result.getStart(); + result.setStart(result.getEnd()); + result.setEnd(tmp); + + return result; + } + + /** + * @return the references + * @see #references + */ + public List<MiriamData> getReferences() { + return references; + } + + /** + * @param references + * the references to set + * @see #references + */ + public void setReferences(List<MiriamData> references) { + this.references = references; + } + + /** + * Adds set of references. + * + * @param references + * references to add + */ + public void addReferences(List<MiriamData> references) { + for (MiriamData miriamData : references) { + addReference(miriamData); + } + } + + /** + * This method extend edge (the line) by adding data from the edge in parameter. + * + * @param edge2 + * edge that should be used for extension + */ + public void extend(Edge edge2) { + // check if extension make sense (they should point to the same identifier) + if (!getEnd().equals(edge2.getStart())) { + throw new InvalidArgumentException( + getWarningPrefix() + edge2.getWarningPrefix() + " Cannot merge - anchor points doesn't match: " + getEnd() + + "," + edge2.getStart()); + } + + if (line.getEndPoint().distance(edge2.getLine().getBeginPoint()) > EPSILON) { + throw new InvalidArgumentException( + getWarningPrefix() + edge2.getWarningPrefix() + " Cannot merge - edges are far from each other: " + + line.getEndPoint() + "," + + edge2.getLine().getBeginPoint()); + } + + // graphId should be the same + + // start should be taken from the original + + // end should be taken from the extension + setEnd(edge2.getEnd()); + + // add points + for (int i = 1; i < edge2.getLine().getPoints().size(); i++) { + Point2D p = (Point2D) edge2.getLine().getPoints().get(i).clone(); + line.addPoint(p); + } + + // skip type + + for (MiriamData md : edge2.getReferences()) { + addReference(new MiriamData(md)); + } + anchors.addAll(edge2.getAnchors()); + List<String> toAdd = new ArrayList<>(); + for (String comment : edge2.getComments()) { + if (!comments.contains(comment)) { + toAdd.add(comment); + } + } + comments.addAll(toAdd); + + // color should be skipped + if (!getColor().equals(edge2.getColor())) { + logger + .warn(getWarningPrefix() + edge2.getWarningPrefix() + " Problem with merging. Edges have different colors."); + } + + // add biopax references + biopaxReferences.addAll(edge2.getBiopaxReferences()); + + } + + /** + * @return the color + * @see #color + */ + public Color getColor() { + return line.getColor(); + } + + /** + * @param color + * the color to set + * @see #color + */ + public void setColor(Color color) { + if (color != null) { + line.setColor(color); + } + } + + /** + * @return the zOrder + * @see #zOrder + */ + public Integer getzOrder() { + return zOrder; + } + + /** + * @param zOrder + * the zOrder to set + * @see #zOrder + */ + public void setzOrder(Integer zOrder) { + this.zOrder = zOrder; + } + + /** + * Adds element to {@link #biopaxReferences}. + * + * @param reference + * reference to add + */ + public void addBiopaxReference(String reference) { + biopaxReferences.add(reference); + + } + + /** + * @return the groupRef + * @see #groupRef + */ + public String getGroupRef() { + return groupRef; + } + + /** + * @param groupRef + * the groupRef to set + * @see #groupRef + */ + public void setGroupRef(String groupRef) { + this.groupRef = groupRef; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlInteractionType.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlInteractionType.java index 524c0b7e1a..3775bf5f8e 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlInteractionType.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlInteractionType.java @@ -8,128 +8,128 @@ package lcsb.mapviewer.wikipathway.model; */ public enum GpmlInteractionType { - /** - * Simple line. - */ - LINE(null), - - /** - * Arrow. - */ - ARROW("Arrow"), - - /** - * T-bar. - */ - TBAR("TBar"), - - /** - * Necessary stimulation. - */ - NECESSARY_STIMULATION("mim-necessary-stimulation"), - - /** - * Binding. - */ - BINDING("mim-binding"), - - /** - * Conversion. - */ - CONVERSION("mim-conversion"), - - /** - * Stimulation. - */ - STIMULATION("mim-stimulation"), - - /** - * Modification. - */ - MODIFICATION("mim-modification"), - - /** - * Catalysis. - */ - CATALYSIS("mim-catalysis"), - - /** - * Inhibition. - */ - INHIBITION("mim-inhibition"), - - /** - * Cleavage. - */ - CLEAVAGE("mim-cleavage"), - - /** - * Covalent bond. - */ - COVALENT_BOND("mim-covalent-bond"), - - /** - * Branching (to the left). - */ - BRANCHING_LEFT("mim-branching-left"), - - /** - * Branching (to the right). - */ - BRANCHING_RIGHT("mim-branching-right"), - - /** - * Transcription, translation. - */ - TRANSCRIPTION_TRANSLATION("mim-transcription-translation"), - - /** - * Gap. - */ - GAP("mim-gap"); - - /** - * GPML string representing this type. - */ - private String gpmlString; - - /** - * Default constructor. - * - * @param gpmlString - * {@link #gpmlString} - */ - GpmlInteractionType(String gpmlString) { - this.gpmlString = gpmlString; - } - - /** - * @return the gpmlString - * @see #gpmlString - */ - public String getGpmlString() { - return gpmlString; - } - - /** - * Returns a type identified by the gpml string. - * - * @param gpmlString - * string in GPML represetning type - * @return type identified by the gpml string - * @throws UnknownTypeException - * thrown when type cannot be resolved - */ - public static GpmlInteractionType getTypeByGpmlString(String gpmlString) throws UnknownTypeException { - for (GpmlInteractionType type : values()) { - if (type.getGpmlString() == null) { - if (gpmlString == null || gpmlString.isEmpty()) { - return type; - } - } else if (type.getGpmlString().equals(gpmlString)) { - return type; - } - } - throw new UnknownTypeException("Unknown gpml interaction type: " + gpmlString); - } + /** + * Simple line. + */ + LINE(null), + + /** + * Arrow. + */ + ARROW("Arrow"), + + /** + * T-bar. + */ + TBAR("TBar"), + + /** + * Necessary stimulation. + */ + NECESSARY_STIMULATION("mim-necessary-stimulation"), + + /** + * Binding. + */ + BINDING("mim-binding"), + + /** + * Conversion. + */ + CONVERSION("mim-conversion"), + + /** + * Stimulation. + */ + STIMULATION("mim-stimulation"), + + /** + * Modification. + */ + MODIFICATION("mim-modification"), + + /** + * Catalysis. + */ + CATALYSIS("mim-catalysis"), + + /** + * Inhibition. + */ + INHIBITION("mim-inhibition"), + + /** + * Cleavage. + */ + CLEAVAGE("mim-cleavage"), + + /** + * Covalent bond. + */ + COVALENT_BOND("mim-covalent-bond"), + + /** + * Branching (to the left). + */ + BRANCHING_LEFT("mim-branching-left"), + + /** + * Branching (to the right). + */ + BRANCHING_RIGHT("mim-branching-right"), + + /** + * Transcription, translation. + */ + TRANSCRIPTION_TRANSLATION("mim-transcription-translation"), + + /** + * Gap. + */ + GAP("mim-gap"); + + /** + * GPML string representing this type. + */ + private String gpmlString; + + /** + * Default constructor. + * + * @param gpmlString + * {@link #gpmlString} + */ + GpmlInteractionType(String gpmlString) { + this.gpmlString = gpmlString; + } + + /** + * Returns a type identified by the gpml string. + * + * @param gpmlString + * string in GPML represetning type + * @return type identified by the gpml string + * @throws UnknownTypeException + * thrown when type cannot be resolved + */ + public static GpmlInteractionType getTypeByGpmlString(String gpmlString) throws UnknownTypeException { + for (GpmlInteractionType type : values()) { + if (type.getGpmlString() == null) { + if (gpmlString == null || gpmlString.isEmpty()) { + return type; + } + } else if (type.getGpmlString().equals(gpmlString)) { + return type; + } + } + throw new UnknownTypeException("Unknown gpml interaction type: " + gpmlString); + } + + /** + * @return the gpmlString + * @see #gpmlString + */ + public String getGpmlString() { + return gpmlString; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineConnectorType.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineConnectorType.java index 8eab165591..1fc70aa044 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineConnectorType.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineConnectorType.java @@ -8,66 +8,66 @@ package lcsb.mapviewer.wikipathway.model; */ public enum GpmlLineConnectorType { - /** - * Line is a curve. - */ - CURVED("Curved"), + /** + * Line is a curve. + */ + CURVED("Curved"), - /** - * Line is constructed from list of perpendicular segments. - */ - ELBOW("Elbow"), + /** + * Line is constructed from list of perpendicular segments. + */ + ELBOW("Elbow"), - /** - * It's a straight line from start point to the end point. - */ - STRAIGHT("Straight"), + /** + * It's a straight line from start point to the end point. + */ + STRAIGHT("Straight"), - /** - * Line is constructoed from list of segement lines. - */ - SEGMENTED("Segmented"); + /** + * Line is constructoed from list of segement lines. + */ + SEGMENTED("Segmented"); - /** - * String used in gpml to identify this specific connection type. - */ - private String gpmlName; + /** + * String used in gpml to identify this specific connection type. + */ + private String gpmlName; - /** - * Default constructor. - * - * @param gpmlName - * {@link #gpmlName} - */ - GpmlLineConnectorType(String gpmlName) { - this.gpmlName = gpmlName; - } + /** + * Default constructor. + * + * @param gpmlName + * {@link #gpmlName} + */ + GpmlLineConnectorType(String gpmlName) { + this.gpmlName = gpmlName; + } - /** - * @return the gpmlName - * @see #gpmlName - */ - public String getGpmlName() { - return gpmlName; - } + /** + * Returns {@link GpmlLineConnectorType type} identified by {@link #gpmlName + * gpml string} identifing the type. + * + * @param gpmlName + * {@link #gpmlName} + * @return {@link GpmlLineConnectorType type} identified by {@link #gpmlName + * gpml string} identifing the type + * @throws UnknownTypeException + * thrown when type cannot be found + */ + public static GpmlLineConnectorType getByGpmlName(String gpmlName) throws UnknownTypeException { + for (GpmlLineConnectorType type : values()) { + if (type.getGpmlName().equals(gpmlName)) { + return type; + } + } + throw new UnknownTypeException("Unknown type name: " + gpmlName); + } - /** - * Returns {@link GpmlLineConnectorType type} identified by {@link #gpmlName - * gpml string} identifing the type. - * - * @param gpmlName - * {@link #gpmlName} - * @return {@link GpmlLineConnectorType type} identified by {@link #gpmlName - * gpml string} identifing the type - * @throws UnknownTypeException - * thrown when type cannot be found - */ - public static GpmlLineConnectorType getByGpmlName(String gpmlName) throws UnknownTypeException { - for (GpmlLineConnectorType type : values()) { - if (type.getGpmlName().equals(gpmlName)) { - return type; - } - } - throw new UnknownTypeException("Unknown type name: " + gpmlName); - } + /** + * @return the gpmlName + * @see #gpmlName + */ + public String getGpmlName() { + return gpmlName; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineType.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineType.java index 60a07ccd7d..d8fa12c162 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineType.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlLineType.java @@ -9,77 +9,77 @@ import lcsb.mapviewer.model.graphics.LineType; * */ public enum GpmlLineType { - - /** - * Sold line (global representation: {@link LineType#SOLID}). - */ - SOLID(null, LineType.SOLID), - - /** - * Dashed line (global representation: {@link LineType#DASHED}). - */ - DASHED("Broken", LineType.DASHED); - /** - * String in GPML format representig this type. - */ - private String gpmlString; + /** + * Sold line (global representation: {@link LineType#SOLID}). + */ + SOLID(null, LineType.SOLID), - /** - * Which {@link LineType} in our model should be used for this GPML line type. - */ - private LineType correspondingGlobalLineType; + /** + * Dashed line (global representation: {@link LineType#DASHED}). + */ + DASHED("Broken", LineType.DASHED); - /** - * Default constructor. - * - * @param gpmlString - * {@link #gpmlString} - * @param globalLineType - * {@link #correspondingGlobalLineType} - */ - GpmlLineType(String gpmlString, LineType globalLineType) { - this.gpmlString = gpmlString; - this.correspondingGlobalLineType = globalLineType; - } + /** + * String in GPML format representig this type. + */ + private String gpmlString; - /** - * @return the gpmlString - * @see #gpmlString - */ - public String getGpmlString() { - return gpmlString; - } + /** + * Which {@link LineType} in our model should be used for this GPML line type. + */ + private LineType correspondingGlobalLineType; - /** - * @return the correspondingGlobalLineType - * @see #correspondingGlobalLineType - */ - public LineType getCorrespondingGlobalLineType() { - return correspondingGlobalLineType; - } + /** + * Default constructor. + * + * @param gpmlString + * {@link #gpmlString} + * @param globalLineType + * {@link #correspondingGlobalLineType} + */ + GpmlLineType(String gpmlString, LineType globalLineType) { + this.gpmlString = gpmlString; + this.correspondingGlobalLineType = globalLineType; + } - /** - * Returns {@link GpmlLineType type} identified by {@link #gpmlName gpml - * string} identifing the type. - * - * @param gpmlName - * {@link #gpmlString} - * @return {@link GpmlLineType type} identified by {@link #gpmlName gpml - * string} identifing the type - * @throws UnknownTypeException - * thrown when type cannot be found - */ - public static GpmlLineType getByGpmlName(String gpmlName) throws UnknownTypeException { - for (GpmlLineType type : values()) { - if (type.getGpmlString() == null) { - if (gpmlName == null) { - return type; - } - } else if (type.getGpmlString().equals(gpmlName)) { - return type; - } - } - throw new UnknownTypeException("Unknown line type: " + gpmlName); - } + /** + * Returns {@link GpmlLineType type} identified by {@link #gpmlName gpml string} + * identifing the type. + * + * @param gpmlName + * {@link #gpmlString} + * @return {@link GpmlLineType type} identified by {@link #gpmlName gpml string} + * identifing the type + * @throws UnknownTypeException + * thrown when type cannot be found + */ + public static GpmlLineType getByGpmlName(String gpmlName) throws UnknownTypeException { + for (GpmlLineType type : values()) { + if (type.getGpmlString() == null) { + if (gpmlName == null) { + return type; + } + } else if (type.getGpmlString().equals(gpmlName)) { + return type; + } + } + throw new UnknownTypeException("Unknown line type: " + gpmlName); + } + + /** + * @return the gpmlString + * @see #gpmlString + */ + public String getGpmlString() { + return gpmlString; + } + + /** + * @return the correspondingGlobalLineType + * @see #correspondingGlobalLineType + */ + public LineType getCorrespondingGlobalLineType() { + return correspondingGlobalLineType; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlModificationType.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlModificationType.java index 79370f35ab..a0879d2eb7 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlModificationType.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlModificationType.java @@ -10,127 +10,126 @@ import lcsb.mapviewer.model.map.species.field.ModificationState; */ public enum GpmlModificationType { - /** - * Gpml type representing: {@link ModificationState#PHOSPHORYLATED}. - */ - PHOSPHORYLATED("P", ModificationState.PHOSPHORYLATED), - - /** - * Gpml type representing: {@link ModificationState#ACETYLATED}. - */ - ACETYLATED("Ac", ModificationState.ACETYLATED), - - /** - * Gpml type representing: {@link ModificationState#UBIQUITINATED}. - */ - UBIQUITINATED("Ub", ModificationState.UBIQUITINATED), - - /** - * Gpml type representing: {@link ModificationState#METHYLATED}. - */ - METHYLATED("Me", ModificationState.METHYLATED), - - /** - * Gpml type representing: {@link ModificationState#HYDROXYLATED}. - */ - HYDROXYLATED("OH", ModificationState.HYDROXYLATED), - - /** - * Gpml type representing: {@link ModificationState#MYRISTOYLATED}. - */ - MYRISTOYLATED("My", ModificationState.MYRISTOYLATED), - - /** - * Gpml type representing: {@link ModificationState#SULFATED}. - */ - SULFATED("S", ModificationState.SULFATED), - - /** - * Gpml type representing: {@link ModificationState#PRENYLATED}. - */ - PRENYLATED("Pr", ModificationState.PRENYLATED), - - /** - * Gpml type representing: {@link ModificationState#GLYCOSYLATED}. - */ - GLYCOSYLATED("G", ModificationState.GLYCOSYLATED), - - /** - * Gpml type representing: {@link ModificationState#PALMYTOYLATED}. - */ - PALMYTOYLATED("Pa", ModificationState.PALMYTOYLATED), - - /** - * Gpml type representing: {@link ModificationState#UNKNOWN}. - */ - UNKOWN("", ModificationState.UNKNOWN), - - /** - * Gpml type representing: {@link ModificationState#PROTONATED}. - */ - PROTONATED("H", ModificationState.PROTONATED); - - /** - * Default constructor. - * - * @param gpmlString - * {@link #gpmlString} - * @param correspondingModificationState - * {@link #correspondingModificationState} - */ - GpmlModificationType(String gpmlString, ModificationState correspondingModificationState) { - this.gpmlString = gpmlString; - this.correspondingModificationState = correspondingModificationState; - } - - /** - * String in GPML format representig this type. - */ - private String gpmlString; - - /** - * Which {@link ModificationState} in our model should be used for this GPML - * modification type. - */ - private ModificationState correspondingModificationState; - - /** - * @return the gpmlString - * @see #gpmlString - */ - public String getGpmlString() { - return gpmlString; - } - - /** - * Returns {@link GpmlModificationType type} identified by {@link #gpmlName - * gpml string} identifing the type. - * - * @param gpmlName - * {@link #gpmlString} - * @return {@link GpmlModificationType type} identified by {@link #gpmlName - * gpml string} identifing the type - * @throws UnknownTypeException - * thrown when type cannot be found - */ - public static GpmlModificationType getByGpmlName(String gpmlName) throws UnknownTypeException { - for (GpmlModificationType type : values()) { - if (type.getGpmlString() == null) { - if (gpmlName == null) { - return type; - } - } else if (type.getGpmlString().equalsIgnoreCase(gpmlName)) { - return type; - } - } - throw new UnknownTypeException("Unknown state type: " + gpmlName); - } - - /** - * @return the correspondingModificationState - * @see #correspondingModificationState - */ - public ModificationState getCorrespondingModificationState() { - return correspondingModificationState; - } + /** + * Gpml type representing: {@link ModificationState#PHOSPHORYLATED}. + */ + PHOSPHORYLATED("P", ModificationState.PHOSPHORYLATED), + + /** + * Gpml type representing: {@link ModificationState#ACETYLATED}. + */ + ACETYLATED("Ac", ModificationState.ACETYLATED), + + /** + * Gpml type representing: {@link ModificationState#UBIQUITINATED}. + */ + UBIQUITINATED("Ub", ModificationState.UBIQUITINATED), + + /** + * Gpml type representing: {@link ModificationState#METHYLATED}. + */ + METHYLATED("Me", ModificationState.METHYLATED), + + /** + * Gpml type representing: {@link ModificationState#HYDROXYLATED}. + */ + HYDROXYLATED("OH", ModificationState.HYDROXYLATED), + + /** + * Gpml type representing: {@link ModificationState#MYRISTOYLATED}. + */ + MYRISTOYLATED("My", ModificationState.MYRISTOYLATED), + + /** + * Gpml type representing: {@link ModificationState#SULFATED}. + */ + SULFATED("S", ModificationState.SULFATED), + + /** + * Gpml type representing: {@link ModificationState#PRENYLATED}. + */ + PRENYLATED("Pr", ModificationState.PRENYLATED), + + /** + * Gpml type representing: {@link ModificationState#GLYCOSYLATED}. + */ + GLYCOSYLATED("G", ModificationState.GLYCOSYLATED), + + /** + * Gpml type representing: {@link ModificationState#PALMYTOYLATED}. + */ + PALMYTOYLATED("Pa", ModificationState.PALMYTOYLATED), + + /** + * Gpml type representing: {@link ModificationState#UNKNOWN}. + */ + UNKOWN("", ModificationState.UNKNOWN), + + /** + * Gpml type representing: {@link ModificationState#PROTONATED}. + */ + PROTONATED("H", ModificationState.PROTONATED); + + /** + * String in GPML format representig this type. + */ + private String gpmlString; + /** + * Which {@link ModificationState} in our model should be used for this GPML + * modification type. + */ + private ModificationState correspondingModificationState; + + /** + * Default constructor. + * + * @param gpmlString + * {@link #gpmlString} + * @param correspondingModificationState + * {@link #correspondingModificationState} + */ + GpmlModificationType(String gpmlString, ModificationState correspondingModificationState) { + this.gpmlString = gpmlString; + this.correspondingModificationState = correspondingModificationState; + } + + /** + * Returns {@link GpmlModificationType type} identified by {@link #gpmlName gpml + * string} identifing the type. + * + * @param gpmlName + * {@link #gpmlString} + * @return {@link GpmlModificationType type} identified by {@link #gpmlName gpml + * string} identifing the type + * @throws UnknownTypeException + * thrown when type cannot be found + */ + public static GpmlModificationType getByGpmlName(String gpmlName) throws UnknownTypeException { + for (GpmlModificationType type : values()) { + if (type.getGpmlString() == null) { + if (gpmlName == null) { + return type; + } + } else if (type.getGpmlString().equalsIgnoreCase(gpmlName)) { + return type; + } + } + throw new UnknownTypeException("Unknown state type: " + gpmlName); + } + + /** + * @return the gpmlString + * @see #gpmlString + */ + public String getGpmlString() { + return gpmlString; + } + + /** + * @return the correspondingModificationState + * @see #correspondingModificationState + */ + public ModificationState getCorrespondingModificationState() { + return correspondingModificationState; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlStateType.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlStateType.java index feccb7c7fc..f7a72157c4 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlStateType.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GpmlStateType.java @@ -8,80 +8,79 @@ package lcsb.mapviewer.wikipathway.model; */ public enum GpmlStateType { - /** - * Gpml type representing "GTP" - * {@link lcsb.mapviewer.model.map.species.Protein#structuralState state of - * Protein}. - */ - GTP("GTP", "GTP"), + /** + * Gpml type representing "GTP" + * {@link lcsb.mapviewer.model.map.species.Protein#structuralState state of + * Protein}. + */ + GTP("GTP", "GTP"), - /** - * Gpml type representing "GDP" - * {@link lcsb.mapviewer.model.map.species.Protein#structuralState state of - * Protein}. - */ - GDP("GDP", "GDP"); + /** + * Gpml type representing "GDP" + * {@link lcsb.mapviewer.model.map.species.Protein#structuralState state of + * Protein}. + */ + GDP("GDP", "GDP"); - /** - * Default constructor. - * - * @param gpmlString - * {@link #gpmlString} - * @param stringRepresenation - * {@link #stringRepresenation} - */ - GpmlStateType(String gpmlString, String stringRepresenation) { - this.gpmlString = gpmlString; - this.stringRepresenation = stringRepresenation; - } + /** + * String in GPML format representig this type. + */ + private String gpmlString; + /** + * String that should be used in our representation. + */ + private String stringRepresenation; - /** - * String in GPML format representig this type. - */ - private String gpmlString; + /** + * Default constructor. + * + * @param gpmlString + * {@link #gpmlString} + * @param stringRepresenation + * {@link #stringRepresenation} + */ + GpmlStateType(String gpmlString, String stringRepresenation) { + this.gpmlString = gpmlString; + this.stringRepresenation = stringRepresenation; + } - /** - * String that should be used in our representation. - */ - private String stringRepresenation; + /** + * Returns {@link GpmlStateType type} identified by {@link #gpmlName gpml + * string} identifing the type. + * + * @param gpmlName + * {@link #gpmlString} + * @return {@link GpmlStateType type} identified by {@link #gpmlName gpml + * string} identifing the type + * @throws UnknownTypeException + * thrown when type cannot be found + */ + public static GpmlStateType getByGpmlName(String gpmlName) throws UnknownTypeException { + for (GpmlStateType type : values()) { + if (type.getGpmlString() == null) { + if (gpmlName == null) { + return type; + } + } else if (type.getGpmlString().equalsIgnoreCase(gpmlName)) { + return type; + } + } + throw new UnknownTypeException("Unknown state type: " + gpmlName); + } - /** - * @return the gpmlString - * @see #gpmlString - */ - public String getGpmlString() { - return gpmlString; - } + /** + * @return the gpmlString + * @see #gpmlString + */ + public String getGpmlString() { + return gpmlString; + } - /** - * Returns {@link GpmlStateType type} identified by {@link #gpmlName gpml - * string} identifing the type. - * - * @param gpmlName - * {@link #gpmlString} - * @return {@link GpmlStateType type} identified by {@link #gpmlName gpml - * string} identifing the type - * @throws UnknownTypeException - * thrown when type cannot be found - */ - public static GpmlStateType getByGpmlName(String gpmlName) throws UnknownTypeException { - for (GpmlStateType type : values()) { - if (type.getGpmlString() == null) { - if (gpmlName == null) { - return type; - } - } else if (type.getGpmlString().equalsIgnoreCase(gpmlName)) { - return type; - } - } - throw new UnknownTypeException("Unknown state type: " + gpmlName); - } - - /** - * @return the stringRepresenation - * @see #stringRepresenation - */ - public String getStringRepresenation() { - return stringRepresenation; - } + /** + * @return the stringRepresenation + * @see #stringRepresenation + */ + public String getStringRepresenation() { + return stringRepresenation; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Graph.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Graph.java index e967340cf5..e789c9debc 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Graph.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Graph.java @@ -1,17 +1,14 @@ package lcsb.mapviewer.wikipathway.model; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.wikipathway.model.biopax.BiopaxData; -import org.apache.logging.log4j.*; - /** * This class models nodes and reaction from PathVisio for easy(?) conversion to * Model. @@ -21,563 +18,562 @@ import org.apache.logging.log4j.*; */ public class Graph implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default width of the graphic model. - */ - private static final double DEFAULT_MODEL_WIDTH = 1024.0; - - /** - * Default height of the graphic model. - */ - private static final double DEFAULT_MODEL_HEIGHT = 1024.0; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(Graph.class); - - /** - * Height of the model. - */ - private double boardHeight; - - /** - * Information about biopax data in the gpml file. - */ - private BiopaxData biopaxData; - - /** - * Width of the model. - */ - private double boardWidth; - - /** - * All {@link PathwayElement nodes} in the model identified by the - * {@link PathwayElement#graphId}. - */ - private Map<String, PathwayElement> nodes; - - /** - * All {@link Group groups} in the model identified by the - * {@link PathwayElement#graphId}. - */ - private Map<String, Group> groupsByGraphId; - - /** - * All {@link Group groups} in the model identified by the - * {@link Group#groupId}. - */ - private Map<String, Group> groupsByGroupId; - - /** - * All {@link DataNode data nodes} in the model identified by the - * {@link PathwayElement#graphId}. - */ - private Map<String, DataNode> dataNodes; - - /** - * All {@link Label labvels} in the model identified by the - * {@link PathwayElement#graphId}. - */ - private Map<String, Label> labels; - - /** - * All {@link Shape shapes} in the model identified by the - * {@link PathwayElement#graphId}. - */ - private Map<String, Shape> shapes; - - /** - * All {@link Edge edges} in the model identified by the {@link Edge#graphId}. - */ - private Map<String, Edge> edges; - - /** - * {@link Edge Edges} in the model identified by anchors . - */ - private Map<String, Edge> anchorToEdge; - - /** - * All {@link Interaction interactions} in the model identified by the - * {@link Interaction#graphId}. - */ - private Map<String, Interaction> interactions; - - /** - * Comments on the model. - */ - private List<String> comments = new ArrayList<>(); - - /** - * Pathvisio attributes of the model. - */ - private Map<String, String> attributes = new HashMap<String, String>(); - - /** - * List of identifiers used by biopax nodes that are inside gpml. These biopax - * nodes contain annotations. - */ - private List<String> biopaxReferences = new ArrayList<String>(); - - /** - * List of lines in gpml model. - */ - private List<PolylineData> lines = new ArrayList<PolylineData>(); - - /** - * List of states in gpml model. - */ - private List<State> states = new ArrayList<State>(); - - /** - * Default constructor. - */ - public Graph() { - boardHeight = DEFAULT_MODEL_HEIGHT; - boardWidth = DEFAULT_MODEL_WIDTH; - nodes = new HashMap<String, PathwayElement>(); - groupsByGraphId = new HashMap<String, Group>(); - groupsByGroupId = new HashMap<String, Group>(); - dataNodes = new HashMap<String, DataNode>(); - labels = new HashMap<String, Label>(); - shapes = new HashMap<String, Shape>(); - edges = new HashMap<String, Edge>(); - anchorToEdge = new HashMap<String, Edge>(); - interactions = new HashMap<String, Interaction>(); - } - - /** - * Adds {@link Group} to model. - * - * @param group - * object to add - */ - public void addGroup(Group group) { - groupsByGraphId.put(group.getGraphId(), group); - groupsByGroupId.put(group.getGroupId(), group); - nodes.put(group.getGraphId(), group); - } - - /** - * Adds {@link DataNode} to model. - * - * @param node - * object to add - */ - public void addDataNode(DataNode node) { - dataNodes.put(node.getGraphId(), node); - nodes.put(node.getGraphId(), node); - if (node.getGroupRef() != null && !node.getGroupRef().equals("")) { - groupsByGroupId.get(node.getGroupRef()).addNode(node); - } - } - - /** - * Adds {@link Label} to model. - * - * @param label - * object to add - */ - public void addLabel(Label label) { - labels.put(label.getGraphId(), label); - nodes.put(label.getGraphId(), label); - if (label.getGroupRef() != null && !label.getGroupRef().equals("")) { - groupsByGroupId.get(label.getGroupRef()).addNode(label); - } - } - - /** - * Adds {@link Shape} to model. - * - * @param shape - * object to add - */ - public void addShape(Shape shape) { - shapes.put(shape.getGraphId(), shape); - nodes.put(shape.getGraphId(), shape); - if (shape.getGroupRef() != null && !shape.getGroupRef().equals("")) { - groupsByGroupId.get(shape.getGroupRef()).addNode(shape); - } - } - - /** - * Adds {@link Edge} to model. - * - * @param edge - * object to add - */ - public void addEdge(Edge edge) { - edges.put(edge.getGraphId(), edge); - for (String anchor : edge.getAnchors()) { - anchorToEdge.put(anchor, edge); - } - } - - /** - * Adds {@link Interaction} to model. - * - * @param interaction - * object to add - */ - public void addInteraction(Interaction interaction) { - interactions.put(interaction.getGraphId(), interaction); - } - - /** - * Returns {@link PathwayElement} identified by {@link PathwayElement#graphId} - * . - * - * @param graphId - * identifier - * @return {@link PathwayElement} identified by {@link PathwayElement#graphId} - */ - public PathwayElement getNodeByGraphId(String graphId) { - return nodes.get(graphId); - } - - /** - * Returns collection of {@link Group groups} in the model. - * - * @return collection of {@link Group groups} in the model - */ - public Collection<Group> getGroups() { - return groupsByGraphId.values(); - } - - /** - * Returns {@link Group} identified by {@link Group#groupId}. - * - * @param groupId - * identifier - * @return {@link Group} identified by {@link Group#groupId} - */ - public Group getGroupByGroupId(String groupId) { - return groupsByGroupId.get(groupId); - } - - /** - * Returns set of {@link DataNode data nodes} in model. - * - * @return set of {@link DataNode data nodes} in model - */ - public Collection<DataNode> getDataNodes() { - return dataNodes.values(); - } - - /** - * Returns set of {@link Label labels} in model. - * - * @return set of {@link Label labels} in model. - */ - public Collection<Label> getLabels() { - return labels.values(); - } - - /** - * Returns {@link Label} identified by {@link PathwayElement#graphId}. - * - * @param graphId - * identifier - * @return {@link Label} identified by {@link PathwayElement#graphId}. - */ - public Label getLabelByGraphId(String graphId) { - return labels.get(graphId); - } - - /** - * Returns set of {@link Shape shapes} in the model. - * - * @return set of {@link Shape shapes} in the model. - */ - public Collection<Shape> getShapes() { - return shapes.values(); - } - - /** - * Returns {@link Shape} identified by {@link PathwayElement#graphId}. - * - * @param graphId - * identifier - * @return {@link Shape} identified by {@link PathwayElement#graphId} - */ - public Shape getShapeByGraphId(String graphId) { - return shapes.get(graphId); - } - - /** - * Returns set of {@link Edge edges} in the model. - * - * @return set of {@link Edge edges} in the model - */ - public Collection<Edge> getEdges() { - return edges.values(); - } - - /** - * Return {@link Edge} pointed by the anchor. - * - * @param anchor - * anchor string identifier - * @return {@link Edge} pointed by the anchor - */ - public Edge getEdgeByAnchor(String anchor) { - return anchorToEdge.get(anchor); - } - - /** - * Returns set of {@link Interaction interactions} in the model. - * - * @return set of {@link Interaction interactions} in the model - */ - public Collection<Interaction> getInteractions() { - return interactions.values(); - } - - /** - * Returns {@link Interaction} identified by {@link Interaction#graphId}. - * - * @param graphId - * identifier - * @return {@link Interaction} identified by {@link Interaction#graphId} - */ - public Interaction getInteractionByGraphId(String graphId) { - return interactions.get(graphId); - } - - /** - * @return the boardHeight - * @see #boardHeight - */ - public double getBoardHeight() { - return boardHeight; - } - - /** - * @param boardHeight - * the boardHeight to set - * @see #boardHeight - */ - public void setBoardHeight(double boardHeight) { - this.boardHeight = boardHeight; - } - - /** - * @return the boardWidth - * @see #boardWidth - */ - public double getBoardWidth() { - return boardWidth; - } - - /** - * @param boardWidth - * the boardWidth to set - * @see #boardWidth - */ - public void setBoardWidth(double boardWidth) { - this.boardWidth = boardWidth; - } - - /** - * @return the comments - * @see #comments - */ - public List<String> getComments() { - return comments; - } - - /** - * @param comment - * the comment to add - * @see #comments - */ - public void addComment(String comment) { - this.comments.add(comment); - } - - /** - * @return the biopaxData - * @see #biopaxData - */ - public BiopaxData getBiopaxData() { - return biopaxData; - } - - /** - * @param biopaxData - * the biopaxData to set - * @see #biopaxData - */ - public void setBiopaxData(BiopaxData biopaxData) { - this.biopaxData = biopaxData; - } - - /** - * @return the attributesMap - * @see #attributes - */ - public Map<String, String> getAttributes() { - return attributes; - } - - /** - * @param attributesMap - * the attributesMap to set - * @see #attributes - */ - public void setAttributes(Map<String, String> attributesMap) { - this.attributes = attributesMap; - } - - /** - * @return the biopaxReferences - * @see #biopaxReferences - */ - public List<String> getBiopaxReferences() { - return biopaxReferences; - } - - /** - * @param biopaxReference - * the biopaxReference to add - * @see #biopaxReferences - */ - public void addBiopaxReferences(String biopaxReference) { - this.biopaxReferences.add(biopaxReference); - } - - /** - * @return the lines - * @see #lines - */ - public List<PolylineData> getLines() { - return lines; - } - - /** - * @param line - * the line to add - * @see #lines - */ - public void addLine(PolylineData line) { - this.lines.add(line); - } - - /** - * @param lines - * the lines to add - * @see #lines - */ - public void addLines(Collection<PolylineData> lines) { - this.lines.addAll(lines); - } - - /** - * Adds edges to the model. - * - * @param parseEdgesFromLines - * set of edges to add - */ - public void addEdges(Collection<Edge> parseEdgesFromLines) { - for (Edge edge : parseEdgesFromLines) { - addEdge(edge); - } - } - - /** - * Removes edge from the model. - * - * @param edge - * object to remove - */ - public void removeEdge(Edge edge) { - edges.remove(edge.getGraphId(), edge); - for (String anchor : edge.getAnchors()) { - anchorToEdge.remove(anchor, edge); - } - } - - /** - * Adds {@link DataNode data nodes} to the graph. - * - * @param nodes - * object to add - */ - public void addDataNodes(List<DataNode> nodes) { - for (DataNode dataNode : nodes) { - addDataNode(dataNode); - } - } - - /** - * Adds {@link Label labels} to the graph. - * - * @param nodes - * object to add - */ - public void addLabels(List<Label> nodes) { - for (Label label : nodes) { - addLabel(label); - } - - } - - /** - * Adds {@link Shape shapes} to the graph. - * - * @param nodes - * object to add - */ - public void addShapes(List<Shape> nodes) { - for (Shape shape : nodes) { - addShape(shape); - } - } - - /** - * Adds {@link State states} to the graph. - * - * @param parseCollection - * collections of objects to add - */ - public void addStates(List<State> parseCollection) { - for (State state : parseCollection) { - addState(state); - } - - } - - /** - * Adds {@link State} to the graph. - * - * @param state - * object to add - */ - private void addState(State state) { - this.states.add(state); - } - - /** - * @return the states - * @see #states - */ - public List<State> getStates() { - return states; - } - - /** - * @param states - * the states to set - * @see #states - */ - public void setStates(List<State> states) { - this.states = states; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default width of the graphic model. + */ + private static final double DEFAULT_MODEL_WIDTH = 1024.0; + + /** + * Default height of the graphic model. + */ + private static final double DEFAULT_MODEL_HEIGHT = 1024.0; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(Graph.class); + + /** + * Height of the model. + */ + private double boardHeight; + + /** + * Information about biopax data in the gpml file. + */ + private BiopaxData biopaxData; + + /** + * Width of the model. + */ + private double boardWidth; + + /** + * All {@link PathwayElement nodes} in the model identified by the + * {@link PathwayElement#graphId}. + */ + private Map<String, PathwayElement> nodes; + + /** + * All {@link Group groups} in the model identified by the + * {@link PathwayElement#graphId}. + */ + private Map<String, Group> groupsByGraphId; + + /** + * All {@link Group groups} in the model identified by the + * {@link Group#groupId}. + */ + private Map<String, Group> groupsByGroupId; + + /** + * All {@link DataNode data nodes} in the model identified by the + * {@link PathwayElement#graphId}. + */ + private Map<String, DataNode> dataNodes; + + /** + * All {@link Label labvels} in the model identified by the + * {@link PathwayElement#graphId}. + */ + private Map<String, Label> labels; + + /** + * All {@link Shape shapes} in the model identified by the + * {@link PathwayElement#graphId}. + */ + private Map<String, Shape> shapes; + + /** + * All {@link Edge edges} in the model identified by the {@link Edge#graphId}. + */ + private Map<String, Edge> edges; + + /** + * {@link Edge Edges} in the model identified by anchors . + */ + private Map<String, Edge> anchorToEdge; + + /** + * All {@link Interaction interactions} in the model identified by the + * {@link Interaction#graphId}. + */ + private Map<String, Interaction> interactions; + + /** + * Comments on the model. + */ + private List<String> comments = new ArrayList<>(); + + /** + * Pathvisio attributes of the model. + */ + private Map<String, String> attributes = new HashMap<String, String>(); + + /** + * List of identifiers used by biopax nodes that are inside gpml. These biopax + * nodes contain annotations. + */ + private List<String> biopaxReferences = new ArrayList<String>(); + + /** + * List of lines in gpml model. + */ + private List<PolylineData> lines = new ArrayList<PolylineData>(); + + /** + * List of states in gpml model. + */ + private List<State> states = new ArrayList<State>(); + + /** + * Default constructor. + */ + public Graph() { + boardHeight = DEFAULT_MODEL_HEIGHT; + boardWidth = DEFAULT_MODEL_WIDTH; + nodes = new HashMap<String, PathwayElement>(); + groupsByGraphId = new HashMap<String, Group>(); + groupsByGroupId = new HashMap<String, Group>(); + dataNodes = new HashMap<String, DataNode>(); + labels = new HashMap<String, Label>(); + shapes = new HashMap<String, Shape>(); + edges = new HashMap<String, Edge>(); + anchorToEdge = new HashMap<String, Edge>(); + interactions = new HashMap<String, Interaction>(); + } + + /** + * Adds {@link Group} to model. + * + * @param group + * object to add + */ + public void addGroup(Group group) { + groupsByGraphId.put(group.getGraphId(), group); + groupsByGroupId.put(group.getGroupId(), group); + nodes.put(group.getGraphId(), group); + } + + /** + * Adds {@link DataNode} to model. + * + * @param node + * object to add + */ + public void addDataNode(DataNode node) { + dataNodes.put(node.getGraphId(), node); + nodes.put(node.getGraphId(), node); + if (node.getGroupRef() != null && !node.getGroupRef().equals("")) { + groupsByGroupId.get(node.getGroupRef()).addNode(node); + } + } + + /** + * Adds {@link Label} to model. + * + * @param label + * object to add + */ + public void addLabel(Label label) { + labels.put(label.getGraphId(), label); + nodes.put(label.getGraphId(), label); + if (label.getGroupRef() != null && !label.getGroupRef().equals("")) { + groupsByGroupId.get(label.getGroupRef()).addNode(label); + } + } + + /** + * Adds {@link Shape} to model. + * + * @param shape + * object to add + */ + public void addShape(Shape shape) { + shapes.put(shape.getGraphId(), shape); + nodes.put(shape.getGraphId(), shape); + if (shape.getGroupRef() != null && !shape.getGroupRef().equals("")) { + groupsByGroupId.get(shape.getGroupRef()).addNode(shape); + } + } + + /** + * Adds {@link Edge} to model. + * + * @param edge + * object to add + */ + public void addEdge(Edge edge) { + edges.put(edge.getGraphId(), edge); + for (String anchor : edge.getAnchors()) { + anchorToEdge.put(anchor, edge); + } + } + + /** + * Adds {@link Interaction} to model. + * + * @param interaction + * object to add + */ + public void addInteraction(Interaction interaction) { + interactions.put(interaction.getGraphId(), interaction); + } + + /** + * Returns {@link PathwayElement} identified by {@link PathwayElement#graphId} . + * + * @param graphId + * identifier + * @return {@link PathwayElement} identified by {@link PathwayElement#graphId} + */ + public PathwayElement getNodeByGraphId(String graphId) { + return nodes.get(graphId); + } + + /** + * Returns collection of {@link Group groups} in the model. + * + * @return collection of {@link Group groups} in the model + */ + public Collection<Group> getGroups() { + return groupsByGraphId.values(); + } + + /** + * Returns {@link Group} identified by {@link Group#groupId}. + * + * @param groupId + * identifier + * @return {@link Group} identified by {@link Group#groupId} + */ + public Group getGroupByGroupId(String groupId) { + return groupsByGroupId.get(groupId); + } + + /** + * Returns set of {@link DataNode data nodes} in model. + * + * @return set of {@link DataNode data nodes} in model + */ + public Collection<DataNode> getDataNodes() { + return dataNodes.values(); + } + + /** + * Returns set of {@link Label labels} in model. + * + * @return set of {@link Label labels} in model. + */ + public Collection<Label> getLabels() { + return labels.values(); + } + + /** + * Returns {@link Label} identified by {@link PathwayElement#graphId}. + * + * @param graphId + * identifier + * @return {@link Label} identified by {@link PathwayElement#graphId}. + */ + public Label getLabelByGraphId(String graphId) { + return labels.get(graphId); + } + + /** + * Returns set of {@link Shape shapes} in the model. + * + * @return set of {@link Shape shapes} in the model. + */ + public Collection<Shape> getShapes() { + return shapes.values(); + } + + /** + * Returns {@link Shape} identified by {@link PathwayElement#graphId}. + * + * @param graphId + * identifier + * @return {@link Shape} identified by {@link PathwayElement#graphId} + */ + public Shape getShapeByGraphId(String graphId) { + return shapes.get(graphId); + } + + /** + * Returns set of {@link Edge edges} in the model. + * + * @return set of {@link Edge edges} in the model + */ + public Collection<Edge> getEdges() { + return edges.values(); + } + + /** + * Return {@link Edge} pointed by the anchor. + * + * @param anchor + * anchor string identifier + * @return {@link Edge} pointed by the anchor + */ + public Edge getEdgeByAnchor(String anchor) { + return anchorToEdge.get(anchor); + } + + /** + * Returns set of {@link Interaction interactions} in the model. + * + * @return set of {@link Interaction interactions} in the model + */ + public Collection<Interaction> getInteractions() { + return interactions.values(); + } + + /** + * Returns {@link Interaction} identified by {@link Interaction#graphId}. + * + * @param graphId + * identifier + * @return {@link Interaction} identified by {@link Interaction#graphId} + */ + public Interaction getInteractionByGraphId(String graphId) { + return interactions.get(graphId); + } + + /** + * @return the boardHeight + * @see #boardHeight + */ + public double getBoardHeight() { + return boardHeight; + } + + /** + * @param boardHeight + * the boardHeight to set + * @see #boardHeight + */ + public void setBoardHeight(double boardHeight) { + this.boardHeight = boardHeight; + } + + /** + * @return the boardWidth + * @see #boardWidth + */ + public double getBoardWidth() { + return boardWidth; + } + + /** + * @param boardWidth + * the boardWidth to set + * @see #boardWidth + */ + public void setBoardWidth(double boardWidth) { + this.boardWidth = boardWidth; + } + + /** + * @return the comments + * @see #comments + */ + public List<String> getComments() { + return comments; + } + + /** + * @param comment + * the comment to add + * @see #comments + */ + public void addComment(String comment) { + this.comments.add(comment); + } + + /** + * @return the biopaxData + * @see #biopaxData + */ + public BiopaxData getBiopaxData() { + return biopaxData; + } + + /** + * @param biopaxData + * the biopaxData to set + * @see #biopaxData + */ + public void setBiopaxData(BiopaxData biopaxData) { + this.biopaxData = biopaxData; + } + + /** + * @return the attributesMap + * @see #attributes + */ + public Map<String, String> getAttributes() { + return attributes; + } + + /** + * @param attributesMap + * the attributesMap to set + * @see #attributes + */ + public void setAttributes(Map<String, String> attributesMap) { + this.attributes = attributesMap; + } + + /** + * @return the biopaxReferences + * @see #biopaxReferences + */ + public List<String> getBiopaxReferences() { + return biopaxReferences; + } + + /** + * @param biopaxReference + * the biopaxReference to add + * @see #biopaxReferences + */ + public void addBiopaxReferences(String biopaxReference) { + this.biopaxReferences.add(biopaxReference); + } + + /** + * @return the lines + * @see #lines + */ + public List<PolylineData> getLines() { + return lines; + } + + /** + * @param line + * the line to add + * @see #lines + */ + public void addLine(PolylineData line) { + this.lines.add(line); + } + + /** + * @param lines + * the lines to add + * @see #lines + */ + public void addLines(Collection<PolylineData> lines) { + this.lines.addAll(lines); + } + + /** + * Adds edges to the model. + * + * @param parseEdgesFromLines + * set of edges to add + */ + public void addEdges(Collection<Edge> parseEdgesFromLines) { + for (Edge edge : parseEdgesFromLines) { + addEdge(edge); + } + } + + /** + * Removes edge from the model. + * + * @param edge + * object to remove + */ + public void removeEdge(Edge edge) { + edges.remove(edge.getGraphId(), edge); + for (String anchor : edge.getAnchors()) { + anchorToEdge.remove(anchor, edge); + } + } + + /** + * Adds {@link DataNode data nodes} to the graph. + * + * @param nodes + * object to add + */ + public void addDataNodes(List<DataNode> nodes) { + for (DataNode dataNode : nodes) { + addDataNode(dataNode); + } + } + + /** + * Adds {@link Label labels} to the graph. + * + * @param nodes + * object to add + */ + public void addLabels(List<Label> nodes) { + for (Label label : nodes) { + addLabel(label); + } + + } + + /** + * Adds {@link Shape shapes} to the graph. + * + * @param nodes + * object to add + */ + public void addShapes(List<Shape> nodes) { + for (Shape shape : nodes) { + addShape(shape); + } + } + + /** + * Adds {@link State states} to the graph. + * + * @param parseCollection + * collections of objects to add + */ + public void addStates(List<State> parseCollection) { + for (State state : parseCollection) { + addState(state); + } + + } + + /** + * Adds {@link State} to the graph. + * + * @param state + * object to add + */ + private void addState(State state) { + this.states.add(state); + } + + /** + * @return the states + * @see #states + */ + public List<State> getStates() { + return states; + } + + /** + * @param states + * the states to set + * @see #states + */ + public void setStates(List<State> states) { + this.states = states; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GraphicalPathwayElement.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GraphicalPathwayElement.java index a16f5337f1..2bb2c2bd46 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GraphicalPathwayElement.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/GraphicalPathwayElement.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.wikipathway.model; -import java.awt.Color; +import java.awt.*; import java.awt.font.TextAttribute; import java.awt.geom.Rectangle2D; import java.util.HashMap; @@ -18,236 +18,237 @@ import lcsb.mapviewer.model.graphics.LineType; */ public abstract class GraphicalPathwayElement extends PathwayElement { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Color. - */ - private Color color = Color.BLACK; - - /** - * Fill color. - */ - private Color fillColor = Color.WHITE; - - /** - * Name of the font used in drawing. - */ - private String fontName; - - /** - * Font size used for description. - */ - private Double fontSize; - - /** - * Rectangle border of the element. - */ - private Rectangle2D rectangle; - - /** - * {@link TextAttribute Font attributes}. - */ - private Map<TextAttribute, Object> fontAttributes = new HashMap<>(); - - /** - * {@link TextAttribute Font attributes}. - */ - private TextAlignment textAlignment = TextAlignment.LEFT; - - /** - * Thickness of the line used to draw element. - */ - private Double lineThickness = 1.0; - - /** - * Type of line used to draw the element. - */ - private LineType lineType = LineType.SOLID; - - /** - * Default constructor. - */ - public GraphicalPathwayElement() { - super(); - } - - /** - * Default constructor. - * - * @param graphId - * {@link PathwayElement#graphId} - */ - public GraphicalPathwayElement(String graphId) { - super(graphId); - } - - /** - * @return the fontAttributes - * @see #fontAttributes - */ - public Map<TextAttribute, Object> getFontAttributes() { - return fontAttributes; - } - - /** - * @param fontAttributes - * the fontAttributes to set - * @see #fontAttributes - */ - public void setFontAttributes(Map<TextAttribute, Object> fontAttributes) { - this.fontAttributes = fontAttributes; - } - - /** - * Adds font attribute. - * - * @param key - * type of the attribute - * @param value - * value of the attribute - */ - public void addFontAttribute(TextAttribute key, Object value) { - fontAttributes.put(key, value); - } - - /** - * @return the textAlignment - * @see #textAlignment - */ - public TextAlignment getTextAlignment() { - return textAlignment; - } - - /** - * @param textAlignment - * the textAlignment to set - * @see #textAlignment - */ - public void setTextAlignment(TextAlignment textAlignment) { - this.textAlignment = textAlignment; - } - - /** - * @return the fontSize - * @see #fontSize - */ - public Double getFontSize() { - return fontSize; - } - - /** - * @param fontSize - * the fontSize to set - * @see #fontSize - */ - public void setFontSize(Double fontSize) { - this.fontSize = fontSize; - } - - /** - * @return the color - * @see #color - */ - public Color getColor() { - return color; - } - - /** - * @param color - * the color to set - * @see #color - */ - public void setColor(Color color) { - if (color != null) { - this.color = color; - } - } - - /** - * @return the fillColor - * @see #fillColor - */ - public Color getFillColor() { - return fillColor; - } - - /** - * @param fillColor - * the fillColor to set - * @see #fillColor - */ - public void setFillColor(Color fillColor) { - if (fillColor != null) { - this.fillColor = fillColor; - } - } - - /** - * @return the fontName - * @see #fontName - */ - public String getFontName() { - return fontName; - } - - /** - * @param fontName - * the fontName to set - * @see #fontName - */ - public void setFontName(String fontName) { - this.fontName = fontName; - } - - /** - * @return the lineThickness - * @see #lineThickness - */ - public Double getLineThickness() { - return lineThickness; - } - - /** - * @param lineThickness - * the lineThickness to set - * @see #lineThickness - */ - public void setLineThickness(Double lineThickness) { - this.lineThickness = lineThickness; - } - - /** - * @return the lineType - * @see #lineType - */ - public LineType getLineType() { - return lineType; - } - - /** - * @param lineType - * the lineType to set - * @see #lineType - */ - public void setLineType(LineType lineType) { - this.lineType = lineType; - } - - @Override - public Rectangle2D getRectangle() { - return rectangle; - } - - /** - * @param rectangle the rectangle to set - * @see #rectangle - */ - public void setRectangle(Rectangle2D rectangle) { - this.rectangle = rectangle; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Color. + */ + private Color color = Color.BLACK; + + /** + * Fill color. + */ + private Color fillColor = Color.WHITE; + + /** + * Name of the font used in drawing. + */ + private String fontName; + + /** + * Font size used for description. + */ + private Double fontSize; + + /** + * Rectangle border of the element. + */ + private Rectangle2D rectangle; + + /** + * {@link TextAttribute Font attributes}. + */ + private Map<TextAttribute, Object> fontAttributes = new HashMap<>(); + + /** + * {@link TextAttribute Font attributes}. + */ + private TextAlignment textAlignment = TextAlignment.LEFT; + + /** + * Thickness of the line used to draw element. + */ + private Double lineThickness = 1.0; + + /** + * Type of line used to draw the element. + */ + private LineType lineType = LineType.SOLID; + + /** + * Default constructor. + */ + public GraphicalPathwayElement() { + super(); + } + + /** + * Default constructor. + * + * @param graphId + * {@link PathwayElement#graphId} + */ + public GraphicalPathwayElement(String graphId) { + super(graphId); + } + + /** + * @return the fontAttributes + * @see #fontAttributes + */ + public Map<TextAttribute, Object> getFontAttributes() { + return fontAttributes; + } + + /** + * @param fontAttributes + * the fontAttributes to set + * @see #fontAttributes + */ + public void setFontAttributes(Map<TextAttribute, Object> fontAttributes) { + this.fontAttributes = fontAttributes; + } + + /** + * Adds font attribute. + * + * @param key + * type of the attribute + * @param value + * value of the attribute + */ + public void addFontAttribute(TextAttribute key, Object value) { + fontAttributes.put(key, value); + } + + /** + * @return the textAlignment + * @see #textAlignment + */ + public TextAlignment getTextAlignment() { + return textAlignment; + } + + /** + * @param textAlignment + * the textAlignment to set + * @see #textAlignment + */ + public void setTextAlignment(TextAlignment textAlignment) { + this.textAlignment = textAlignment; + } + + /** + * @return the fontSize + * @see #fontSize + */ + public Double getFontSize() { + return fontSize; + } + + /** + * @param fontSize + * the fontSize to set + * @see #fontSize + */ + public void setFontSize(Double fontSize) { + this.fontSize = fontSize; + } + + /** + * @return the color + * @see #color + */ + public Color getColor() { + return color; + } + + /** + * @param color + * the color to set + * @see #color + */ + public void setColor(Color color) { + if (color != null) { + this.color = color; + } + } + + /** + * @return the fillColor + * @see #fillColor + */ + public Color getFillColor() { + return fillColor; + } + + /** + * @param fillColor + * the fillColor to set + * @see #fillColor + */ + public void setFillColor(Color fillColor) { + if (fillColor != null) { + this.fillColor = fillColor; + } + } + + /** + * @return the fontName + * @see #fontName + */ + public String getFontName() { + return fontName; + } + + /** + * @param fontName + * the fontName to set + * @see #fontName + */ + public void setFontName(String fontName) { + this.fontName = fontName; + } + + /** + * @return the lineThickness + * @see #lineThickness + */ + public Double getLineThickness() { + return lineThickness; + } + + /** + * @param lineThickness + * the lineThickness to set + * @see #lineThickness + */ + public void setLineThickness(Double lineThickness) { + this.lineThickness = lineThickness; + } + + /** + * @return the lineType + * @see #lineType + */ + public LineType getLineType() { + return lineType; + } + + /** + * @param lineType + * the lineType to set + * @see #lineType + */ + public void setLineType(LineType lineType) { + this.lineType = lineType; + } + + @Override + public Rectangle2D getRectangle() { + return rectangle; + } + + /** + * @param rectangle + * the rectangle to set + * @see #rectangle + */ + public void setRectangle(Rectangle2D rectangle) { + this.rectangle = rectangle; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Group.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Group.java index 954b92053a..16160000c5 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Group.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Group.java @@ -11,125 +11,127 @@ import java.util.Set; * */ public class Group extends PathwayElement { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Margin used when retrieving rectangle border of the group (result rectangle - * will by wider and higher in every direction by this value). - */ - private static final int RECTANGLE_BORDER_MARGIN = 8; - - /** - * Identifier of the group. - */ - private String groupId; - - /** - * Style of the group. - */ - private String style; - - /** - * Elements in the group. - */ - private Set<PathwayElement> nodes; - - /** - * Default constructor. - * - * @param graphId - * graph identifier in the model - * @param groupId - * {@link #groupId} - */ - public Group(String graphId, String groupId) { - super(graphId); - this.groupId = groupId; - nodes = new HashSet<PathwayElement>(); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected Group() { - } - - @Override - public String getName() { - StringBuilder sb = new StringBuilder(""); - for (PathwayElement n : nodes) { - sb.append(n.getName() + ":"); - } - return sb.toString(); - } - - @Override - public Rectangle2D getRectangle() { - - Rectangle2D result = null; - boolean first = true; - - for (PathwayElement n : nodes) { - if (first) { - result = (Rectangle2D) n.getRectangle().clone(); - first = false; - } - Rectangle2D.union(result, n.getRectangle(), result); - } - if (result == null) { - return null; - } - result.setRect( - result.getX() - RECTANGLE_BORDER_MARGIN, result.getY() - RECTANGLE_BORDER_MARGIN, result.getWidth() + 2 * RECTANGLE_BORDER_MARGIN, result.getHeight() - + 2 * RECTANGLE_BORDER_MARGIN); - return result; - } - - /** - * - * @return {@link #groupId} - */ - public String getGroupId() { - return groupId; - } - - /** - * Adds element to group. - * - * @param pe - * object to add - */ - public void addNode(PathwayElement pe) { - nodes.add(pe); - } - - /** - * - * @return {@link #nodes} - */ - public Set<PathwayElement> getNodes() { - return this.nodes; - } - - /** - * @return the style - * @see #style - */ - public String getStyle() { - return style; - } - - /** - * @param style the style to set - * @see #style - */ - public void setStyle(String style) { - this.style = style; - } + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Margin used when retrieving rectangle border of the group (result rectangle + * will by wider and higher in every direction by this value). + */ + private static final int RECTANGLE_BORDER_MARGIN = 8; + + /** + * Identifier of the group. + */ + private String groupId; + + /** + * Style of the group. + */ + private String style; + + /** + * Elements in the group. + */ + private Set<PathwayElement> nodes; + + /** + * Default constructor. + * + * @param graphId + * graph identifier in the model + * @param groupId + * {@link #groupId} + */ + public Group(String graphId, String groupId) { + super(graphId); + this.groupId = groupId; + nodes = new HashSet<PathwayElement>(); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected Group() { + } + + @Override + public String getName() { + StringBuilder sb = new StringBuilder(""); + for (PathwayElement n : nodes) { + sb.append(n.getName() + ":"); + } + return sb.toString(); + } + + @Override + public Rectangle2D getRectangle() { + + Rectangle2D result = null; + boolean first = true; + + for (PathwayElement n : nodes) { + if (first) { + result = (Rectangle2D) n.getRectangle().clone(); + first = false; + } + Rectangle2D.union(result, n.getRectangle(), result); + } + if (result == null) { + return null; + } + result.setRect( + result.getX() - RECTANGLE_BORDER_MARGIN, result.getY() - RECTANGLE_BORDER_MARGIN, + result.getWidth() + 2 * RECTANGLE_BORDER_MARGIN, result.getHeight() + + 2 * RECTANGLE_BORDER_MARGIN); + return result; + } + + /** + * + * @return {@link #groupId} + */ + public String getGroupId() { + return groupId; + } + + /** + * Adds element to group. + * + * @param pe + * object to add + */ + public void addNode(PathwayElement pe) { + nodes.add(pe); + } + + /** + * + * @return {@link #nodes} + */ + public Set<PathwayElement> getNodes() { + return this.nodes; + } + + /** + * @return the style + * @see #style + */ + public String getStyle() { + return style; + } + + /** + * @param style + * the style to set + * @see #style + */ + public void setStyle(String style) { + this.style = style; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Interaction.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Interaction.java index 69f9081aa7..563536b9f0 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Interaction.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Interaction.java @@ -1,11 +1,9 @@ package lcsb.mapviewer.wikipathway.model; -import java.awt.Color; +import java.awt.*; import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Set; import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.model.map.MiriamData; @@ -18,373 +16,373 @@ import lcsb.mapviewer.model.map.MiriamData; */ public class Interaction implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Identifier in gpml model. - */ - private String graphId; - - /** - * Where this {@link Interaction} starts (in which {@link Edge}/ - * {@link Interaction}). - */ - private String start; - - /** - * Where this {@link Interaction} ends (in which {@link Edge}/ - * {@link Interaction}). - */ - private String end; - - /** - * Line representing this edge. - */ - private PolylineData line; - - /** - * Z order of the {@link Interaction} (how far it should be located in the z - * coordinate). - */ - private Integer zOrder; - - /** - * Gpml interaction type (arrow). - */ - private GpmlInteractionType type = GpmlInteractionType.LINE; - - /** - * List of anchors placed on the edge. - */ - private Set<String> anchors; - - /** - * Comments. - */ - private List<String> comments = new ArrayList<>(); - - /** - * List of edges representing reactants in interaction. - */ - private Set<Edge> reactants = new HashSet<Edge>(); - - /** - * List of edges representing products in interaction. - */ - private Set<Edge> products = new HashSet<Edge>(); - - /** - * List of edges representing modifiers in interaction. - */ - private Set<Edge> modifiers = new HashSet<Edge>(); - - /** - * Identifiers of biopax references. - */ - private Set<String> biopaxReferences = new HashSet<String>(); - - /** - * References for given edge. - */ - private List<MiriamData> references = new ArrayList<>(); - - /** - * Default constructor. - * - * @param edge - * object will be created from this {@link Edge} - */ - public Interaction(Edge edge) { - graphId = edge.getGraphId(); - setStart(edge.getStart()); - setEnd(edge.getEnd()); - setLine(edge.getLine()); - setType(edge.getType()); - setzOrder(edge.getzOrder()); - for (MiriamData md : edge.getReferences()) { - addReference(new MiriamData(md)); - } - setColor(edge.getColor()); - this.comments.addAll(edge.getComments()); - biopaxReferences.addAll(edge.getBiopaxReferences()); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected Interaction() { - } - - /** - * Adds reference. - * - * @param reference - * object to add - */ - private void addReference(MiriamData reference) { - references.add(reference); - } - - /** - * @return the graphId - * @see #graphId - */ - public String getGraphId() { - return graphId; - } - - /** - * @param graphId - * the graphId to set - * @see #graphId - */ - public void setGraphId(String graphId) { - this.graphId = graphId; - } - - /** - * @return the start - * @see #start - */ - public String getStart() { - return start; - } - - /** - * @param start - * the start to set - * @see #start - */ - public void setStart(String start) { - this.start = start; - } - - /** - * @return the end - * @see #end - */ - public String getEnd() { - return end; - } - - /** - * @param end - * the end to set - * @see #end - */ - public void setEnd(String end) { - this.end = end; - } - - /** - * @return the line - * @see #line - */ - public PolylineData getLine() { - return line; - } - - /** - * @param line - * the line to set - * @see #line - */ - public void setLine(PolylineData line) { - this.line = line; - } - - /** - * @return the anchors - * @see #anchors - */ - public Set<String> getAnchors() { - return anchors; - } - - /** - * @param anchors - * the anchors to set - * @see #anchors - */ - public void setAnchors(Set<String> anchors) { - this.anchors = anchors; - } - - /** - * @return the comment - * @see #comment - */ - public List<String> getComments() { - return comments; - } - - /** - * @param comment - * the comment to set - * @see #comment - */ - public void addComment(String comment) { - this.comments.add(comment); - } - - /** - * @return the reactants - * @see #reactants - */ - public Set<Edge> getReactants() { - return reactants; - } - - /** - * @return the products - * @see #products - */ - public Set<Edge> getProducts() { - return products; - } - - /** - * @return the modifiers - * @see #modifiers - */ - public Set<Edge> getModifiers() { - return modifiers; - } - - /** - * Adds product. - * - * @param interaction - * product to add - */ - public void addProduct(Edge interaction) { - this.products.add(interaction); - interaction.setColor(getLine().getColor()); - biopaxReferences.addAll(interaction.getBiopaxReferences()); - } - - /** - * Add modifier. - * - * @param interaction - * modifier to add - */ - public void addModifier(Edge interaction) { - this.modifiers.add(interaction); - interaction.setColor(getLine().getColor()); - biopaxReferences.addAll(interaction.getBiopaxReferences()); - } - - /** - * Add modifier. - * - * @param interaction - * reactant to add - */ - public void addReactant(Edge interaction) { - this.reactants.add(interaction); - interaction.setColor(getLine().getColor()); - biopaxReferences.addAll(interaction.getBiopaxReferences()); - } - - /** - * @return the biopaxReferences - * @see #biopaxReferences - */ - public Set<String> getBiopaxReferences() { - return biopaxReferences; - } - - /** - * @param biopaxReferences - * the biopaxReferences to set - * @see #biopaxReferences - */ - public void setBiopaxReferences(Set<String> biopaxReferences) { - this.biopaxReferences = biopaxReferences; - } - - /** - * @return the type - * @see #type - */ - public GpmlInteractionType getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(GpmlInteractionType type) { - this.type = type; - } - - /** - * @return the references - * @see #references - */ - public List<MiriamData> getReferences() { - return references; - } - - /** - * @param references - * the references to set - * @see #references - */ - public void setReferences(List<MiriamData> references) { - this.references = references; - } - - /** - * @return the color - * @see #color - */ - public Color getColor() { - return line.getColor(); - } - - /** - * @param color - * the color to set - * @see #color - */ - public void setColor(Color color) { - if (color != null) { - line.setColor(color); - for (Edge edge : reactants) { - edge.setColor(color); - } - for (Edge edge : products) { - edge.setColor(color); - } - for (Edge edge : modifiers) { - edge.setColor(color); - } - } - } - - /** - * @return the zOrder - * @see #zOrder - */ - public Integer getzOrder() { - return zOrder; - } - - /** - * @param zOrder - * the zOrder to set - * @see #zOrder - */ - public void setzOrder(Integer zOrder) { - this.zOrder = zOrder; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Identifier in gpml model. + */ + private String graphId; + + /** + * Where this {@link Interaction} starts (in which {@link Edge}/ + * {@link Interaction}). + */ + private String start; + + /** + * Where this {@link Interaction} ends (in which {@link Edge}/ + * {@link Interaction}). + */ + private String end; + + /** + * Line representing this edge. + */ + private PolylineData line; + + /** + * Z order of the {@link Interaction} (how far it should be located in the z + * coordinate). + */ + private Integer zOrder; + + /** + * Gpml interaction type (arrow). + */ + private GpmlInteractionType type = GpmlInteractionType.LINE; + + /** + * List of anchors placed on the edge. + */ + private Set<String> anchors; + + /** + * Comments. + */ + private List<String> comments = new ArrayList<>(); + + /** + * List of edges representing reactants in interaction. + */ + private Set<Edge> reactants = new HashSet<Edge>(); + + /** + * List of edges representing products in interaction. + */ + private Set<Edge> products = new HashSet<Edge>(); + + /** + * List of edges representing modifiers in interaction. + */ + private Set<Edge> modifiers = new HashSet<Edge>(); + + /** + * Identifiers of biopax references. + */ + private Set<String> biopaxReferences = new HashSet<String>(); + + /** + * References for given edge. + */ + private List<MiriamData> references = new ArrayList<>(); + + /** + * Default constructor. + * + * @param edge + * object will be created from this {@link Edge} + */ + public Interaction(Edge edge) { + graphId = edge.getGraphId(); + setStart(edge.getStart()); + setEnd(edge.getEnd()); + setLine(edge.getLine()); + setType(edge.getType()); + setzOrder(edge.getzOrder()); + for (MiriamData md : edge.getReferences()) { + addReference(new MiriamData(md)); + } + setColor(edge.getColor()); + this.comments.addAll(edge.getComments()); + biopaxReferences.addAll(edge.getBiopaxReferences()); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected Interaction() { + } + + /** + * Adds reference. + * + * @param reference + * object to add + */ + private void addReference(MiriamData reference) { + references.add(reference); + } + + /** + * @return the graphId + * @see #graphId + */ + public String getGraphId() { + return graphId; + } + + /** + * @param graphId + * the graphId to set + * @see #graphId + */ + public void setGraphId(String graphId) { + this.graphId = graphId; + } + + /** + * @return the start + * @see #start + */ + public String getStart() { + return start; + } + + /** + * @param start + * the start to set + * @see #start + */ + public void setStart(String start) { + this.start = start; + } + + /** + * @return the end + * @see #end + */ + public String getEnd() { + return end; + } + + /** + * @param end + * the end to set + * @see #end + */ + public void setEnd(String end) { + this.end = end; + } + + /** + * @return the line + * @see #line + */ + public PolylineData getLine() { + return line; + } + + /** + * @param line + * the line to set + * @see #line + */ + public void setLine(PolylineData line) { + this.line = line; + } + + /** + * @return the anchors + * @see #anchors + */ + public Set<String> getAnchors() { + return anchors; + } + + /** + * @param anchors + * the anchors to set + * @see #anchors + */ + public void setAnchors(Set<String> anchors) { + this.anchors = anchors; + } + + /** + * @return the comment + * @see #comment + */ + public List<String> getComments() { + return comments; + } + + /** + * @param comment + * the comment to set + * @see #comment + */ + public void addComment(String comment) { + this.comments.add(comment); + } + + /** + * @return the reactants + * @see #reactants + */ + public Set<Edge> getReactants() { + return reactants; + } + + /** + * @return the products + * @see #products + */ + public Set<Edge> getProducts() { + return products; + } + + /** + * @return the modifiers + * @see #modifiers + */ + public Set<Edge> getModifiers() { + return modifiers; + } + + /** + * Adds product. + * + * @param interaction + * product to add + */ + public void addProduct(Edge interaction) { + this.products.add(interaction); + interaction.setColor(getLine().getColor()); + biopaxReferences.addAll(interaction.getBiopaxReferences()); + } + + /** + * Add modifier. + * + * @param interaction + * modifier to add + */ + public void addModifier(Edge interaction) { + this.modifiers.add(interaction); + interaction.setColor(getLine().getColor()); + biopaxReferences.addAll(interaction.getBiopaxReferences()); + } + + /** + * Add modifier. + * + * @param interaction + * reactant to add + */ + public void addReactant(Edge interaction) { + this.reactants.add(interaction); + interaction.setColor(getLine().getColor()); + biopaxReferences.addAll(interaction.getBiopaxReferences()); + } + + /** + * @return the biopaxReferences + * @see #biopaxReferences + */ + public Set<String> getBiopaxReferences() { + return biopaxReferences; + } + + /** + * @param biopaxReferences + * the biopaxReferences to set + * @see #biopaxReferences + */ + public void setBiopaxReferences(Set<String> biopaxReferences) { + this.biopaxReferences = biopaxReferences; + } + + /** + * @return the type + * @see #type + */ + public GpmlInteractionType getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(GpmlInteractionType type) { + this.type = type; + } + + /** + * @return the references + * @see #references + */ + public List<MiriamData> getReferences() { + return references; + } + + /** + * @param references + * the references to set + * @see #references + */ + public void setReferences(List<MiriamData> references) { + this.references = references; + } + + /** + * @return the color + * @see #color + */ + public Color getColor() { + return line.getColor(); + } + + /** + * @param color + * the color to set + * @see #color + */ + public void setColor(Color color) { + if (color != null) { + line.setColor(color); + for (Edge edge : reactants) { + edge.setColor(color); + } + for (Edge edge : products) { + edge.setColor(color); + } + for (Edge edge : modifiers) { + edge.setColor(color); + } + } + } + + /** + * @return the zOrder + * @see #zOrder + */ + public Integer getzOrder() { + return zOrder; + } + + /** + * @param zOrder + * the zOrder to set + * @see #zOrder + */ + public void setzOrder(Integer zOrder) { + this.zOrder = zOrder; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/InteractionMapping.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/InteractionMapping.java index d8570ebf06..413dab8be1 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/InteractionMapping.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/InteractionMapping.java @@ -1,24 +1,9 @@ package lcsb.mapviewer.wikipathway.model; import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.modifier.Inhibition; -import lcsb.mapviewer.model.map.modifier.Modulation; -import lcsb.mapviewer.model.map.modifier.PhysicalStimulation; -import lcsb.mapviewer.model.map.modifier.UnknownCatalysis; -import lcsb.mapviewer.model.map.modifier.UnknownInhibition; -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.reaction.type.HeterodimerAssociationReaction; -import lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction; -import lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction; -import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; +import lcsb.mapviewer.model.map.modifier.*; +import lcsb.mapviewer.model.map.reaction.*; +import lcsb.mapviewer.model.map.reaction.type.*; /** * This class contains mapping between gpml interactions and CellDesigner model @@ -39,476 +24,479 @@ import lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction; */ public enum InteractionMapping { - /** - * Default line. - */ - LINE(GpmlInteractionType.LINE, GpmlLineType.SOLID, - UnknownTransitionReaction.class, true, - Reactant.class, false, - Reactant.class, false, - true), - - /** - * Default arrow. - */ - ARROW(GpmlInteractionType.ARROW, GpmlLineType.SOLID, - StateTransitionReaction.class, false, - Modulation.class, true, - Product.class, false), - - /** - * Dashed line. - */ - LINE_DASHED(GpmlInteractionType.LINE, GpmlLineType.DASHED, - UnknownTransitionReaction.class, true, - Reactant.class, true, - Reactant.class, true, - true), - - /** - * Dashed arrow. - */ - ARROW_DASHED(GpmlInteractionType.ARROW, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, false, - Modulation.class, true, - Product.class, true), - - /** - * Line ended with T-bar. - */ - TBAR(GpmlInteractionType.TBAR, GpmlLineType.SOLID, - NegativeInfluenceReaction.class, true, - Inhibition.class, false, - Product.class, true), - - /** - * Line ended with T-bar dashed. - */ - TBAR_DASHED(GpmlInteractionType.TBAR, GpmlLineType.DASHED, - UnknownNegativeInfluenceReaction.class, true, - UnknownInhibition.class, false, - Product.class, true), - - /** - * Necessary stimulation. - */ - NECESSARY_STIMULATION(GpmlInteractionType.NECESSARY_STIMULATION, GpmlLineType.SOLID, - ReducedPhysicalStimulationReaction.class, false, - PhysicalStimulation.class, false, - Product.class, true), - - /** - * Necessary stimulation dashed. - */ - NECESSARY_STIMULATION_DASHED(GpmlInteractionType.NECESSARY_STIMULATION, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, true, - Modulation.class, true, - Product.class, true), - - /** - * Binding. - */ - BINDING(GpmlInteractionType.BINDING, GpmlLineType.SOLID, - HeterodimerAssociationReaction.class, false, - Modulation.class, true, - Product.class, true), - - /** - * Binding dashed. - */ - BINDING_DASHED(GpmlInteractionType.BINDING, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, false, - Modulation.class, true, - Product.class, true), - - /** - * Conversion. - */ - CONVERSION(GpmlInteractionType.CONVERSION, GpmlLineType.SOLID, - StateTransitionReaction.class, false, - Modulation.class, true, - Product.class, false), - - /** - * Dashed conversion. - */ - CONVERSION_DASHED(GpmlInteractionType.CONVERSION, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, false, - Modulation.class, true, - Product.class, true), - - /** - * Stimulation. - */ - STIMULATION(GpmlInteractionType.STIMULATION, GpmlLineType.SOLID, - ReducedPhysicalStimulationReaction.class, true, - PhysicalStimulation.class, false, - Product.class, true), - - /** - * Stimulation dashed. - */ - STIMULATION_DASHED(GpmlInteractionType.STIMULATION, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, true, - Modulation.class, true, - Product.class, true), - - /** - * Modification. - */ - MODIFICATION(GpmlInteractionType.MODIFICATION, GpmlLineType.SOLID, - PositiveInfluenceReaction.class, true, - Modulation.class, false, - Product.class, true), - - /** - * Modification dashed. - */ - MODIFICATION_DASHED(GpmlInteractionType.MODIFICATION, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, false, - Modulation.class, true, - Product.class, true), - - /** - * Catalysis. - */ - CATALYSIS(GpmlInteractionType.CATALYSIS, GpmlLineType.SOLID, - PositiveInfluenceReaction.class, true, - Catalysis.class, false, - Product.class, true), - - /** - * Catalysis dashed. - */ - CATALYSIS_DASHED(GpmlInteractionType.CATALYSIS, GpmlLineType.DASHED, - UnknownPositiveInfluenceReaction.class, true, - UnknownCatalysis.class, false, - Product.class, true), - - /** - * Inhibition. - */ - INHIBITION(GpmlInteractionType.INHIBITION, GpmlLineType.SOLID, - NegativeInfluenceReaction.class, false, - Inhibition.class, false, - Product.class, true), - - /** - * Inhibition dashed. - */ - INHIBITION_DASHED(GpmlInteractionType.INHIBITION, GpmlLineType.DASHED, - UnknownNegativeInfluenceReaction.class, true, - UnknownInhibition.class, true, - Product.class, true), - - /** - * Cleavage. - */ - CLEAVAGE(GpmlInteractionType.CLEAVAGE, GpmlLineType.SOLID, - StateTransitionReaction.class, false, - Modulation.class, true, - Product.class, false), - - /** - * Cleavage dashed. - */ - CLEAVAGE_DASHED(GpmlInteractionType.CLEAVAGE, GpmlLineType.DASHED, - UnknownTransitionReaction.class, true, - Modulation.class, true, - Product.class, true), - - /** - * Covalent bond. - */ - COVALENT_BOND(GpmlInteractionType.COVALENT_BOND, GpmlLineType.SOLID, - UnknownTransitionReaction.class, true, - Reactant.class, true, - Product.class, true, - true), - - /** - * Covalent bond dashed. - */ - COVALENT_BOND_DASHED(GpmlInteractionType.COVALENT_BOND, GpmlLineType.DASHED, - UnknownTransitionReaction.class, true, - Reactant.class, true, - Product.class, true, - true), - - /** - * Branching left. - */ - BRANCHING_LEFT(GpmlInteractionType.BRANCHING_LEFT, GpmlLineType.SOLID, - UnknownTransitionReaction.class, true, - Reactant.class, false, - Reactant.class, false, - true), - - /** - * Branching left dashed. - */ - BRANCHING_LEFT_DASHED(GpmlInteractionType.BRANCHING_LEFT, GpmlLineType.DASHED, - UnknownTransitionReaction.class, true, - Reactant.class, true, - Reactant.class, true, - true), - - /** - * Branching right. - */ - BRANCHING_RIGHT(GpmlInteractionType.BRANCHING_RIGHT, GpmlLineType.SOLID, - UnknownTransitionReaction.class, true, - Reactant.class, false, - Reactant.class, false, - true), - - /** - * Branching right dashed. - */ - BRANCHING_RIGHT_DASHED(GpmlInteractionType.BRANCHING_RIGHT, GpmlLineType.DASHED, - UnknownTransitionReaction.class, true, - Reactant.class, true, - Reactant.class, true, - true), - - /** - * Transription-translation. - */ - TRANSCRIPTION_TRANSLATION(GpmlInteractionType.TRANSCRIPTION_TRANSLATION, GpmlLineType.SOLID, - PositiveInfluenceReaction.class, true, - Modulation.class, true, - Product.class, true), - - /** - * Transription-translation dashed. - */ - TRANSCRIPTION_TRANSLATION_DASHED(GpmlInteractionType.TRANSCRIPTION_TRANSLATION, GpmlLineType.DASHED, - PositiveInfluenceReaction.class, true, - Modulation.class, true, - Product.class, true), - - /** - * Gap... - */ - GAP(GpmlInteractionType.GAP, GpmlLineType.SOLID, - UnknownTransitionReaction.class, true, - Modulation.class, true, - Product.class, true, - true), - - /** - * Gap dashed... - */ - GAP_DASHED(GpmlInteractionType.GAP, GpmlLineType.DASHED, - UnknownTransitionReaction.class, true, - Modulation.class, true, - Product.class, true, - true); - - /** - * Interaction type defined in gpml. - */ - private GpmlInteractionType gpmlInteractionType; - - /** - * Line type defined in gpml. - */ - private GpmlLineType gpmlLineStyle; - - /** - * Cell designer reaction to which gpml interaction should be transformed. - */ - private Class<? extends Reaction> modelReactionType; - - /** - * Cell designer reaction node to which interaction should be transformed when - * it's an input to the reaction. - */ - private Class<? extends ReactionNode> modelInputReactionNodeType; - - /** - * Cell designer reaction node to which interaction should be transformed when - * it's an output to the reaction. - */ - private Class<? extends ReactionNode> modelOutputReactionNodeType; - - /** - * Should CellDesigner reaction be reversible. - */ - private boolean reversible = false; - - /** - * When converting to reaction. Should the code warn. - */ - private boolean interactionWarning = false; - - /** - * When converting to input of the reaction should the code warn. - */ - private boolean inputWarning = false; - - /** - * When converting to output of the reaction should the code warn. - */ - private boolean outputWarning = false; - - /** - * Default constructor. - * - * @param gpmlInteractionType - * {@link #gpmlInteractionType} - * @param gpmlLineStyle - * {@link #gpmlLineStyle} - * @param modelReactionType - * {@link #modelReactionType} - * @param interactionWarning - * {@link #interactionWarning} - * @param modelInputReactionNodeType - * {@link #modelInputReactionNodeType} - * @param inputWarning - * {@link #inputWarning} - * @param modelOutputReactionNodeType - * {@link #modelOutputReactionNodeType} - * @param outputWarning - * {@link #outputWarning} - * @param reversible - * {@link #reversible} - */ - InteractionMapping(GpmlInteractionType gpmlInteractionType, GpmlLineType gpmlLineStyle, Class<? extends Reaction> modelReactionType, - boolean interactionWarning, Class<? extends ReactionNode> modelInputReactionNodeType, boolean inputWarning, - Class<? extends ReactionNode> modelOutputReactionNodeType, boolean outputWarning, boolean reversible) { - this.gpmlInteractionType = gpmlInteractionType; - this.modelReactionType = modelReactionType; - this.interactionWarning = interactionWarning; - this.modelInputReactionNodeType = modelInputReactionNodeType; - this.inputWarning = inputWarning; - this.modelOutputReactionNodeType = modelOutputReactionNodeType; - this.outputWarning = outputWarning; - this.reversible = reversible; - this.gpmlLineStyle = gpmlLineStyle; - } - - /** - * Default constructor. - * - * @param gpmlInteractionType - * {@link #gpmlInteractionType} - * @param gpmlLineStyle - * {@link #gpmlLineStyle} - * @param modelReactionType - * {@link #modelReactionType} - * @param interactionWarning - * {@link #interactionWarning} - * @param modelInputReactionNodeType - * {@link #modelInputReactionNodeType} - * @param inputWarning - * {@link #inputWarning} - * @param modelOutputReactionNodeType - * {@link #modelOutputReactionNodeType} - * @param outputWarning - * {@link #outputWarning} - */ - InteractionMapping(GpmlInteractionType gpmlInteractionType, GpmlLineType gpmlLineStyle, Class<? extends Reaction> modelReactionType, - boolean interactionWarning, Class<? extends ReactionNode> modelInputReactionNodeType, boolean inputWarning, - Class<? extends ReactionNode> modelOutputReactionNodeType, boolean outputWarning) { - this( - gpmlInteractionType, gpmlLineStyle, modelReactionType, interactionWarning, modelInputReactionNodeType, inputWarning, modelOutputReactionNodeType, - outputWarning, false); - } - - /** - * @return the gpmlInteractionType - * @see #gpmlInteractionType - */ - public GpmlInteractionType getGpmlInteractionType() { - return gpmlInteractionType; - } - - /** - * @return the modelReactionType - * @see #modelReactionType - */ - public Class<? extends Reaction> getModelReactionType() { - return modelReactionType; - } - - /** - * @return the modelInputReactionNodeType - * @see #modelInputReactionNodeType - */ - public Class<? extends ReactionNode> getModelInputReactionNodeType() { - return modelInputReactionNodeType; - } - - /** - * @return the modelOutputReactionNodeType - * @see #modelOutputReactionNodeType - */ - public Class<? extends ReactionNode> getModelOutputReactionNodeType() { - return modelOutputReactionNodeType; - } - - /** - * @return the reversible - * @see #reversible - */ - public boolean isReversible() { - return reversible; - } - - /** - * @return the interactionWarning - * @see #interactionWarning - */ - public boolean isInteractionWarning() { - return interactionWarning; - } - - /** - * @return the inputWarning - * @see #inputWarning - */ - public boolean isInputWarning() { - return inputWarning; - } - - /** - * @return the outputWarning - * @see #outputWarning - */ - public boolean isOutputWarning() { - return outputWarning; - } - - /** - * Method that is looking for the {@link InteractionMapping} that matches to - * given gpml "arrow type" and "line type". - * - * @param gpmlType - * gpml arrow type - * @param lineType - * gpml line type - * @return {@link InteractionMapping} that matches to given gpml "arrow type" - * and "line type" - */ - public static InteractionMapping getInteractionMapping(GpmlInteractionType gpmlType, LineType lineType) { - for (InteractionMapping mapping : InteractionMapping.values()) { - boolean arrowMatch = mapping.getGpmlInteractionType().equals(gpmlType); - boolean lineTypeMatch = lineType.equals(mapping.getGpmlLineStyle().getCorrespondingGlobalLineType()); - - if (arrowMatch && lineTypeMatch) { - return mapping; - } - } - return null; - } - - /** - * @return the gpmlLineStyle - * @see #gpmlLineStyle - */ - public GpmlLineType getGpmlLineStyle() { - return gpmlLineStyle; - } + /** + * Default line. + */ + LINE(GpmlInteractionType.LINE, GpmlLineType.SOLID, + UnknownTransitionReaction.class, true, + Reactant.class, false, + Reactant.class, false, + true), + + /** + * Default arrow. + */ + ARROW(GpmlInteractionType.ARROW, GpmlLineType.SOLID, + StateTransitionReaction.class, false, + Modulation.class, true, + Product.class, false), + + /** + * Dashed line. + */ + LINE_DASHED(GpmlInteractionType.LINE, GpmlLineType.DASHED, + UnknownTransitionReaction.class, true, + Reactant.class, true, + Reactant.class, true, + true), + + /** + * Dashed arrow. + */ + ARROW_DASHED(GpmlInteractionType.ARROW, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, false, + Modulation.class, true, + Product.class, true), + + /** + * Line ended with T-bar. + */ + TBAR(GpmlInteractionType.TBAR, GpmlLineType.SOLID, + NegativeInfluenceReaction.class, true, + Inhibition.class, false, + Product.class, true), + + /** + * Line ended with T-bar dashed. + */ + TBAR_DASHED(GpmlInteractionType.TBAR, GpmlLineType.DASHED, + UnknownNegativeInfluenceReaction.class, true, + UnknownInhibition.class, false, + Product.class, true), + + /** + * Necessary stimulation. + */ + NECESSARY_STIMULATION(GpmlInteractionType.NECESSARY_STIMULATION, GpmlLineType.SOLID, + ReducedPhysicalStimulationReaction.class, false, + PhysicalStimulation.class, false, + Product.class, true), + + /** + * Necessary stimulation dashed. + */ + NECESSARY_STIMULATION_DASHED(GpmlInteractionType.NECESSARY_STIMULATION, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, true, + Modulation.class, true, + Product.class, true), + + /** + * Binding. + */ + BINDING(GpmlInteractionType.BINDING, GpmlLineType.SOLID, + HeterodimerAssociationReaction.class, false, + Modulation.class, true, + Product.class, true), + + /** + * Binding dashed. + */ + BINDING_DASHED(GpmlInteractionType.BINDING, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, false, + Modulation.class, true, + Product.class, true), + + /** + * Conversion. + */ + CONVERSION(GpmlInteractionType.CONVERSION, GpmlLineType.SOLID, + StateTransitionReaction.class, false, + Modulation.class, true, + Product.class, false), + + /** + * Dashed conversion. + */ + CONVERSION_DASHED(GpmlInteractionType.CONVERSION, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, false, + Modulation.class, true, + Product.class, true), + + /** + * Stimulation. + */ + STIMULATION(GpmlInteractionType.STIMULATION, GpmlLineType.SOLID, + ReducedPhysicalStimulationReaction.class, true, + PhysicalStimulation.class, false, + Product.class, true), + + /** + * Stimulation dashed. + */ + STIMULATION_DASHED(GpmlInteractionType.STIMULATION, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, true, + Modulation.class, true, + Product.class, true), + + /** + * Modification. + */ + MODIFICATION(GpmlInteractionType.MODIFICATION, GpmlLineType.SOLID, + PositiveInfluenceReaction.class, true, + Modulation.class, false, + Product.class, true), + + /** + * Modification dashed. + */ + MODIFICATION_DASHED(GpmlInteractionType.MODIFICATION, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, false, + Modulation.class, true, + Product.class, true), + + /** + * Catalysis. + */ + CATALYSIS(GpmlInteractionType.CATALYSIS, GpmlLineType.SOLID, + PositiveInfluenceReaction.class, true, + Catalysis.class, false, + Product.class, true), + + /** + * Catalysis dashed. + */ + CATALYSIS_DASHED(GpmlInteractionType.CATALYSIS, GpmlLineType.DASHED, + UnknownPositiveInfluenceReaction.class, true, + UnknownCatalysis.class, false, + Product.class, true), + + /** + * Inhibition. + */ + INHIBITION(GpmlInteractionType.INHIBITION, GpmlLineType.SOLID, + NegativeInfluenceReaction.class, false, + Inhibition.class, false, + Product.class, true), + + /** + * Inhibition dashed. + */ + INHIBITION_DASHED(GpmlInteractionType.INHIBITION, GpmlLineType.DASHED, + UnknownNegativeInfluenceReaction.class, true, + UnknownInhibition.class, true, + Product.class, true), + + /** + * Cleavage. + */ + CLEAVAGE(GpmlInteractionType.CLEAVAGE, GpmlLineType.SOLID, + StateTransitionReaction.class, false, + Modulation.class, true, + Product.class, false), + + /** + * Cleavage dashed. + */ + CLEAVAGE_DASHED(GpmlInteractionType.CLEAVAGE, GpmlLineType.DASHED, + UnknownTransitionReaction.class, true, + Modulation.class, true, + Product.class, true), + + /** + * Covalent bond. + */ + COVALENT_BOND(GpmlInteractionType.COVALENT_BOND, GpmlLineType.SOLID, + UnknownTransitionReaction.class, true, + Reactant.class, true, + Product.class, true, + true), + + /** + * Covalent bond dashed. + */ + COVALENT_BOND_DASHED(GpmlInteractionType.COVALENT_BOND, GpmlLineType.DASHED, + UnknownTransitionReaction.class, true, + Reactant.class, true, + Product.class, true, + true), + + /** + * Branching left. + */ + BRANCHING_LEFT(GpmlInteractionType.BRANCHING_LEFT, GpmlLineType.SOLID, + UnknownTransitionReaction.class, true, + Reactant.class, false, + Reactant.class, false, + true), + + /** + * Branching left dashed. + */ + BRANCHING_LEFT_DASHED(GpmlInteractionType.BRANCHING_LEFT, GpmlLineType.DASHED, + UnknownTransitionReaction.class, true, + Reactant.class, true, + Reactant.class, true, + true), + + /** + * Branching right. + */ + BRANCHING_RIGHT(GpmlInteractionType.BRANCHING_RIGHT, GpmlLineType.SOLID, + UnknownTransitionReaction.class, true, + Reactant.class, false, + Reactant.class, false, + true), + + /** + * Branching right dashed. + */ + BRANCHING_RIGHT_DASHED(GpmlInteractionType.BRANCHING_RIGHT, GpmlLineType.DASHED, + UnknownTransitionReaction.class, true, + Reactant.class, true, + Reactant.class, true, + true), + + /** + * Transription-translation. + */ + TRANSCRIPTION_TRANSLATION(GpmlInteractionType.TRANSCRIPTION_TRANSLATION, GpmlLineType.SOLID, + PositiveInfluenceReaction.class, true, + Modulation.class, true, + Product.class, true), + + /** + * Transription-translation dashed. + */ + TRANSCRIPTION_TRANSLATION_DASHED(GpmlInteractionType.TRANSCRIPTION_TRANSLATION, GpmlLineType.DASHED, + PositiveInfluenceReaction.class, true, + Modulation.class, true, + Product.class, true), + + /** + * Gap... + */ + GAP(GpmlInteractionType.GAP, GpmlLineType.SOLID, + UnknownTransitionReaction.class, true, + Modulation.class, true, + Product.class, true, + true), + + /** + * Gap dashed... + */ + GAP_DASHED(GpmlInteractionType.GAP, GpmlLineType.DASHED, + UnknownTransitionReaction.class, true, + Modulation.class, true, + Product.class, true, + true); + + /** + * Interaction type defined in gpml. + */ + private GpmlInteractionType gpmlInteractionType; + + /** + * Line type defined in gpml. + */ + private GpmlLineType gpmlLineStyle; + + /** + * Cell designer reaction to which gpml interaction should be transformed. + */ + private Class<? extends Reaction> modelReactionType; + + /** + * Cell designer reaction node to which interaction should be transformed when + * it's an input to the reaction. + */ + private Class<? extends ReactionNode> modelInputReactionNodeType; + + /** + * Cell designer reaction node to which interaction should be transformed when + * it's an output to the reaction. + */ + private Class<? extends ReactionNode> modelOutputReactionNodeType; + + /** + * Should CellDesigner reaction be reversible. + */ + private boolean reversible = false; + + /** + * When converting to reaction. Should the code warn. + */ + private boolean interactionWarning = false; + + /** + * When converting to input of the reaction should the code warn. + */ + private boolean inputWarning = false; + + /** + * When converting to output of the reaction should the code warn. + */ + private boolean outputWarning = false; + + /** + * Default constructor. + * + * @param gpmlInteractionType + * {@link #gpmlInteractionType} + * @param gpmlLineStyle + * {@link #gpmlLineStyle} + * @param modelReactionType + * {@link #modelReactionType} + * @param interactionWarning + * {@link #interactionWarning} + * @param modelInputReactionNodeType + * {@link #modelInputReactionNodeType} + * @param inputWarning + * {@link #inputWarning} + * @param modelOutputReactionNodeType + * {@link #modelOutputReactionNodeType} + * @param outputWarning + * {@link #outputWarning} + * @param reversible + * {@link #reversible} + */ + InteractionMapping(GpmlInteractionType gpmlInteractionType, GpmlLineType gpmlLineStyle, + Class<? extends Reaction> modelReactionType, + boolean interactionWarning, Class<? extends ReactionNode> modelInputReactionNodeType, boolean inputWarning, + Class<? extends ReactionNode> modelOutputReactionNodeType, boolean outputWarning, boolean reversible) { + this.gpmlInteractionType = gpmlInteractionType; + this.modelReactionType = modelReactionType; + this.interactionWarning = interactionWarning; + this.modelInputReactionNodeType = modelInputReactionNodeType; + this.inputWarning = inputWarning; + this.modelOutputReactionNodeType = modelOutputReactionNodeType; + this.outputWarning = outputWarning; + this.reversible = reversible; + this.gpmlLineStyle = gpmlLineStyle; + } + + /** + * Default constructor. + * + * @param gpmlInteractionType + * {@link #gpmlInteractionType} + * @param gpmlLineStyle + * {@link #gpmlLineStyle} + * @param modelReactionType + * {@link #modelReactionType} + * @param interactionWarning + * {@link #interactionWarning} + * @param modelInputReactionNodeType + * {@link #modelInputReactionNodeType} + * @param inputWarning + * {@link #inputWarning} + * @param modelOutputReactionNodeType + * {@link #modelOutputReactionNodeType} + * @param outputWarning + * {@link #outputWarning} + */ + InteractionMapping(GpmlInteractionType gpmlInteractionType, GpmlLineType gpmlLineStyle, + Class<? extends Reaction> modelReactionType, + boolean interactionWarning, Class<? extends ReactionNode> modelInputReactionNodeType, boolean inputWarning, + Class<? extends ReactionNode> modelOutputReactionNodeType, boolean outputWarning) { + this( + gpmlInteractionType, gpmlLineStyle, modelReactionType, interactionWarning, modelInputReactionNodeType, + inputWarning, modelOutputReactionNodeType, + outputWarning, false); + } + + /** + * Method that is looking for the {@link InteractionMapping} that matches to + * given gpml "arrow type" and "line type". + * + * @param gpmlType + * gpml arrow type + * @param lineType + * gpml line type + * @return {@link InteractionMapping} that matches to given gpml "arrow type" + * and "line type" + */ + public static InteractionMapping getInteractionMapping(GpmlInteractionType gpmlType, LineType lineType) { + for (InteractionMapping mapping : InteractionMapping.values()) { + boolean arrowMatch = mapping.getGpmlInteractionType().equals(gpmlType); + boolean lineTypeMatch = lineType.equals(mapping.getGpmlLineStyle().getCorrespondingGlobalLineType()); + + if (arrowMatch && lineTypeMatch) { + return mapping; + } + } + return null; + } + + /** + * @return the gpmlInteractionType + * @see #gpmlInteractionType + */ + public GpmlInteractionType getGpmlInteractionType() { + return gpmlInteractionType; + } + + /** + * @return the modelReactionType + * @see #modelReactionType + */ + public Class<? extends Reaction> getModelReactionType() { + return modelReactionType; + } + + /** + * @return the modelInputReactionNodeType + * @see #modelInputReactionNodeType + */ + public Class<? extends ReactionNode> getModelInputReactionNodeType() { + return modelInputReactionNodeType; + } + + /** + * @return the modelOutputReactionNodeType + * @see #modelOutputReactionNodeType + */ + public Class<? extends ReactionNode> getModelOutputReactionNodeType() { + return modelOutputReactionNodeType; + } + + /** + * @return the reversible + * @see #reversible + */ + public boolean isReversible() { + return reversible; + } + + /** + * @return the interactionWarning + * @see #interactionWarning + */ + public boolean isInteractionWarning() { + return interactionWarning; + } + + /** + * @return the inputWarning + * @see #inputWarning + */ + public boolean isInputWarning() { + return inputWarning; + } + + /** + * @return the outputWarning + * @see #outputWarning + */ + public boolean isOutputWarning() { + return outputWarning; + } + + /** + * @return the gpmlLineStyle + * @see #gpmlLineStyle + */ + public GpmlLineType getGpmlLineStyle() { + return gpmlLineStyle; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Label.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Label.java index 0f1ff697dc..d6ba71d23c 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Label.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Label.java @@ -8,165 +8,165 @@ package lcsb.mapviewer.wikipathway.model; */ public class Label extends GraphicalPathwayElement { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * ??? - */ - private String textLabel; - - /** - * Font weight (like italic, bold) that should be used. - */ - private String fontWeight; - - /** - * Shape associated with the label border. - */ - private String shape; - - /** - * How description should be aligned. - */ - private String vAlign; - - /** - * Where this node belongs to. - */ - private String groupRef; - - /** - * Sometimes {@link Label labels} are connected to reactions. This field - */ - private boolean treatAsNode = false; - - /** - * Default constructor. - * - * @param graphId - * {@link PathwayElement#graphId} - */ - public Label(String graphId) { - super(graphId); - setTextLabel(null); - setGroupRef(null); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected Label() { - } - - @Override - public String getName() { - return getTextLabel(); - } - - /** - * @return the textLabel - * @see #textLabel - */ - public String getTextLabel() { - return textLabel; - } - - /** - * @param textLabel - * the textLabel to set - * @see #textLabel - */ - public void setTextLabel(String textLabel) { - this.textLabel = textLabel; - } - - /** - * @return the groupRef - * @see #groupRef - */ - public String getGroupRef() { - return groupRef; - } - - /** - * @param groupRef - * the groupRef to set - * @see #groupRef - */ - public void setGroupRef(String groupRef) { - this.groupRef = groupRef; - } - - /** - * @return the treatAsNode - * @see #treatAsNode - */ - public boolean isTreatAsNode() { - return treatAsNode; - } - - /** - * @param treatAsNode - * the treatAsNode to set - * @see #treatAsNode - */ - public void setTreatAsNode(boolean treatAsNode) { - this.treatAsNode = treatAsNode; - } - - /** - * @return the vAlign - * @see #vAlign - */ - public String getvAlign() { - return vAlign; - } - - /** - * @param vAlign - * the vAlign to set - * @see #vAlign - */ - public void setvAlign(String vAlign) { - this.vAlign = vAlign; - } - - /** - * @return the fontWeight - * @see #fontWeight - */ - public String getFontWeight() { - return fontWeight; - } - - /** - * @param fontWeight - * the fontWeight to set - * @see #fontWeight - */ - public void setFontWeight(String fontWeight) { - this.fontWeight = fontWeight; - } - - /** - * @return the shape - * @see #shape - */ - public String getShape() { - return shape; - } - - /** - * @param shape - * the shape to set - * @see #shape - */ - public void setShape(String shape) { - this.shape = shape; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * ??? + */ + private String textLabel; + + /** + * Font weight (like italic, bold) that should be used. + */ + private String fontWeight; + + /** + * Shape associated with the label border. + */ + private String shape; + + /** + * How description should be aligned. + */ + private String vAlign; + + /** + * Where this node belongs to. + */ + private String groupRef; + + /** + * Sometimes {@link Label labels} are connected to reactions. This field + */ + private boolean treatAsNode = false; + + /** + * Default constructor. + * + * @param graphId + * {@link PathwayElement#graphId} + */ + public Label(String graphId) { + super(graphId); + setTextLabel(null); + setGroupRef(null); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected Label() { + } + + @Override + public String getName() { + return getTextLabel(); + } + + /** + * @return the textLabel + * @see #textLabel + */ + public String getTextLabel() { + return textLabel; + } + + /** + * @param textLabel + * the textLabel to set + * @see #textLabel + */ + public void setTextLabel(String textLabel) { + this.textLabel = textLabel; + } + + /** + * @return the groupRef + * @see #groupRef + */ + public String getGroupRef() { + return groupRef; + } + + /** + * @param groupRef + * the groupRef to set + * @see #groupRef + */ + public void setGroupRef(String groupRef) { + this.groupRef = groupRef; + } + + /** + * @return the treatAsNode + * @see #treatAsNode + */ + public boolean isTreatAsNode() { + return treatAsNode; + } + + /** + * @param treatAsNode + * the treatAsNode to set + * @see #treatAsNode + */ + public void setTreatAsNode(boolean treatAsNode) { + this.treatAsNode = treatAsNode; + } + + /** + * @return the vAlign + * @see #vAlign + */ + public String getvAlign() { + return vAlign; + } + + /** + * @param vAlign + * the vAlign to set + * @see #vAlign + */ + public void setvAlign(String vAlign) { + this.vAlign = vAlign; + } + + /** + * @return the fontWeight + * @see #fontWeight + */ + public String getFontWeight() { + return fontWeight; + } + + /** + * @param fontWeight + * the fontWeight to set + * @see #fontWeight + */ + public void setFontWeight(String fontWeight) { + this.fontWeight = fontWeight; + } + + /** + * @return the shape + * @see #shape + */ + public String getShape() { + return shape; + } + + /** + * @param shape + * the shape to set + * @see #shape + */ + public void setShape(String shape) { + this.shape = shape; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/MergeMapping.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/MergeMapping.java index 2076bccc08..ec6a8877ec 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/MergeMapping.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/MergeMapping.java @@ -10,190 +10,190 @@ package lcsb.mapviewer.wikipathway.model; */ public enum MergeMapping { - /** - * Merging {@link GpmlInteractionType#LINE} and - * {@link GpmlInteractionType#ARROW} when both of them are in right direction. - */ - LINE_ARROW_N_N(GpmlInteractionType.LINE, false, GpmlInteractionType.ARROW, false, GpmlInteractionType.ARROW, false), - - /** - * Merging {@link GpmlInteractionType#LINE} and - * {@link GpmlInteractionType#ARROW} when line is reversed (user doesn't see a - * difference) and arrow is in normal direction. - */ - LINE_ARROW_R_N(GpmlInteractionType.LINE, true, GpmlInteractionType.ARROW, false, GpmlInteractionType.ARROW, false), - - /** - * Merging {@link GpmlInteractionType#ARROW} and - * {@link GpmlInteractionType#LINE} when arrow is reversed and line is in - * normal direction. - */ - ARROW_LINE_R_N(GpmlInteractionType.ARROW, true, GpmlInteractionType.LINE, false, GpmlInteractionType.ARROW, true), - - /** - * Merging {@link GpmlInteractionType#ARROW} and - * {@link GpmlInteractionType#LINE} when line is reversed and line is also - * reversed (user doesn't see a difference) . - */ - ARROW_LINE_R_R(GpmlInteractionType.ARROW, true, GpmlInteractionType.LINE, true, GpmlInteractionType.ARROW, true), - - /** - * Merging {@link GpmlInteractionType#LINE} and - * {@link GpmlInteractionType#LINE} when both of them are in right direction. - */ - LINE_LINE_N_N(GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, false), - - /** - * Merging {@link GpmlInteractionType#LINE} and - * {@link GpmlInteractionType#LINE} when first of them is reversed and second - * not. - */ - LINE_LINE_R_N(GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, false), - - /** - * Merging {@link GpmlInteractionType#LINE} and - * {@link GpmlInteractionType#LINE} when first is in right direction, but - * second reversed. - */ - LINE_LINE_N_R(GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, false), - - /** - * Merging {@link GpmlInteractionType#LINE} and - * {@link GpmlInteractionType#LINE} when both of them are reversed. - */ - LINE_LINE_R_R(GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, false); - - /** - * Type of the first edge to merge. - */ - private GpmlInteractionType type1; - - /** - * Is the first edge reversed or not (if first edge is reversed it means that - * the merging will be done in the beginning of first edge). - */ - private boolean reversed1; - - /** - * Type of the second edge. - */ - private GpmlInteractionType type2; - - /** - * Is the second edge reversed or not (if second edge is reversed it means - * that the merging will be done in the end of second edge). - */ - private boolean reversed2; - - /** - * Which type should be used after merging. - */ - private GpmlInteractionType resultType; - - /** - * Should the edge after merging be reversed or not. If it's reversed it means - * that it will go from second edge to first edge, if it's not reversed then - * it will go from first edge to second edge. - */ - private boolean resultReversed; - - /** - * Default constructor. - * - * @param type1 - * {@link #type1} - * @param reversed1 - * {@link #reversed1} - * @param type2 - * {@link #type2} - * @param reversed2 - * {@link #reversed2} - * @param resultType - * {@link #resultType} - * @param resultReversed - * {@link #resultReversed} - */ - MergeMapping(GpmlInteractionType type1, boolean reversed1, GpmlInteractionType type2, boolean reversed2, GpmlInteractionType resultType, - boolean resultReversed) { - this.type1 = type1; - this.reversed1 = reversed1; - this.type2 = type2; - this.reversed2 = reversed2; - this.resultType = resultType; - this.resultReversed = resultReversed; - } - - /** - * Returns {@link MergeMapping merge rule} that should be used for merging two - * {@link Edge edges}. - * - * @param type1 - * {@link #type1} - * @param reversed1 - * {@link #reversed1} - * @param type2 - * {@link #type2} - * @param reversed2 - * {@link #reversed2} - * @return {@link MergeMapping merge rule} that should be used for merging two - * {@link Edge edges} or <code>null</code> if such rule cannot be - * found - */ - public static MergeMapping getMergeMappingByInteractions(GpmlInteractionType type1, boolean reversed1, GpmlInteractionType type2, boolean reversed2) { - for (MergeMapping mm : values()) { - if (mm.getType1().equals(type1) && mm.isReversed1() == reversed1 && mm.getType2().equals(type2) && mm.isReversed2() == reversed2) { - return mm; - } - } - return null; - } - - /** - * @return the type1 - * @see #type1 - */ - public GpmlInteractionType getType1() { - return type1; - } - - /** - * @return the reversed1 - * @see #reversed1 - */ - public boolean isReversed1() { - return reversed1; - } - - /** - * @return the type2 - * @see #type2 - */ - public GpmlInteractionType getType2() { - return type2; - } - - /** - * @return the reversed2 - * @see #reversed2 - */ - public boolean isReversed2() { - return reversed2; - } - - /** - * @return the resultType - * @see #resultType - */ - public GpmlInteractionType getResultType() { - return resultType; - } - - /** - * @return the resultReversed - * @see #resultReversed - */ - public boolean isResultReversed() { - return resultReversed; - } + /** + * Merging {@link GpmlInteractionType#LINE} and + * {@link GpmlInteractionType#ARROW} when both of them are in right direction. + */ + LINE_ARROW_N_N(GpmlInteractionType.LINE, false, GpmlInteractionType.ARROW, false, GpmlInteractionType.ARROW, false), + + /** + * Merging {@link GpmlInteractionType#LINE} and + * {@link GpmlInteractionType#ARROW} when line is reversed (user doesn't see a + * difference) and arrow is in normal direction. + */ + LINE_ARROW_R_N(GpmlInteractionType.LINE, true, GpmlInteractionType.ARROW, false, GpmlInteractionType.ARROW, false), + + /** + * Merging {@link GpmlInteractionType#ARROW} and + * {@link GpmlInteractionType#LINE} when arrow is reversed and line is in normal + * direction. + */ + ARROW_LINE_R_N(GpmlInteractionType.ARROW, true, GpmlInteractionType.LINE, false, GpmlInteractionType.ARROW, true), + + /** + * Merging {@link GpmlInteractionType#ARROW} and + * {@link GpmlInteractionType#LINE} when line is reversed and line is also + * reversed (user doesn't see a difference) . + */ + ARROW_LINE_R_R(GpmlInteractionType.ARROW, true, GpmlInteractionType.LINE, true, GpmlInteractionType.ARROW, true), + + /** + * Merging {@link GpmlInteractionType#LINE} and {@link GpmlInteractionType#LINE} + * when both of them are in right direction. + */ + LINE_LINE_N_N(GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, false), + + /** + * Merging {@link GpmlInteractionType#LINE} and {@link GpmlInteractionType#LINE} + * when first of them is reversed and second not. + */ + LINE_LINE_R_N(GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, false), + + /** + * Merging {@link GpmlInteractionType#LINE} and {@link GpmlInteractionType#LINE} + * when first is in right direction, but second reversed. + */ + LINE_LINE_N_R(GpmlInteractionType.LINE, false, GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, false), + + /** + * Merging {@link GpmlInteractionType#LINE} and {@link GpmlInteractionType#LINE} + * when both of them are reversed. + */ + LINE_LINE_R_R(GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, true, GpmlInteractionType.LINE, false); + + /** + * Type of the first edge to merge. + */ + private GpmlInteractionType type1; + + /** + * Is the first edge reversed or not (if first edge is reversed it means that + * the merging will be done in the beginning of first edge). + */ + private boolean reversed1; + + /** + * Type of the second edge. + */ + private GpmlInteractionType type2; + + /** + * Is the second edge reversed or not (if second edge is reversed it means that + * the merging will be done in the end of second edge). + */ + private boolean reversed2; + + /** + * Which type should be used after merging. + */ + private GpmlInteractionType resultType; + + /** + * Should the edge after merging be reversed or not. If it's reversed it means + * that it will go from second edge to first edge, if it's not reversed then it + * will go from first edge to second edge. + */ + private boolean resultReversed; + + /** + * Default constructor. + * + * @param type1 + * {@link #type1} + * @param reversed1 + * {@link #reversed1} + * @param type2 + * {@link #type2} + * @param reversed2 + * {@link #reversed2} + * @param resultType + * {@link #resultType} + * @param resultReversed + * {@link #resultReversed} + */ + MergeMapping(GpmlInteractionType type1, boolean reversed1, GpmlInteractionType type2, boolean reversed2, + GpmlInteractionType resultType, + boolean resultReversed) { + this.type1 = type1; + this.reversed1 = reversed1; + this.type2 = type2; + this.reversed2 = reversed2; + this.resultType = resultType; + this.resultReversed = resultReversed; + } + + /** + * Returns {@link MergeMapping merge rule} that should be used for merging two + * {@link Edge edges}. + * + * @param type1 + * {@link #type1} + * @param reversed1 + * {@link #reversed1} + * @param type2 + * {@link #type2} + * @param reversed2 + * {@link #reversed2} + * @return {@link MergeMapping merge rule} that should be used for merging two + * {@link Edge edges} or <code>null</code> if such rule cannot be found + */ + public static MergeMapping getMergeMappingByInteractions(GpmlInteractionType type1, boolean reversed1, + GpmlInteractionType type2, boolean reversed2) { + for (MergeMapping mm : values()) { + if (mm.getType1().equals(type1) && mm.isReversed1() == reversed1 && mm.getType2().equals(type2) + && mm.isReversed2() == reversed2) { + return mm; + } + } + return null; + } + + /** + * @return the type1 + * @see #type1 + */ + public GpmlInteractionType getType1() { + return type1; + } + + /** + * @return the reversed1 + * @see #reversed1 + */ + public boolean isReversed1() { + return reversed1; + } + + /** + * @return the type2 + * @see #type2 + */ + public GpmlInteractionType getType2() { + return type2; + } + + /** + * @return the reversed2 + * @see #reversed2 + */ + public boolean isReversed2() { + return reversed2; + } + + /** + * @return the resultType + * @see #resultType + */ + public GpmlInteractionType getResultType() { + return resultType; + } + + /** + * @return the resultReversed + * @see #resultReversed + */ + public boolean isResultReversed() { + return resultReversed; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PathwayElement.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PathwayElement.java index 665c44527d..4b0a7263e8 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PathwayElement.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PathwayElement.java @@ -9,9 +9,9 @@ import java.util.List; * Abstract class for pathway elements. It defines common functionalities for * all elements in the model. There are two known subclasses: * <ul> - * <li> {@link GraphicalPathwayElement}, representing elemnts with some graphical + * <li>{@link GraphicalPathwayElement}, representing elemnts with some graphical * representation</li> - * <li> {@link Group}, representing just groups of elements</li> + * <li>{@link Group}, representing just groups of elements</li> * </ul> * * @author Jan Badura @@ -19,149 +19,147 @@ import java.util.List; */ public abstract class PathwayElement implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Comment of the element. - */ - private List<String> comments = new ArrayList<>(); - - /** - * Z order of the element. - */ - private Integer zOrder; - - /** - * Identifier of the element in model. - */ - private String graphId; - - /** - * - * Reference to biopax node with references about this element. - */ - private List<String> biopaxReferences = new ArrayList<>(); - - /** - * Default constructor. - * - * @param graphId - * {@link #graphId} value - */ - public PathwayElement(String graphId) { - this.graphId = graphId; - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected PathwayElement() { - } - - /** - * - * @return {@link #graphId} - */ - public String getGraphId() { - return this.graphId; - } - - /** - * Returns name of the element. - * - * @return name of the element - */ - abstract String getName(); - - /** - * Return boundary of the element. - * - * @return boundary of the element - */ - abstract Rectangle2D getRectangle(); - - /** - * @param graphId - * the graphId to set - * @see #graphId - */ - void setGraphId(String graphId) { - this.graphId = graphId; - } - - /** - * Returns prefix that should be used in logger for warnings about this - * element. - * - * @return prefix that should be used in logger for warnings about this - * element - */ - public String getWarningPrefix() { - return "[" + this.getClass().getSimpleName() + ", " + getGraphId() + "]\t"; - } - - /** - * @return the biopaxReference - * @see #biopaxReference - */ - public List<String> getBiopaxReference() { - return biopaxReferences; - } - - /** - * @param biopaxReferences - * the biopaxReference to set - * @see #biopaxReference - */ - public void setBiopaxReference(List<String> biopaxReferences) { - this.biopaxReferences = biopaxReferences; - } - - /** - * @return the zOrder - * @see #zOrder - */ - public Integer getzOrder() { - return zOrder; - } - - /** - * @param zOrder - * the zOrder to set - * @see #zOrder - */ - public void setzOrder(Integer zOrder) { - this.zOrder = zOrder; - } - - /** - * Adds reference to {@link #biopaxReferences}. - * - * @param biopaxString - * reference to add - */ - public void addBiopaxReference(String biopaxString) { - biopaxReferences.add(biopaxString); - } - - /** - * @return the comments - * @see #comments - */ - public List<String> getComments() { - return comments; - } - - /** - * @param comment - * the comment to set - * @see #comment - */ - public void addComment(String comment) { - this.comments.add(comment); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Comment of the element. + */ + private List<String> comments = new ArrayList<>(); + + /** + * Z order of the element. + */ + private Integer zOrder; + + /** + * Identifier of the element in model. + */ + private String graphId; + + /** + * + * Reference to biopax node with references about this element. + */ + private List<String> biopaxReferences = new ArrayList<>(); + + /** + * Default constructor. + * + * @param graphId + * {@link #graphId} value + */ + public PathwayElement(String graphId) { + this.graphId = graphId; + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected PathwayElement() { + } + + /** + * + * @return {@link #graphId} + */ + public String getGraphId() { + return this.graphId; + } + + /** + * @param graphId + * the graphId to set + * @see #graphId + */ + void setGraphId(String graphId) { + this.graphId = graphId; + } + + /** + * Returns name of the element. + * + * @return name of the element + */ + abstract String getName(); + + /** + * Return boundary of the element. + * + * @return boundary of the element + */ + abstract Rectangle2D getRectangle(); + + /** + * Returns prefix that should be used in logger for warnings about this element. + * + * @return prefix that should be used in logger for warnings about this element + */ + public String getWarningPrefix() { + return "[" + this.getClass().getSimpleName() + ", " + getGraphId() + "]\t"; + } + + /** + * @return the biopaxReference + * @see #biopaxReference + */ + public List<String> getBiopaxReference() { + return biopaxReferences; + } + + /** + * @param biopaxReferences + * the biopaxReference to set + * @see #biopaxReference + */ + public void setBiopaxReference(List<String> biopaxReferences) { + this.biopaxReferences = biopaxReferences; + } + + /** + * @return the zOrder + * @see #zOrder + */ + public Integer getzOrder() { + return zOrder; + } + + /** + * @param zOrder + * the zOrder to set + * @see #zOrder + */ + public void setzOrder(Integer zOrder) { + this.zOrder = zOrder; + } + + /** + * Adds reference to {@link #biopaxReferences}. + * + * @param biopaxString + * reference to add + */ + public void addBiopaxReference(String biopaxString) { + biopaxReferences.add(biopaxString); + } + + /** + * @return the comments + * @see #comments + */ + public List<String> getComments() { + return comments; + } + + /** + * @param comment + * the comment to set + * @see #comment + */ + public void addComment(String comment) { + this.comments.add(comment); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PointData.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PointData.java index c05084ce6c..a651e4af3e 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PointData.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/PointData.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.wikipathway.model; import java.awt.geom.Point2D; import java.io.Serializable; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Class that defines infgomration about point stored in gpml structures. @@ -13,189 +14,190 @@ import org.apache.logging.log4j.*; */ public class PointData implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Defdault clas logger. - */ - private final transient Logger logger = LogManager.getLogger(PointData.class); - - /** - * X coordinate. - */ - private Double x; - - /** - * Y coordinate. - */ - private Double y; - - /** - * String identifing anchor point on the map. - */ - private String graphRef; - - /** - * Where the point is placed on the {@link Shape} object (it's a value between - * -1,1). - */ - private String relX; - - /** - * Where the point is placed on the {@link Shape} object (it's a value between - * -1,1). - */ - private String relY; - - /** - * Type of line asociated with line that ends in this point. - */ - private GpmlInteractionType type; - - /** - * @return the x - * @see #x - */ - public Double getX() { - return x; - } - - /** - * @param x - * the x to set - * @see #x - */ - public void setX(Double x) { - this.x = x; - } - - /** - * @return the y - * @see #y - */ - public Double getY() { - return y; - } - - /** - * @param y - * the y to set - * @see #y - */ - public void setY(Double y) { - this.y = y; - } - - /** - * @param relX - * the relX to set - * @see #relX - */ - public void setRelX(String relX) { - this.relX = relX; - } - - /** - * @param relY - * the relY to set - * @see #relY - */ - public void setRelY(String relY) { - this.relY = relY; - } - - /** - * @return the type - * @see #type - */ - public GpmlInteractionType getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(GpmlInteractionType type) { - this.type = type; - } - - /** - * @return the graphRef - * @see #graphRef - */ - public String getGraphRef() { - return graphRef; - } - - /** - * @param graphRef - * the graphRef to set - * @see #graphRef - */ - public void setGraphRef(String graphRef) { - this.graphRef = graphRef; - } - - /** - * Transform {@link PointData} into standard {@link Point2D point}. - * - * @return {@link Point2D point} represented by this structure - */ - public Point2D toPoint() { - return new Point2D.Double(x, y); - } - - /** - * Returns <code>true</code> if point is connected some defined point on the - * map, <code>false</code> otherwise. - * - * @return <code>true</code> if point is connected some defined point on the - * map, <code>false</code> otherwise. - */ - public boolean hasGraphRef() { - return graphRef != null && !graphRef.isEmpty(); - } - - /** - * Returns {@link Direction direction} from which this point is placed on - * {@link Shape} to which the point is connected. - * - * @return {@link Direction direction} from which this point is placed on - * {@link Shape} - */ - public Direction getDirection() { - if (relX == null || relY == null) { - return null; - } else if (relX.equals("1.0")) { - return Direction.EAST; - } else if (relX.equals("-1.0")) { - return Direction.WEST; - } else if (relY.equals("1.0")) { - return Direction.SOUTH; - } else if (relY.equals("-1.0")) { - return Direction.NORTH; - } else { - logger.warn("Cannot determine connection direction from values: relX=" + relX + "; relY=" + relY + ". Estimating..."); - double xVal = Double.valueOf(relX); - double yVal = Double.valueOf(relY); - if (Math.abs(xVal) > Math.abs(yVal)) { - if (xVal > 0) { - return Direction.EAST; - } else { - return Direction.WEST; - } - } else { - if (yVal > 0) { - return Direction.NORTH; - } else { - return Direction.SOUTH; - } - } - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Defdault clas logger. + */ + private final transient Logger logger = LogManager.getLogger(PointData.class); + + /** + * X coordinate. + */ + private Double x; + + /** + * Y coordinate. + */ + private Double y; + + /** + * String identifing anchor point on the map. + */ + private String graphRef; + + /** + * Where the point is placed on the {@link Shape} object (it's a value between + * -1,1). + */ + private String relX; + + /** + * Where the point is placed on the {@link Shape} object (it's a value between + * -1,1). + */ + private String relY; + + /** + * Type of line asociated with line that ends in this point. + */ + private GpmlInteractionType type; + + /** + * @return the x + * @see #x + */ + public Double getX() { + return x; + } + + /** + * @param x + * the x to set + * @see #x + */ + public void setX(Double x) { + this.x = x; + } + + /** + * @return the y + * @see #y + */ + public Double getY() { + return y; + } + + /** + * @param y + * the y to set + * @see #y + */ + public void setY(Double y) { + this.y = y; + } + + /** + * @param relX + * the relX to set + * @see #relX + */ + public void setRelX(String relX) { + this.relX = relX; + } + + /** + * @param relY + * the relY to set + * @see #relY + */ + public void setRelY(String relY) { + this.relY = relY; + } + + /** + * @return the type + * @see #type + */ + public GpmlInteractionType getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(GpmlInteractionType type) { + this.type = type; + } + + /** + * @return the graphRef + * @see #graphRef + */ + public String getGraphRef() { + return graphRef; + } + + /** + * @param graphRef + * the graphRef to set + * @see #graphRef + */ + public void setGraphRef(String graphRef) { + this.graphRef = graphRef; + } + + /** + * Transform {@link PointData} into standard {@link Point2D point}. + * + * @return {@link Point2D point} represented by this structure + */ + public Point2D toPoint() { + return new Point2D.Double(x, y); + } + + /** + * Returns <code>true</code> if point is connected some defined point on the + * map, <code>false</code> otherwise. + * + * @return <code>true</code> if point is connected some defined point on the + * map, <code>false</code> otherwise. + */ + public boolean hasGraphRef() { + return graphRef != null && !graphRef.isEmpty(); + } + + /** + * Returns {@link Direction direction} from which this point is placed on + * {@link Shape} to which the point is connected. + * + * @return {@link Direction direction} from which this point is placed on + * {@link Shape} + */ + public Direction getDirection() { + if (relX == null || relY == null) { + return null; + } else if (relX.equals("1.0")) { + return Direction.EAST; + } else if (relX.equals("-1.0")) { + return Direction.WEST; + } else if (relY.equals("1.0")) { + return Direction.SOUTH; + } else if (relY.equals("-1.0")) { + return Direction.NORTH; + } else { + logger.warn( + "Cannot determine connection direction from values: relX=" + relX + "; relY=" + relY + ". Estimating..."); + double xVal = Double.valueOf(relX); + double yVal = Double.valueOf(relY); + if (Math.abs(xVal) > Math.abs(yVal)) { + if (xVal > 0) { + return Direction.EAST; + } else { + return Direction.WEST; + } + } else { + if (yVal > 0) { + return Direction.NORTH; + } else { + return Direction.SOUTH; + } + } + } + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/ReferenceMapping.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/ReferenceMapping.java index 9db45a737d..e0067fabbd 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/ReferenceMapping.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/ReferenceMapping.java @@ -11,260 +11,260 @@ import lcsb.mapviewer.model.map.MiriamType; */ public enum ReferenceMapping { - /** - * {@link MiriamType#CAS}. - */ - CAS("CAS", MiriamType.CAS), - - /** - * {@link MiriamType#CHEBI}. - */ - CHEBI("Chebi", MiriamType.CHEBI), - - /** - * {@link MiriamType#CHEMBL_COMPOUND}. - */ - CHEMBL_COMPOUND(null, MiriamType.CHEMBL_COMPOUND), - - /** - * {@link MiriamType#CHEMBL_TARGET}. - */ - CHEMBL_TARGET(null, MiriamType.CHEMBL_TARGET), - - /** - * {@link MiriamType#CHEMSPIDER}. - */ - CHEMSPIDER("ChemSpider", MiriamType.CHEMSPIDER), - - /** - * {@link MiriamType#EC}. - */ - EC("Enzyme Nomenclature", MiriamType.EC), - - /** - * {@link MiriamType#ENSEMBL}. - */ - ENSEMBL("Ensembl", MiriamType.ENSEMBL), - - /** - * {@link MiriamType#ENTREZ}. - */ - ENTREZ("Entrez Gene", MiriamType.ENTREZ), - - /** - * Alternative name for {@link MiriamType#ENTREZ}. - */ - GEN_BANK("GenBank", MiriamType.ENTREZ), - - /** - * {@link MiriamType#GO}. - */ - GO("GeneOntology", MiriamType.GO), - - /** - * {@link MiriamType#HGNC}. - */ - HGNC("HGNC Accession number", MiriamType.HGNC), - - /** - * {@link MiriamType#HGNC_SYMBOL}. - */ - HGNC_SYMBOL("HGNC", MiriamType.HGNC_SYMBOL), - - /** - * {@link MiriamType#HMDB}. - */ - HMDB("HMDB", MiriamType.HMDB), - - /** - * {@link MiriamType#INTERPRO}. - */ - INTERPRO("InterPro", MiriamType.INTERPRO), - - /** - * {@link MiriamType#MESH_2012}. - */ - MESH_2012(null, MiriamType.MESH_2012), - - /** - * {@link MiriamType#MI_RBASE_SEQUENCE}. - */ - MI_RBASE_SEQUENCE2("miRBase", MiriamType.MI_R_BASE_SEQUENCE), - - /** - * {@link MiriamType#KEGG_COMPOUND}. - */ - KEGG_COMPOUND("KEGG Compound", MiriamType.KEGG_COMPOUND), - - /** - * {@link MiriamType#KEGG_GENES}. - */ - KEGG_GENES("KEGG Genes", MiriamType.KEGG_GENES), - - /** - * {@link MiriamType#KEGG_ORTHOLOGY}. - */ - KEGG_ORTHOLOGY("Kegg ortholog", MiriamType.KEGG_ORTHOLOGY), - - /** - * {@link MiriamType#KEGG_PATHWAY}. - */ - KEGG_PATHWAY("KEGG Pathway", MiriamType.KEGG_PATHWAY), - - /** - * {@link MiriamType#KEGG_REACTION}. - */ - KEGG_REACTION("KEGG Reaction", MiriamType.KEGG_REACTION), - - /** - * {@link MiriamType#MGD}. - */ - MGD("MGI", MiriamType.MGD), - - /** - * {@link MiriamType#MI_RBASE_SEQUENCE}. - */ - MI_RBASE_SEQUENCE("miRBase Sequence", MiriamType.MI_R_BASE_SEQUENCE), - - /** - * {@link MiriamType#PANTHER}. - */ - PANTHER(null, MiriamType.PANTHER), - - /** - * {@link MiriamType#PFAM}. - */ - PFAM("Pfam", MiriamType.PFAM), - - /** - * {@link MiriamType#PHARM}. - */ - PHARM("PharmGKB Pathways", MiriamType.PHARM), - - /** - * {@link MiriamType#PUBCHEM}. - */ - PUBCHEM("PubChem-compound", MiriamType.PUBCHEM), - - /** - * {@link MiriamType#PUBCHEM_SUBSTANCE}. - */ - PUBCHEM_SUBSTANCE("PubChem-substance", MiriamType.PUBCHEM_SUBSTANCE), - - /** - * {@link MiriamType#REACTOME}. - */ - REACTOME("Reactome", MiriamType.REACTOME), - - /** - * {@link MiriamType#REFSEQ}. - */ - REFSEQ("RefSeq", MiriamType.REFSEQ), - - /** - * {@link MiriamType#SGD }. - */ - SGD("SGD", MiriamType.SGD), - - /** - * {@link MiriamType#TAIR_LOCUS}. - */ - TAIR_LOCUS("TAIR", MiriamType.TAIR_LOCUS), - - /** - * {@link MiriamType#UNIPROT}. - */ - UNIPROT("Uniprot-TrEMBL", MiriamType.UNIPROT), - - /** - * {@link MiriamType#UNIPROT_ISOFORM}. - */ - UNIPROT_ISOFORM(null, MiriamType.UNIPROT_ISOFORM), - - /** - * {@link MiriamType#WIKIPATHWAYS}. - */ - WIKIPATHWAYS("Wikipathways", MiriamType.WIKIPATHWAYS), - - /** - * {@link MiriamType#WIKIPEDIA}. - */ - WIKIPEDIA("Wikipedia", MiriamType.WIKIPEDIA); - - /** - * Gpml string representing specific database type. - */ - private String gpmlString; - - /** - * {@link MiriamType} corresponding to {@link #gpmlString}. - */ - private MiriamType type; - - /** - * Default constructor. - * - * @param gpmlString - * {@link #getGpmlString()} - * @param type - * {@link #type} - */ - ReferenceMapping(String gpmlString, MiriamType type) { - this.type = type; - this.gpmlString = gpmlString; - } - - /** - * @return the gpmlString - * @see #gpmlString - */ - public String getGpmlString() { - return gpmlString; - } - - /** - * @return the type - * @see #type - */ - public MiriamType getType() { - return type; - } - - /** - * Returns {@link ReferenceMapping mapping} to {@link MiriamType} that should - * be used for gpml resource type. - * - * @param gpmlString - * {@link #gpmlString} - * @return {@link ReferenceMapping mapping} to {@link MiriamType} that should - * be used for gpml resource type - */ - public static ReferenceMapping getMappingByGpmlString(String gpmlString) { - for (ReferenceMapping mm : values()) { - if (mm.getGpmlString() != null && mm.getGpmlString().equals(gpmlString)) { - return mm; - } - } - return null; - } - - /** - * Returns {@link ReferenceMapping mapping} that should be used for - * {@link #gpmlString gpml string} representing type of annotation. - * - * @param dataType - * {@link #type} - * - * @return {@link ReferenceMapping mapping} that should be used for - * {@link #gpmlString gpml string} representing type of annotation - */ - public static ReferenceMapping getMappingByMiriamType(MiriamType dataType) { - for (ReferenceMapping mm : values()) { - if (mm.getType().equals(dataType)) { - return mm; - } - } - return null; - } + /** + * {@link MiriamType#CAS}. + */ + CAS("CAS", MiriamType.CAS), + + /** + * {@link MiriamType#CHEBI}. + */ + CHEBI("Chebi", MiriamType.CHEBI), + + /** + * {@link MiriamType#CHEMBL_COMPOUND}. + */ + CHEMBL_COMPOUND(null, MiriamType.CHEMBL_COMPOUND), + + /** + * {@link MiriamType#CHEMBL_TARGET}. + */ + CHEMBL_TARGET(null, MiriamType.CHEMBL_TARGET), + + /** + * {@link MiriamType#CHEMSPIDER}. + */ + CHEMSPIDER("ChemSpider", MiriamType.CHEMSPIDER), + + /** + * {@link MiriamType#EC}. + */ + EC("Enzyme Nomenclature", MiriamType.EC), + + /** + * {@link MiriamType#ENSEMBL}. + */ + ENSEMBL("Ensembl", MiriamType.ENSEMBL), + + /** + * {@link MiriamType#ENTREZ}. + */ + ENTREZ("Entrez Gene", MiriamType.ENTREZ), + + /** + * Alternative name for {@link MiriamType#ENTREZ}. + */ + GEN_BANK("GenBank", MiriamType.ENTREZ), + + /** + * {@link MiriamType#GO}. + */ + GO("GeneOntology", MiriamType.GO), + + /** + * {@link MiriamType#HGNC}. + */ + HGNC("HGNC Accession number", MiriamType.HGNC), + + /** + * {@link MiriamType#HGNC_SYMBOL}. + */ + HGNC_SYMBOL("HGNC", MiriamType.HGNC_SYMBOL), + + /** + * {@link MiriamType#HMDB}. + */ + HMDB("HMDB", MiriamType.HMDB), + + /** + * {@link MiriamType#INTERPRO}. + */ + INTERPRO("InterPro", MiriamType.INTERPRO), + + /** + * {@link MiriamType#MESH_2012}. + */ + MESH_2012(null, MiriamType.MESH_2012), + + /** + * {@link MiriamType#MI_RBASE_SEQUENCE}. + */ + MI_RBASE_SEQUENCE2("miRBase", MiriamType.MI_R_BASE_SEQUENCE), + + /** + * {@link MiriamType#KEGG_COMPOUND}. + */ + KEGG_COMPOUND("KEGG Compound", MiriamType.KEGG_COMPOUND), + + /** + * {@link MiriamType#KEGG_GENES}. + */ + KEGG_GENES("KEGG Genes", MiriamType.KEGG_GENES), + + /** + * {@link MiriamType#KEGG_ORTHOLOGY}. + */ + KEGG_ORTHOLOGY("Kegg ortholog", MiriamType.KEGG_ORTHOLOGY), + + /** + * {@link MiriamType#KEGG_PATHWAY}. + */ + KEGG_PATHWAY("KEGG Pathway", MiriamType.KEGG_PATHWAY), + + /** + * {@link MiriamType#KEGG_REACTION}. + */ + KEGG_REACTION("KEGG Reaction", MiriamType.KEGG_REACTION), + + /** + * {@link MiriamType#MGD}. + */ + MGD("MGI", MiriamType.MGD), + + /** + * {@link MiriamType#MI_RBASE_SEQUENCE}. + */ + MI_RBASE_SEQUENCE("miRBase Sequence", MiriamType.MI_R_BASE_SEQUENCE), + + /** + * {@link MiriamType#PANTHER}. + */ + PANTHER(null, MiriamType.PANTHER), + + /** + * {@link MiriamType#PFAM}. + */ + PFAM("Pfam", MiriamType.PFAM), + + /** + * {@link MiriamType#PHARM}. + */ + PHARM("PharmGKB Pathways", MiriamType.PHARM), + + /** + * {@link MiriamType#PUBCHEM}. + */ + PUBCHEM("PubChem-compound", MiriamType.PUBCHEM), + + /** + * {@link MiriamType#PUBCHEM_SUBSTANCE}. + */ + PUBCHEM_SUBSTANCE("PubChem-substance", MiriamType.PUBCHEM_SUBSTANCE), + + /** + * {@link MiriamType#REACTOME}. + */ + REACTOME("Reactome", MiriamType.REACTOME), + + /** + * {@link MiriamType#REFSEQ}. + */ + REFSEQ("RefSeq", MiriamType.REFSEQ), + + /** + * {@link MiriamType#SGD }. + */ + SGD("SGD", MiriamType.SGD), + + /** + * {@link MiriamType#TAIR_LOCUS}. + */ + TAIR_LOCUS("TAIR", MiriamType.TAIR_LOCUS), + + /** + * {@link MiriamType#UNIPROT}. + */ + UNIPROT("Uniprot-TrEMBL", MiriamType.UNIPROT), + + /** + * {@link MiriamType#UNIPROT_ISOFORM}. + */ + UNIPROT_ISOFORM(null, MiriamType.UNIPROT_ISOFORM), + + /** + * {@link MiriamType#WIKIPATHWAYS}. + */ + WIKIPATHWAYS("Wikipathways", MiriamType.WIKIPATHWAYS), + + /** + * {@link MiriamType#WIKIPEDIA}. + */ + WIKIPEDIA("Wikipedia", MiriamType.WIKIPEDIA); + + /** + * Gpml string representing specific database type. + */ + private String gpmlString; + + /** + * {@link MiriamType} corresponding to {@link #gpmlString}. + */ + private MiriamType type; + + /** + * Default constructor. + * + * @param gpmlString + * {@link #getGpmlString()} + * @param type + * {@link #type} + */ + ReferenceMapping(String gpmlString, MiriamType type) { + this.type = type; + this.gpmlString = gpmlString; + } + + /** + * Returns {@link ReferenceMapping mapping} to {@link MiriamType} that should be + * used for gpml resource type. + * + * @param gpmlString + * {@link #gpmlString} + * @return {@link ReferenceMapping mapping} to {@link MiriamType} that should be + * used for gpml resource type + */ + public static ReferenceMapping getMappingByGpmlString(String gpmlString) { + for (ReferenceMapping mm : values()) { + if (mm.getGpmlString() != null && mm.getGpmlString().equals(gpmlString)) { + return mm; + } + } + return null; + } + + /** + * Returns {@link ReferenceMapping mapping} that should be used for + * {@link #gpmlString gpml string} representing type of annotation. + * + * @param dataType + * {@link #type} + * + * @return {@link ReferenceMapping mapping} that should be used for + * {@link #gpmlString gpml string} representing type of annotation + */ + public static ReferenceMapping getMappingByMiriamType(MiriamType dataType) { + for (ReferenceMapping mm : values()) { + if (mm.getType().equals(dataType)) { + return mm; + } + } + return null; + } + + /** + * @return the gpmlString + * @see #gpmlString + */ + public String getGpmlString() { + return gpmlString; + } + + /** + * @return the type + * @see #type + */ + public MiriamType getType() { + return type; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Shape.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Shape.java index db68dc2c69..8755fc2ebc 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Shape.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/Shape.java @@ -8,217 +8,217 @@ package lcsb.mapviewer.wikipathway.model; */ public class Shape extends GraphicalPathwayElement { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Shape of the node. ??? - */ - private String shape; - - /** - * ??? - */ - private String textLabel; - - /** - * Where this node belongs to. - */ - private String groupRef; - - /** - * Is shape a compartment. - */ - private Boolean compartment; - - /** - * Thickness of the line used for drawing shape. - */ - private Double lineThickness; - - /** - * Align of the description. - */ - private String vAlign; - - /** - * Rotation of the element. - */ - private Double rotation; - - /** - * Sometimes {@link Shape labels} are connected to reactions. - */ - private boolean treatAsNode = false; - - /** - * Default constructor. - * - * @param graphId - * {@link PathwayElement#graphId} - */ - public Shape(String graphId) { - super(graphId); - setRectangle(null); - setShape(null); - setTextLabel(null); - setGroupRef(null); - setCompartment(false); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected Shape() { - } - - @Override - public String getName() { - return shape + ":" + textLabel; - } - - /** - * @return the shape - * @see #shape - */ - public String getShape() { - return shape; - } - - /** - * @param shape - * the shape to set - * @see #shape - */ - public void setShape(String shape) { - this.shape = shape; - } - - /** - * @return the textLabel - * @see #textLabel - */ - public String getTextLabel() { - return textLabel; - } - - /** - * @param textLabel - * the textLabel to set - * @see #textLabel - */ - public void setTextLabel(String textLabel) { - this.textLabel = textLabel; - } - - /** - * @param groupRef - * the groupRef to set - * @see #groupRef - */ - public void setGroupRef(String groupRef) { - this.groupRef = groupRef; - } - - /** - * @return the compartment - * @see #compartment - */ - public Boolean isCompartment() { - return compartment; - } - - /** - * @param compartment - * the compartment to set - * @see #compartment - */ - public void setCompartment(Boolean compartment) { - this.compartment = compartment; - } - - @Override - public String getWarningPrefix() { - return "[" + getShape() + " " + getGraphId() + "]\t"; - } - - /** - * @return the groupRef - * @see #groupRef - */ - public String getGroupRef() { - return groupRef; - } - - /** - * @return the vAlign - * @see #vAlign - */ - public String getvAlign() { - return vAlign; - } - - /** - * @param vAlign - * the vAlign to set - * @see #vAlign - */ - public void setvAlign(String vAlign) { - this.vAlign = vAlign; - } - - /** - * @return the rotation - * @see #rotation - */ - public Double getRotation() { - return rotation; - } - - /** - * @param rotation - * the rotation to set - * @see #rotation - */ - public void setRotation(Double rotation) { - this.rotation = rotation; - } - - /** - * @return the lineThickness - * @see #lineThickness - */ - public Double getLineThickness() { - return lineThickness; - } - - /** - * @param lineThickness - * the lineThickness to set - * @see #lineThickness - */ - public void setLineThickness(Double lineThickness) { - this.lineThickness = lineThickness; - } - - /** - * @return the treatAsNode - * @see #treatAsNode - */ - public boolean isTreatAsNode() { - return treatAsNode; - } - - /** - * @param treatAsNode - * the treatAsNode to set - * @see #treatAsNode - */ - public void setTreatAsNode(boolean treatAsNode) { - this.treatAsNode = treatAsNode; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Shape of the node. ??? + */ + private String shape; + + /** + * ??? + */ + private String textLabel; + + /** + * Where this node belongs to. + */ + private String groupRef; + + /** + * Is shape a compartment. + */ + private Boolean compartment; + + /** + * Thickness of the line used for drawing shape. + */ + private Double lineThickness; + + /** + * Align of the description. + */ + private String vAlign; + + /** + * Rotation of the element. + */ + private Double rotation; + + /** + * Sometimes {@link Shape labels} are connected to reactions. + */ + private boolean treatAsNode = false; + + /** + * Default constructor. + * + * @param graphId + * {@link PathwayElement#graphId} + */ + public Shape(String graphId) { + super(graphId); + setRectangle(null); + setShape(null); + setTextLabel(null); + setGroupRef(null); + setCompartment(false); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected Shape() { + } + + @Override + public String getName() { + return shape + ":" + textLabel; + } + + @Override + public String getWarningPrefix() { + return "[" + getShape() + " " + getGraphId() + "]\t"; + } + + /** + * @return the shape + * @see #shape + */ + public String getShape() { + return shape; + } + + /** + * @param shape + * the shape to set + * @see #shape + */ + public void setShape(String shape) { + this.shape = shape; + } + + /** + * @return the textLabel + * @see #textLabel + */ + public String getTextLabel() { + return textLabel; + } + + /** + * @param textLabel + * the textLabel to set + * @see #textLabel + */ + public void setTextLabel(String textLabel) { + this.textLabel = textLabel; + } + + /** + * @return the compartment + * @see #compartment + */ + public Boolean isCompartment() { + return compartment; + } + + /** + * @param compartment + * the compartment to set + * @see #compartment + */ + public void setCompartment(Boolean compartment) { + this.compartment = compartment; + } + + /** + * @return the groupRef + * @see #groupRef + */ + public String getGroupRef() { + return groupRef; + } + + /** + * @param groupRef + * the groupRef to set + * @see #groupRef + */ + public void setGroupRef(String groupRef) { + this.groupRef = groupRef; + } + + /** + * @return the vAlign + * @see #vAlign + */ + public String getvAlign() { + return vAlign; + } + + /** + * @param vAlign + * the vAlign to set + * @see #vAlign + */ + public void setvAlign(String vAlign) { + this.vAlign = vAlign; + } + + /** + * @return the rotation + * @see #rotation + */ + public Double getRotation() { + return rotation; + } + + /** + * @param rotation + * the rotation to set + * @see #rotation + */ + public void setRotation(Double rotation) { + this.rotation = rotation; + } + + /** + * @return the lineThickness + * @see #lineThickness + */ + public Double getLineThickness() { + return lineThickness; + } + + /** + * @param lineThickness + * the lineThickness to set + * @see #lineThickness + */ + public void setLineThickness(Double lineThickness) { + this.lineThickness = lineThickness; + } + + /** + * @return the treatAsNode + * @see #treatAsNode + */ + public boolean isTreatAsNode() { + return treatAsNode; + } + + /** + * @param treatAsNode + * the treatAsNode to set + * @see #treatAsNode + */ + public void setTreatAsNode(boolean treatAsNode) { + this.treatAsNode = treatAsNode; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/State.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/State.java index 7447a82d5f..23bdb2e653 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/State.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/State.java @@ -17,243 +17,245 @@ import lcsb.mapviewer.model.map.species.field.ModificationState; */ public class State extends GraphicalPathwayElement { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Shape of the element. - */ - private String shape; - - /** - * References for given edge. - */ - private List<MiriamData> references = new ArrayList<>(); - - /** - * Object where this state is placed. - */ - private String graphRef; - - /** - * State correspondig to {@link Protein#structuralState protein structural state}. - */ - private String structuralState; - - /** - * Type of the modification. - */ - private ModificationState type; - - /** - * X position on {@link #graphRef} element. - */ - private Double relX; - - /** - * Y position on {@link #graphRef} element. - */ - private Double relY; - - /** - * Width of the element. - */ - private Double width; - - /** - * Heightof the element. - */ - private Double height; - - /** - * Default constructor. - * - * @param graphId - * {@link PathwayElement#graphId} - */ - public State(String graphId) { - super(graphId); - } - - /** - * Empty constructor that should be used only by serialization tools and - * subclasses. - */ - protected State() { - } - - @Override - String getName() { - throw new NotImplementedException(); - } - - @Override - public Rectangle2D getRectangle() { - throw new NotImplementedException(); - } - - /** - * @return the shape - * @see #shape - */ - public String getShape() { - return shape; - } - - /** - * @param shape - * the shape to set - * @see #shape - */ - public void setShape(String shape) { - this.shape = shape; - } - - /** - * @return the relX - * @see #relX - */ - public Double getRelX() { - return relX; - } - - /** - * @param relX - * the relX to set - * @see #relX - */ - public void setRelX(Double relX) { - this.relX = relX; - } - - /** - * @return the relY - * @see #relY - */ - public Double getRelY() { - return relY; - } - - /** - * @param relY - * the relY to set - * @see #relY - */ - public void setRelY(Double relY) { - this.relY = relY; - } - - /** - * @return the width - * @see #width - */ - public Double getWidth() { - return width; - } - - /** - * @param width - * the width to set - * @see #width - */ - public void setWidth(Double width) { - this.width = width; - } - - /** - * @return the height - * @see #height - */ - public Double getHeight() { - return height; - } - - /** - * @param height - * the height to set - * @see #height - */ - public void setHeight(Double height) { - this.height = height; - } - - /** - * @return the graphRef - * @see #graphRef - */ - public String getGraphRef() { - return graphRef; - } - - /** - * @param graphRef - * the graphRef to set - * @see #graphRef - */ - public void setGraphRef(String graphRef) { - this.graphRef = graphRef; - } - - /** - * @return the references - * @see #references - */ - public List<MiriamData> getReferences() { - return references; - } - - /** - * @param references - * the references to set - * @see #references - */ - public void setReferences(List<MiriamData> references) { - this.references = references; - } - - /** - * Adds reference to object. - * - * @param reference - * reference to add - */ - public void addReference(MiriamData reference) { - this.references.add(reference); - } - - /** - * @return the type - * @see #type - */ - public ModificationState getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(ModificationState type) { - this.type = type; - } - - /** - * @return the structuralState - * @see #structuralState - */ - public String getStructuralState() { - return structuralState; - } - - /** - * @param structuralState the structuralState to set - * @see #structuralState - */ - public void setStructuralState(String structuralState) { - this.structuralState = structuralState; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Shape of the element. + */ + private String shape; + + /** + * References for given edge. + */ + private List<MiriamData> references = new ArrayList<>(); + + /** + * Object where this state is placed. + */ + private String graphRef; + + /** + * State correspondig to {@link Protein#structuralState protein structural + * state}. + */ + private String structuralState; + + /** + * Type of the modification. + */ + private ModificationState type; + + /** + * X position on {@link #graphRef} element. + */ + private Double relX; + + /** + * Y position on {@link #graphRef} element. + */ + private Double relY; + + /** + * Width of the element. + */ + private Double width; + + /** + * Heightof the element. + */ + private Double height; + + /** + * Default constructor. + * + * @param graphId + * {@link PathwayElement#graphId} + */ + public State(String graphId) { + super(graphId); + } + + /** + * Empty constructor that should be used only by serialization tools and + * subclasses. + */ + protected State() { + } + + @Override + String getName() { + throw new NotImplementedException(); + } + + @Override + public Rectangle2D getRectangle() { + throw new NotImplementedException(); + } + + /** + * @return the shape + * @see #shape + */ + public String getShape() { + return shape; + } + + /** + * @param shape + * the shape to set + * @see #shape + */ + public void setShape(String shape) { + this.shape = shape; + } + + /** + * @return the relX + * @see #relX + */ + public Double getRelX() { + return relX; + } + + /** + * @param relX + * the relX to set + * @see #relX + */ + public void setRelX(Double relX) { + this.relX = relX; + } + + /** + * @return the relY + * @see #relY + */ + public Double getRelY() { + return relY; + } + + /** + * @param relY + * the relY to set + * @see #relY + */ + public void setRelY(Double relY) { + this.relY = relY; + } + + /** + * @return the width + * @see #width + */ + public Double getWidth() { + return width; + } + + /** + * @param width + * the width to set + * @see #width + */ + public void setWidth(Double width) { + this.width = width; + } + + /** + * @return the height + * @see #height + */ + public Double getHeight() { + return height; + } + + /** + * @param height + * the height to set + * @see #height + */ + public void setHeight(Double height) { + this.height = height; + } + + /** + * @return the graphRef + * @see #graphRef + */ + public String getGraphRef() { + return graphRef; + } + + /** + * @param graphRef + * the graphRef to set + * @see #graphRef + */ + public void setGraphRef(String graphRef) { + this.graphRef = graphRef; + } + + /** + * @return the references + * @see #references + */ + public List<MiriamData> getReferences() { + return references; + } + + /** + * @param references + * the references to set + * @see #references + */ + public void setReferences(List<MiriamData> references) { + this.references = references; + } + + /** + * Adds reference to object. + * + * @param reference + * reference to add + */ + public void addReference(MiriamData reference) { + this.references.add(reference); + } + + /** + * @return the type + * @see #type + */ + public ModificationState getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(ModificationState type) { + this.type = type; + } + + /** + * @return the structuralState + * @see #structuralState + */ + public String getStructuralState() { + return structuralState; + } + + /** + * @param structuralState + * the structuralState to set + * @see #structuralState + */ + public void setStructuralState(String structuralState) { + this.structuralState = structuralState; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/UnknownTypeException.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/UnknownTypeException.java index f648725fbb..a5af942d9b 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/UnknownTypeException.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/UnknownTypeException.java @@ -10,19 +10,19 @@ import lcsb.mapviewer.converter.ConverterException; */ public class UnknownTypeException extends ConverterException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor with message passed in the argument. - * - * @param string - * message of this exception - */ - public UnknownTypeException(String string) { - super(string); - } + /** + * Default constructor with message passed in the argument. + * + * @param string + * message of this exception + */ + public UnknownTypeException(String string) { + super(string); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxData.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxData.java index 3cd84eb8e5..48b8c782c2 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxData.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxData.java @@ -1,15 +1,12 @@ package lcsb.mapviewer.wikipathway.model.biopax; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; -import lcsb.mapviewer.common.exception.InvalidArgumentException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; -import org.apache.logging.log4j.*; +import lcsb.mapviewer.common.exception.InvalidArgumentException; /** * Element containg all biopax information parsed from gpml file. @@ -19,74 +16,74 @@ import org.apache.logging.log4j.*; */ public class BiopaxData implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final transient Logger logger = LogManager.getLogger(BiopaxData.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final transient Logger logger = LogManager.getLogger(BiopaxData.class); - /** - * List of {@link BiopaxPublication publications}. - */ - private Map<String, BiopaxPublication> publications = new HashMap<String, BiopaxPublication>(); + /** + * List of {@link BiopaxPublication publications}. + */ + private Map<String, BiopaxPublication> publications = new HashMap<String, BiopaxPublication>(); - /** - * List of {@link BiopaxOpenControlledVocabulary biopax vocabulary}. - */ - private List<BiopaxOpenControlledVocabulary> openControlledVocabularies = new ArrayList<BiopaxOpenControlledVocabulary>(); + /** + * List of {@link BiopaxOpenControlledVocabulary biopax vocabulary}. + */ + private List<BiopaxOpenControlledVocabulary> openControlledVocabularies = new ArrayList<BiopaxOpenControlledVocabulary>(); - /** - * @return the publications - * @see #publications - */ - public Collection<BiopaxPublication> getPublications() { - return publications.values(); - } + /** + * @return the publications + * @see #publications + */ + public Collection<BiopaxPublication> getPublications() { + return publications.values(); + } - /** - * @param publication - * the publication to add - * @see #publications - */ - public void addPublication(BiopaxPublication publication) { - String id = publication.getReferenceId(); - if (this.publications.get(publication.getReferenceId()) != null) { - throw new InvalidArgumentException("Biopax publication with " + id + " already exists."); - } - this.publications.put(id, publication); - } + /** + * @param publication + * the publication to add + * @see #publications + */ + public void addPublication(BiopaxPublication publication) { + String id = publication.getReferenceId(); + if (this.publications.get(publication.getReferenceId()) != null) { + throw new InvalidArgumentException("Biopax publication with " + id + " already exists."); + } + this.publications.put(id, publication); + } - /** - * Returns publication identified by reference id. - * - * @param ref - * reference identifier - * @return {@link BiopaxPublication} corresponding to the ref - */ - public BiopaxPublication getPublicationByReference(String ref) { - return publications.get(ref); - } + /** + * Returns publication identified by reference id. + * + * @param ref + * reference identifier + * @return {@link BiopaxPublication} corresponding to the ref + */ + public BiopaxPublication getPublicationByReference(String ref) { + return publications.get(ref); + } - /** - * @return the openControlledVocabularies - * @see #openControlledVocabularies - */ - public List<BiopaxOpenControlledVocabulary> getOpenControlledVocabularies() { - return openControlledVocabularies; - } + /** + * @return the openControlledVocabularies + * @see #openControlledVocabularies + */ + public List<BiopaxOpenControlledVocabulary> getOpenControlledVocabularies() { + return openControlledVocabularies; + } - /** - * @param openControlledVocabulary - * the openControlledVocabulary to add - * @see #openControlledVocabularies - */ - public void addOpenControlledVocabulary(BiopaxOpenControlledVocabulary openControlledVocabulary) { - this.openControlledVocabularies.add(openControlledVocabulary); - } + /** + * @param openControlledVocabulary + * the openControlledVocabulary to add + * @see #openControlledVocabularies + */ + public void addOpenControlledVocabulary(BiopaxOpenControlledVocabulary openControlledVocabulary) { + this.openControlledVocabularies.add(openControlledVocabulary); + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabulary.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabulary.java index 53804781d7..e7aabeee53 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabulary.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxOpenControlledVocabulary.java @@ -10,76 +10,75 @@ import java.io.Serializable; * */ public class BiopaxOpenControlledVocabulary implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * ??? - */ - private String id; - - /** - * ??? - */ - private String term; - - /** - * ??? - */ - private String ontology; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * @return the id - * @see #id - */ - public String getId() { - return id; - } + /** + * ??? + */ + private String id; - /** - * @param id - * the id to set - * @see #id - */ - public void setId(String id) { - this.id = id; - } + /** + * ??? + */ + private String term; - /** - * @return the term - * @see #term - */ - public String getTerm() { - return term; - } + /** + * ??? + */ + private String ontology; - /** - * @param term - * the term to set - * @see #term - */ - public void setTerm(String term) { - this.term = term; - } + /** + * @return the id + * @see #id + */ + public String getId() { + return id; + } - /** - * @return the ontology - * @see #ontology - */ - public String getOntology() { - return ontology; - } + /** + * @param id + * the id to set + * @see #id + */ + public void setId(String id) { + this.id = id; + } - /** - * @param ontology - * the ontology to set - * @see #ontology - */ - public void setOntology(String ontology) { - this.ontology = ontology; - } + /** + * @return the term + * @see #term + */ + public String getTerm() { + return term; + } + + /** + * @param term + * the term to set + * @see #term + */ + public void setTerm(String term) { + this.term = term; + } + + /** + * @return the ontology + * @see #ontology + */ + public String getOntology() { + return ontology; + } + + /** + * @param ontology + * the ontology to set + * @see #ontology + */ + public void setOntology(String ontology) { + this.ontology = ontology; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublication.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublication.java index cb561ad58e..7960830511 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublication.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/BiopaxPublication.java @@ -9,164 +9,163 @@ import java.io.Serializable; * */ public class BiopaxPublication implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - /** - * Identifier of a publication in db. - */ - private String id; - - /** - * Database where publication is located. - */ - private String db; - - /** - * Title of publication. - */ - private String title; - - /** - * Source of the publication. - */ - private String source; - - /** - * Year when publication was issued. - */ - private String year; - - /** - * Authors of the publication. - */ - private String authors; - - /** - * Identifier of the object which this publication annotate. - */ - private String referenceId; - - /** - * @return the id - * @see #id - */ - public String getId() { - return id; - } - - /** - * @param id - * the id to set - * @see #id - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the db - * @see #db - */ - public String getDb() { - return db; - } - - /** - * @param db - * the db to set - * @see #db - */ - public void setDb(String db) { - this.db = db; - } - - /** - * @return the title - * @see #title - */ - public String getTitle() { - return title; - } - - /** - * @param title - * the title to set - * @see #title - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * @return the source - * @see #source - */ - public String getSource() { - return source; - } - - /** - * @param source - * the source to set - * @see #source - */ - public void setSource(String source) { - this.source = source; - } - - /** - * @return the year - * @see #year - */ - public String getYear() { - return year; - } - - /** - * @param year - * the year to set - * @see #year - */ - public void setYear(String year) { - this.year = year; - } - - /** - * @return the authors - * @see #authors - */ - public String getAuthors() { - return authors; - } - - /** - * @param authors - * the authors to set - * @see #authors - */ - public void setAuthors(String authors) { - this.authors = authors; - } - - /** - * @return the referenceId - * @see #referenceId - */ - public String getReferenceId() { - return referenceId; - } - - /** - * @param referenceId - * the referenceId to set - * @see #referenceId - */ - public void setReferenceId(String referenceId) { - this.referenceId = referenceId; - } + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Identifier of a publication in db. + */ + private String id; + + /** + * Database where publication is located. + */ + private String db; + + /** + * Title of publication. + */ + private String title; + + /** + * Source of the publication. + */ + private String source; + + /** + * Year when publication was issued. + */ + private String year; + + /** + * Authors of the publication. + */ + private String authors; + + /** + * Identifier of the object which this publication annotate. + */ + private String referenceId; + + /** + * @return the id + * @see #id + */ + public String getId() { + return id; + } + + /** + * @param id + * the id to set + * @see #id + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the db + * @see #db + */ + public String getDb() { + return db; + } + + /** + * @param db + * the db to set + * @see #db + */ + public void setDb(String db) { + this.db = db; + } + + /** + * @return the title + * @see #title + */ + public String getTitle() { + return title; + } + + /** + * @param title + * the title to set + * @see #title + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * @return the source + * @see #source + */ + public String getSource() { + return source; + } + + /** + * @param source + * the source to set + * @see #source + */ + public void setSource(String source) { + this.source = source; + } + + /** + * @return the year + * @see #year + */ + public String getYear() { + return year; + } + + /** + * @param year + * the year to set + * @see #year + */ + public void setYear(String year) { + this.year = year; + } + + /** + * @return the authors + * @see #authors + */ + public String getAuthors() { + return authors; + } + + /** + * @param authors + * the authors to set + * @see #authors + */ + public void setAuthors(String authors) { + this.authors = authors; + } + + /** + * @return the referenceId + * @see #referenceId + */ + public String getReferenceId() { + return referenceId; + } + + /** + * @param referenceId + * the referenceId to set + * @see #referenceId + */ + public void setReferenceId(String referenceId) { + this.referenceId = referenceId; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/package-info.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/package-info.java index fd3c232c66..59a6d62ae6 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/package-info.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/biopax/package-info.java @@ -4,4 +4,3 @@ * */ package lcsb.mapviewer.wikipathway.model.biopax; - diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/package-info.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/package-info.java index bd59db6b13..64a4c19f86 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/package-info.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/model/package-info.java @@ -2,14 +2,13 @@ * Model elements obtained from gpml file. There are few basic classes in this * package: * <ul> - * <li> {@link lcsb.mapviewer.wikipathway.model.Graph Graph} - description of the + * <li>{@link lcsb.mapviewer.wikipathway.model.Graph Graph} - description of the * whole model imported from gpml file,</li> - * <li> {@link lcsb.mapviewer.wikipathway.model.Interaction Interaction} - + * <li>{@link lcsb.mapviewer.wikipathway.model.Interaction Interaction} - * description of single interaction in the model,</li> - * <li> {@link lcsb.mapviewer.wikipathway.model.PathwayElement PathwayElement} - + * <li>{@link lcsb.mapviewer.wikipathway.model.PathwayElement PathwayElement} - * single element in the model.</li> * </ul> * */ package lcsb.mapviewer.wikipathway.model; - diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/package-info.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/package-info.java index 24f302e3bc..fa582dca17 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/package-info.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/package-info.java @@ -2,9 +2,9 @@ * Contains plugin for pathvisio that supports import and export to CellDEsigner * file. Main plugin class is located in * {@link lcsb.mapviewer.wikipathway.ImportExport ImportExport} class. According - * to <a href="http://developers.pathvisio.org/wiki/PluginDevelopment - * ">pathvisio guidlines</a>, plugin is implemented as an <a - * href="http://en.wikipedia.org/wiki/OSGi#Bundles">OSGI Bundle</a>. + * to + * <a href="http://developers.pathvisio.org/wiki/PluginDevelopment ">pathvisio + * guidlines</a>, plugin is implemented as an + * <a href="http://en.wikipedia.org/wiki/OSGi#Bundles">OSGI Bundle</a>. */ package lcsb.mapviewer.wikipathway; - diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/Geo.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/Geo.java index 3101d56c6f..71d92007b1 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/Geo.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/Geo.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.wikipathway.utils; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; +import java.awt.geom.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidStateException; @@ -16,311 +14,312 @@ import lcsb.mapviewer.model.graphics.PolylineData; */ public final class Geo { - /** - * Max distance betwen point and line that still allows to match intersection. - */ - private static final int DISTANCE_PROXIMITY = 10; - - /** - * Default class constructor. Prevents instatiation. - */ - private Geo() { - - } - - /** - * This function calculates point on line that is closest to given point. - * - * @param line - * - line has to be parallel to oX or oY - * @param point - * point - * @return point on line that is closest to given point - */ - private static Point2D closestPointOnLine(Line2D line, Point2D point) { - Point2D s = line.getP1(); - Point2D e = line.getP2(); - if (s.equals(e)) { - return (Point2D) s.clone(); - } - - if (s.getX() == e.getX()) { - if (point.getY() > Math.min(s.getY(), e.getY()) && point.getY() < Math.max(s.getY(), e.getY())) { - return new Point2D.Double(s.getX(), point.getY()); - } else { - if (point.distance(s) < point.distance(e)) { - return (Point2D) s.clone(); - } else { - return (Point2D) e.clone(); - } - } - } else if (s.getY() == e.getY()) { - if (point.getX() > Math.min(s.getX(), e.getX()) && point.getX() < Math.max(s.getX(), e.getX())) { - return new Point2D.Double(point.getX(), s.getY()); - } else { - if (point.distance(s) < point.distance(e)) { - return (Point2D) s.clone(); - } else { - return (Point2D) e.clone(); - } - } - } else { - throw new InvalidArgumentException("Line is invalid"); - } - } - - /** - * This function return value from <0,1>, that is the position of given point - * on given Polyline. - * - * @param mainLine - * line on which we are looking for a point - * @param point - * point - * @return double position, 0 <= position <= 1 - */ - public static double distanceOnPolyline(PolylineData mainLine, Point2D point) { - double length = 0; - double tmp = 0; - for (Line2D line : mainLine.getLines()) { - length += lineLen(line); - } - - for (Line2D line : mainLine.getLines()) { - if (line.ptSegDist(point) < DISTANCE_PROXIMITY) { - tmp += line.getP1().distance(point); - break; - } else { - tmp += lineLen(line); - } - } - double position = tmp / length; - if (position < 0 || position > 1) { - throw new InvalidStateException(); - } - return position; - } - - /** - * Returns length of the line. - * - * @param line - * line - * @return length of the line - */ - public static double lineLen(Line2D line) { - return line.getP1().distance(line.getP2()); - } - - /** - * Returns distance between point and rectangle border. - * - * @param point - * point - * @param rect - * rectangle border - * @return distance between point and rectangle border - */ - public static double distance(Point2D point, Rectangle2D rect) { - double res = Double.MAX_VALUE; - - Point2D p1 = new Point2D.Double(rect.getX(), rect.getY()); - Point2D p2 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); - Point2D p3 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); - Point2D p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); - res = Math.min(res, new Line2D.Double(p1, p2).ptSegDist(point)); - res = Math.min(res, new Line2D.Double(p2, p3).ptSegDist(point)); - res = Math.min(res, new Line2D.Double(p3, p4).ptSegDist(point)); - res = Math.min(res, new Line2D.Double(p4, p1).ptSegDist(point)); - - return res; - } - - /** - * This function returns point on the middle of rectangle side, that is - * closest to the given point. - * - * @param rect - * rectangle on which we look for a point - * @param point - * point to which result should be as close as possible - * @return point on the middle of rectangle side that is as close as possible - * to the input point - */ - public static Point2D pointOnRectangle(Rectangle2D rect, Point2D point) { - - Point2D p1 = new Point2D.Double(rect.getX(), rect.getY()); - Point2D p2 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); - Point2D p3 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); - Point2D p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); - - Point2D p12 = new Point2D.Double((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2); - Point2D p23 = new Point2D.Double((p2.getX() + p3.getX()) / 2, (p2.getY() + p3.getY()) / 2); - Point2D p34 = new Point2D.Double((p3.getX() + p4.getX()) / 2, (p3.getY() + p4.getY()) / 2); - Point2D p41 = new Point2D.Double((p4.getX() + p1.getX()) / 2, (p4.getY() + p1.getY()) / 2); - - double dis1, dis2, dis3, dis4, min; - dis1 = point.distance(p12); - dis2 = point.distance(p23); - dis3 = point.distance(p34); - dis4 = point.distance(p41); - - min = Math.min(dis1, dis2); - min = Math.min(min, dis3); - min = Math.min(min, dis4); - - if (min == dis1) { - return p12; - } else if (min == dis2) { - return p23; - } else if (min == dis3) { - return p34; - } else { - return p41; - } - } - - /** - * This function returns point on rectangle that is closest to given point. - * - * @param rect - * rectangle on which the result poiint will be placed - * @param point - * point for which we look the closest reference on rectangle - * @return the closest possible point on rectangle - */ - public static Point2D closestPointOnRectangle(Rectangle2D rect, Point2D point) { - Point2D p1 = new Point2D.Double(rect.getX(), rect.getY()); - Point2D p2 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); - Point2D p3 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); - Point2D p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); - - double dis1, dis2, dis3, dis4, min; - dis1 = new Line2D.Double(p1, p2).ptSegDist(point); - dis2 = new Line2D.Double(p2, p3).ptSegDist(point); - dis3 = new Line2D.Double(p3, p4).ptSegDist(point); - dis4 = new Line2D.Double(p4, p1).ptSegDist(point); - min = Math.min(dis1, dis2); - min = Math.min(min, dis3); - min = Math.min(min, dis4); - - if (min == dis1) { - return closestPointOnLine(new Line2D.Double(p1, p2), point); - } else if (min == dis2) { - return closestPointOnLine(new Line2D.Double(p2, p3), point); - } else if (min == dis3) { - return closestPointOnLine(new Line2D.Double(p3, p4), point); - } else { - return closestPointOnLine(new Line2D.Double(p4, p1), point); - } - } - - /** - * Returns point that is outside given rectangle, but still close to the given - * point. If the given point is inside rec then the given point is returned. - * - * @param rec - * rectangle - * @param point - * point - * @return point that is outside given rectangle, but still close to the given - * point - */ - public static Point2D pointRightOutsideRec(Rectangle2D rec, Point2D point) { - if (!rec.contains(point)) { - return (Point2D) point.clone(); - } else { - double lx = rec.getX(); - double rx = lx + rec.getWidth(); - double uy = rec.getY(); - double dy = uy + rec.getHeight(); - - double dis1 = Math.abs(point.getX() - lx); - double dis2 = Math.abs(point.getX() - rx); - double dis3 = Math.abs(point.getY() - uy); - double dis4 = Math.abs(point.getY() - dy); - - double min = Math.min(dis1, dis2); - min = Math.min(min, dis3); - min = Math.min(min, dis4); - - if (min == dis1) { - return new Point2D.Double(lx - 1.0, point.getY()); - } else if (min == dis2) { - return new Point2D.Double(rx + 1.0, point.getY()); - } else if (min == dis3) { - return new Point2D.Double(point.getX(), uy - 1.0); - } else { - return new Point2D.Double(point.getX(), uy + 1.0); - } - } - } - - /** - * Creates a {@link PolylineData} that is identical to parameter line, but - * doesn't contain duplicate points. - * - * @param line - * line that is transformed - * @return input line without duplicate points - */ - public static PolylineData removeRedundantPoints(PolylineData line) { - PolylineData res = new PolylineData(line); - - for (int i = 2; i < res.getPoints().size(); i++) { - if (new Line2D.Double(res.getPoints().get(i), res.getPoints().get(i - 2)).ptSegDist(res.getPoints().get(i - 1)) < DISTANCE_PROXIMITY) { - res.getPoints().remove(i - 1); - i--; - } - } - return res; - } - - /** - * Returns distance between point and line. - * - * @param point - * point - * @param mainLine - * line - * @return distance between point and line - */ - public static double distanceFromPolyline(Point2D point, PolylineData mainLine) { - double min = Double.MAX_VALUE; - for (Line2D line : mainLine.getLines()) { - min = Math.min(min, line.ptSegDist(point)); - } - return min; - } - - /** - * Returns point on line that is as closse as possible to point. - * - * @param point - * point - * @param mainLine - * line - * @return point on line that is as closse as possible to point - */ - public static Point2D closestPointOnPolyline(PolylineData mainLine, Point2D point) { - Point2D res = null; - double distance = distanceOnPolyline(mainLine, point); - double lenght = 0.0; - for (Line2D line : mainLine.getLines()) { - lenght += lineLen(line); - } - lenght *= distance; - for (Line2D line : mainLine.getLines()) { - if (lenght - lineLen(line) > 0) { - lenght -= lineLen(line); - } else { - double tmp = lenght / lineLen(line); - double x = line.getX1() + tmp * (line.getX2() - line.getX1()); - double y = line.getY1() + tmp * (line.getY2() - line.getY1()); - res = new Point2D.Double(x, y); - } - } - return res; - } + /** + * Max distance betwen point and line that still allows to match intersection. + */ + private static final int DISTANCE_PROXIMITY = 10; + + /** + * Default class constructor. Prevents instatiation. + */ + private Geo() { + + } + + /** + * This function calculates point on line that is closest to given point. + * + * @param line + * - line has to be parallel to oX or oY + * @param point + * point + * @return point on line that is closest to given point + */ + private static Point2D closestPointOnLine(Line2D line, Point2D point) { + Point2D s = line.getP1(); + Point2D e = line.getP2(); + if (s.equals(e)) { + return (Point2D) s.clone(); + } + + if (s.getX() == e.getX()) { + if (point.getY() > Math.min(s.getY(), e.getY()) && point.getY() < Math.max(s.getY(), e.getY())) { + return new Point2D.Double(s.getX(), point.getY()); + } else { + if (point.distance(s) < point.distance(e)) { + return (Point2D) s.clone(); + } else { + return (Point2D) e.clone(); + } + } + } else if (s.getY() == e.getY()) { + if (point.getX() > Math.min(s.getX(), e.getX()) && point.getX() < Math.max(s.getX(), e.getX())) { + return new Point2D.Double(point.getX(), s.getY()); + } else { + if (point.distance(s) < point.distance(e)) { + return (Point2D) s.clone(); + } else { + return (Point2D) e.clone(); + } + } + } else { + throw new InvalidArgumentException("Line is invalid"); + } + } + + /** + * This function return value from <0,1>, that is the position of given point on + * given Polyline. + * + * @param mainLine + * line on which we are looking for a point + * @param point + * point + * @return double position, 0 <= position <= 1 + */ + public static double distanceOnPolyline(PolylineData mainLine, Point2D point) { + double length = 0; + double tmp = 0; + for (Line2D line : mainLine.getLines()) { + length += lineLen(line); + } + + for (Line2D line : mainLine.getLines()) { + if (line.ptSegDist(point) < DISTANCE_PROXIMITY) { + tmp += line.getP1().distance(point); + break; + } else { + tmp += lineLen(line); + } + } + double position = tmp / length; + if (position < 0 || position > 1) { + throw new InvalidStateException(); + } + return position; + } + + /** + * Returns length of the line. + * + * @param line + * line + * @return length of the line + */ + public static double lineLen(Line2D line) { + return line.getP1().distance(line.getP2()); + } + + /** + * Returns distance between point and rectangle border. + * + * @param point + * point + * @param rect + * rectangle border + * @return distance between point and rectangle border + */ + public static double distance(Point2D point, Rectangle2D rect) { + double res = Double.MAX_VALUE; + + Point2D p1 = new Point2D.Double(rect.getX(), rect.getY()); + Point2D p2 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); + Point2D p3 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); + Point2D p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); + res = Math.min(res, new Line2D.Double(p1, p2).ptSegDist(point)); + res = Math.min(res, new Line2D.Double(p2, p3).ptSegDist(point)); + res = Math.min(res, new Line2D.Double(p3, p4).ptSegDist(point)); + res = Math.min(res, new Line2D.Double(p4, p1).ptSegDist(point)); + + return res; + } + + /** + * This function returns point on the middle of rectangle side, that is closest + * to the given point. + * + * @param rect + * rectangle on which we look for a point + * @param point + * point to which result should be as close as possible + * @return point on the middle of rectangle side that is as close as possible to + * the input point + */ + public static Point2D pointOnRectangle(Rectangle2D rect, Point2D point) { + + Point2D p1 = new Point2D.Double(rect.getX(), rect.getY()); + Point2D p2 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); + Point2D p3 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); + Point2D p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); + + Point2D p12 = new Point2D.Double((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2); + Point2D p23 = new Point2D.Double((p2.getX() + p3.getX()) / 2, (p2.getY() + p3.getY()) / 2); + Point2D p34 = new Point2D.Double((p3.getX() + p4.getX()) / 2, (p3.getY() + p4.getY()) / 2); + Point2D p41 = new Point2D.Double((p4.getX() + p1.getX()) / 2, (p4.getY() + p1.getY()) / 2); + + double dis1, dis2, dis3, dis4, min; + dis1 = point.distance(p12); + dis2 = point.distance(p23); + dis3 = point.distance(p34); + dis4 = point.distance(p41); + + min = Math.min(dis1, dis2); + min = Math.min(min, dis3); + min = Math.min(min, dis4); + + if (min == dis1) { + return p12; + } else if (min == dis2) { + return p23; + } else if (min == dis3) { + return p34; + } else { + return p41; + } + } + + /** + * This function returns point on rectangle that is closest to given point. + * + * @param rect + * rectangle on which the result poiint will be placed + * @param point + * point for which we look the closest reference on rectangle + * @return the closest possible point on rectangle + */ + public static Point2D closestPointOnRectangle(Rectangle2D rect, Point2D point) { + Point2D p1 = new Point2D.Double(rect.getX(), rect.getY()); + Point2D p2 = new Point2D.Double(rect.getX(), rect.getY() + rect.getHeight()); + Point2D p3 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight()); + Point2D p4 = new Point2D.Double(rect.getX() + rect.getWidth(), rect.getY()); + + double dis1, dis2, dis3, dis4, min; + dis1 = new Line2D.Double(p1, p2).ptSegDist(point); + dis2 = new Line2D.Double(p2, p3).ptSegDist(point); + dis3 = new Line2D.Double(p3, p4).ptSegDist(point); + dis4 = new Line2D.Double(p4, p1).ptSegDist(point); + min = Math.min(dis1, dis2); + min = Math.min(min, dis3); + min = Math.min(min, dis4); + + if (min == dis1) { + return closestPointOnLine(new Line2D.Double(p1, p2), point); + } else if (min == dis2) { + return closestPointOnLine(new Line2D.Double(p2, p3), point); + } else if (min == dis3) { + return closestPointOnLine(new Line2D.Double(p3, p4), point); + } else { + return closestPointOnLine(new Line2D.Double(p4, p1), point); + } + } + + /** + * Returns point that is outside given rectangle, but still close to the given + * point. If the given point is inside rec then the given point is returned. + * + * @param rec + * rectangle + * @param point + * point + * @return point that is outside given rectangle, but still close to the given + * point + */ + public static Point2D pointRightOutsideRec(Rectangle2D rec, Point2D point) { + if (!rec.contains(point)) { + return (Point2D) point.clone(); + } else { + double lx = rec.getX(); + double rx = lx + rec.getWidth(); + double uy = rec.getY(); + double dy = uy + rec.getHeight(); + + double dis1 = Math.abs(point.getX() - lx); + double dis2 = Math.abs(point.getX() - rx); + double dis3 = Math.abs(point.getY() - uy); + double dis4 = Math.abs(point.getY() - dy); + + double min = Math.min(dis1, dis2); + min = Math.min(min, dis3); + min = Math.min(min, dis4); + + if (min == dis1) { + return new Point2D.Double(lx - 1.0, point.getY()); + } else if (min == dis2) { + return new Point2D.Double(rx + 1.0, point.getY()); + } else if (min == dis3) { + return new Point2D.Double(point.getX(), uy - 1.0); + } else { + return new Point2D.Double(point.getX(), uy + 1.0); + } + } + } + + /** + * Creates a {@link PolylineData} that is identical to parameter line, but + * doesn't contain duplicate points. + * + * @param line + * line that is transformed + * @return input line without duplicate points + */ + public static PolylineData removeRedundantPoints(PolylineData line) { + PolylineData res = new PolylineData(line); + + for (int i = 2; i < res.getPoints().size(); i++) { + if (new Line2D.Double(res.getPoints().get(i), res.getPoints().get(i - 2)) + .ptSegDist(res.getPoints().get(i - 1)) < DISTANCE_PROXIMITY) { + res.getPoints().remove(i - 1); + i--; + } + } + return res; + } + + /** + * Returns distance between point and line. + * + * @param point + * point + * @param mainLine + * line + * @return distance between point and line + */ + public static double distanceFromPolyline(Point2D point, PolylineData mainLine) { + double min = Double.MAX_VALUE; + for (Line2D line : mainLine.getLines()) { + min = Math.min(min, line.ptSegDist(point)); + } + return min; + } + + /** + * Returns point on line that is as closse as possible to point. + * + * @param point + * point + * @param mainLine + * line + * @return point on line that is as closse as possible to point + */ + public static Point2D closestPointOnPolyline(PolylineData mainLine, Point2D point) { + Point2D res = null; + double distance = distanceOnPolyline(mainLine, point); + double lenght = 0.0; + for (Line2D line : mainLine.getLines()) { + lenght += lineLen(line); + } + lenght *= distance; + for (Line2D line : mainLine.getLines()) { + if (lenght - lineLen(line) > 0) { + lenght -= lineLen(line); + } else { + double tmp = lenght / lineLen(line); + double x = line.getX1() + tmp * (line.getX2() - line.getX1()); + double y = line.getY1() + tmp * (line.getY2() - line.getY1()); + res = new Point2D.Double(x, y); + } + } + return res; + } } diff --git a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/package-info.java b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/package-info.java index 491c5ebef4..52d16874d7 100644 --- a/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/package-info.java +++ b/pathvisio/src/main/java/lcsb/mapviewer/wikipathway/utils/package-info.java @@ -2,4 +2,3 @@ * Contains utils classes. */ package lcsb.mapviewer.wikipathway.utils; - diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/AllWikipathwaysTests.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/AllWikipathwaysTests.java index fee29d20bc..281011ebeb 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/AllWikipathwaysTests.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/AllWikipathwaysTests.java @@ -9,13 +9,13 @@ import lcsb.mapviewer.wikipathway.model.AllModelTests; @RunWith(Suite.class) @SuiteClasses({ AllModelTests.class, - AllXmlTests.class, - ComplexReactionToModelTest.class, - GPMLToModelTest.class, - ReactionElbowsTest.class, - ReactionGpmlInputToModelTest.class, - ReactionGpmlOutputToModelTest.class, - ReactionGpmlToModelTest.class, + AllXmlTests.class, + ComplexReactionToModelTest.class, + GPMLToModelTest.class, + ReactionElbowsTest.class, + ReactionGpmlInputToModelTest.class, + ReactionGpmlOutputToModelTest.class, + ReactionGpmlToModelTest.class, }) public class AllWikipathwaysTests { diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java index 6cbde646a3..2569ea3c2f 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ComplexReactionToModelTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.wikipathway; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java index 097555f416..4e9b4a2cd5 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/ReactionElbowsTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.wikipathway; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.awt.geom.Line2D; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java index fd2df0a77e..8143060695 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/WikipathwaysTestFunctions.java @@ -1,61 +1,38 @@ package lcsb.mapviewer.wikipathway; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; +import java.io.*; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; +import javax.xml.parsers.*; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LogEvent; import org.junit.*; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.ZIndexPopulator; +import lcsb.mapviewer.converter.*; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.model.Model; public abstract class WikipathwaysTestFunctions { - private Logger logger = LogManager.getLogger(WikipathwaysTestFunctions.class); - + protected static double EPSILON = Configuration.EPSILON; @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - - protected static double EPSILON = Configuration.EPSILON; - + private Logger logger = LogManager.getLogger(WikipathwaysTestFunctions.class); private DocumentBuilder db; private MinervaLoggerAppender appender; @@ -241,7 +218,7 @@ public abstract class WikipathwaysTestFunctions { protected Model serializeModelOverCellDesignerParser(Model model1) throws InconsistentModelException, InvalidInputDataExecption { - for (BioEntity bioEntity: model1.getBioEntities()) { + for (BioEntity bioEntity : model1.getBioEntities()) { bioEntity.setZ(null); } new ZIndexPopulator().populateZIndex(model1); diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/AllXmlTests.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/AllXmlTests.java index 563d471d1f..f52b49dddb 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/AllXmlTests.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/AllXmlTests.java @@ -6,16 +6,16 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ BiopaxParserTest.class, - DataNodeParserTest.class, - BugTest.class, - EdgeLineParserTest.class, - GpmlParserTest.class, - LabelParserTest.class, - ReferenceParserTest.class, - ModelToGPMLTest.class, - ModelContructorTest.class, - ShapeParserTest.class, - StateParserTest.class, + DataNodeParserTest.class, + BugTest.class, + EdgeLineParserTest.class, + GpmlParserTest.class, + LabelParserTest.class, + ReferenceParserTest.class, + ModelToGPMLTest.class, + ModelContructorTest.class, + ShapeParserTest.class, + StateParserTest.class, }) public class AllXmlTests { diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java index f4036a7d22..c77b5b4552 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/BugTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import java.io.FileInputStream; @@ -16,6 +16,7 @@ import lcsb.mapviewer.wikipathway.WikipathwaysTestFunctions; public class BugTest extends WikipathwaysTestFunctions { Logger logger = LogManager.getLogger(BugTest.class); + private ModelComparator mc = new ModelComparator(1.0); @Test public void testBug319() throws Exception { @@ -25,8 +26,6 @@ public class BugTest extends WikipathwaysTestFunctions { assertEquals(1, getWarnings().size()); } - private ModelComparator mc = new ModelComparator(1.0); - @Test public void testBug328() throws Exception { String filename = "testFiles/bugs/error_328.gpml"; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java index 42428c7f96..2f44e6873d 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ElementGpmlParserTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import java.awt.Color; +import java.awt.*; import java.util.Collection; import org.junit.*; @@ -16,7 +16,7 @@ public class ElementGpmlParserTest extends WikipathwaysTestFunctions { ElementGpmlParser<Object> parser = new ElementGpmlParser<Object>() { @Override - public String toXml(Collection<Object> list) throws ConverterException { + public Object parse(Element node) throws ConverterException { throw new NotImplementedException(); } @@ -26,7 +26,7 @@ public class ElementGpmlParserTest extends WikipathwaysTestFunctions { } @Override - public Object parse(Element node) throws ConverterException { + public String toXml(Collection<Object> list) throws ConverterException { throw new NotImplementedException(); } }; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java index 2cd7b571ad..14f6aeb0f9 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/LabelParserTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.wikipathway.XML; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.junit.*; import org.w3c.dom.Element; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java index ea147500f9..2d960c9302 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ModelContructorTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.awt.geom.Point2D; import java.io.ByteArrayInputStream; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java index 0f351c613d..385d524ffe 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ReferenceParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java index 85605eee81..11c6fb1cf4 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/ShapeParserTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.wikipathway.XML; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import org.junit.After; import org.junit.Test; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java index 1446fc6e25..4f8a696a79 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/XML/StateParserTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.wikipathway.XML; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.After; import org.junit.Test; diff --git a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/AllModelTests.java b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/AllModelTests.java index 940702b474..59cc0c9ddb 100644 --- a/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/AllModelTests.java +++ b/pathvisio/src/test/java/lcsb/mapviewer/wikipathway/model/AllModelTests.java @@ -1,22 +1,22 @@ package lcsb.mapviewer.wikipathway.model; -import lcsb.mapviewer.wikipathway.model.biopax.AllBiopaxTests; - import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; +import lcsb.mapviewer.wikipathway.model.biopax.AllBiopaxTests; + @RunWith(Suite.class) @SuiteClasses({ AllBiopaxTests.class, - DataNodeTest.class, - EdgeTest.class, - GraphTest.class, - GroupTest.class, - InteractionTest.class, - LabelTest.class, - PointDataTest.class, - ShapeTest.class, - StateTest.class }) + DataNodeTest.class, + EdgeTest.class, + GraphTest.class, + GroupTest.class, + InteractionTest.class, + LabelTest.class, + PointDataTest.class, + ShapeTest.class, + StateTest.class }) public class AllModelTests { } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/ApplicationContextLoader.java b/persist/src/main/java/lcsb/mapviewer/persist/ApplicationContextLoader.java index 5d898b0ee0..c480231a2a 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/ApplicationContextLoader.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/ApplicationContextLoader.java @@ -22,55 +22,56 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; */ public final class ApplicationContextLoader { - /** - * Application context used by the application. - */ - private static ConfigurableApplicationContext applicationContext; + /** + * Application context used by the application. + */ + private static ConfigurableApplicationContext applicationContext; - /** - * Default constructor. Prevents instatiation. - */ - private ApplicationContextLoader() { + /** + * Default constructor. Prevents instatiation. + */ + private ApplicationContextLoader() { - } + } - /** - * - * @return {@link #applicationContext} - */ - public static ConfigurableApplicationContext getApplicationContext() { - return applicationContext; - } + /** + * + * @return {@link #applicationContext} + */ + public static ConfigurableApplicationContext getApplicationContext() { + return applicationContext; + } - /** - * Loads application context. Override this method to change how the - * application context is loaded. - * - * @param configLocations - * configuration file locations - */ - public static void loadApplicationContext(String... configLocations) { - applicationContext = new ClassPathXmlApplicationContext(configLocations); - applicationContext.registerShutdownHook(); - } + /** + * + * @param applicationContext + * {@link #applicationContext} to set + */ + public static void setApplicationContext(ConfigurableApplicationContext applicationContext) { + ApplicationContextLoader.applicationContext = applicationContext; + } - /** - * Injects dependencies into the object. Override this method if you need full - * control over how dependencies are injected. - * - * @param main - * object to inject dependencies into - */ - public static void injectDependencies(Object main) { - getApplicationContext().getBeanFactory().autowireBeanProperties(main, AutowireCapableBeanFactory.AUTOWIRE_NO, false); - } + /** + * Loads application context. Override this method to change how the application + * context is loaded. + * + * @param configLocations + * configuration file locations + */ + public static void loadApplicationContext(String... configLocations) { + applicationContext = new ClassPathXmlApplicationContext(configLocations); + applicationContext.registerShutdownHook(); + } - /** - * - * @param applicationContext - * {@link #applicationContext} to set - */ - public static void setApplicationContext(ConfigurableApplicationContext applicationContext) { - ApplicationContextLoader.applicationContext = applicationContext; - } + /** + * Injects dependencies into the object. Override this method if you need full + * control over how dependencies are injected. + * + * @param main + * object to inject dependencies into + */ + public static void injectDependencies(Object main) { + getApplicationContext().getBeanFactory().autowireBeanProperties(main, AutowireCapableBeanFactory.AUTOWIRE_NO, + false); + } } \ No newline at end of file diff --git a/persist/src/main/java/lcsb/mapviewer/persist/ConfigurationHolder.java b/persist/src/main/java/lcsb/mapviewer/persist/ConfigurationHolder.java index 3cb7f0f5bb..4109640856 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/ConfigurationHolder.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/ConfigurationHolder.java @@ -7,41 +7,41 @@ import org.springframework.stereotype.Service; @Service @PropertySources({ - @PropertySource("classpath:db.properties"), - @PropertySource(value = "file:/etc/minerva/db.properties", ignoreResourceNotFound = true) + @PropertySource("classpath:db.properties"), + @PropertySource(value = "file:/etc/minerva/db.properties", ignoreResourceNotFound = true) }) public class ConfigurationHolder { - @Value("${database.uri}") - private String dbUri; + @Value("${database.uri}") + private String dbUri; - @Value("${database.username}") - private String dbUsername; + @Value("${database.username}") + private String dbUsername; - @Value("${database.password}") - private String dbPassword; + @Value("${database.password}") + private String dbPassword; - public String getDbUri() { - return dbUri; - } + public String getDbUri() { + return dbUri; + } - public void setDbUri(String dbUri) { - this.dbUri = dbUri; - } + public void setDbUri(String dbUri) { + this.dbUri = dbUri; + } - public String getDbUsername() { - return dbUsername; - } + public String getDbUsername() { + return dbUsername; + } - public void setDbUsername(String dbUsername) { - this.dbUsername = dbUsername; - } + public void setDbUsername(String dbUsername) { + this.dbUsername = dbUsername; + } - public String getDbPassword() { - return dbPassword; - } + public String getDbPassword() { + return dbPassword; + } - public void setDbPassword(String dbPassword) { - this.dbPassword = dbPassword; - } + public void setDbPassword(String dbPassword) { + this.dbPassword = dbPassword; + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/CustomImplicitNamingStrategy.java b/persist/src/main/java/lcsb/mapviewer/persist/CustomImplicitNamingStrategy.java index 145bb45498..a2aae037b9 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/CustomImplicitNamingStrategy.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/CustomImplicitNamingStrategy.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.persist; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.ImplicitEntityNameSource; import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy; @@ -17,10 +18,8 @@ public class CustomImplicitNamingStrategy extends SpringImplicitNamingStrategy { * */ private static final long serialVersionUID = 1L; - - Logger logger = LogManager.getLogger(CustomImplicitNamingStrategy.class); - private static final String TABLE_NAME_SUFFIX = "Table"; + Logger logger = LogManager.getLogger(CustomImplicitNamingStrategy.class); @Override public Identifier determinePrimaryTableName(ImplicitEntityNameSource source) { diff --git a/persist/src/main/java/lcsb/mapviewer/persist/DbUtils.java b/persist/src/main/java/lcsb/mapviewer/persist/DbUtils.java index 5225b1ca80..535d6848e4 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/DbUtils.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/DbUtils.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.persist; -import java.util.HashMap; -import java.util.Map; -import java.util.Observable; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -37,18 +35,11 @@ public class DbUtils extends Observable { * Default class logger. */ private static Logger logger = LogManager.getLogger(DbUtils.class); - - /** - * Hibernate session factory. - */ - private SessionFactory sessionFactory; - /** * Static map containing opened custom sessions. This object is also used for * synchronization between threads when accessing informations about sessions. */ private static Map<Long, Session> sessionForThread = new HashMap<Long, Session>(); - /** * This determines if every add/update/delete operation should be flushed (for * specific {@link Thread}). There are few drawbacks of this approach: @@ -60,6 +51,10 @@ public class DbUtils extends Observable { * </ol> */ private static Map<Long, Boolean> autoFlushForThread = new HashMap<>(); + /** + * Hibernate session factory. + */ + private SessionFactory sessionFactory; /** * Constructor diff --git a/persist/src/main/java/lcsb/mapviewer/persist/SpringApplicationContext.java b/persist/src/main/java/lcsb/mapviewer/persist/SpringApplicationContext.java index 8b87a2a294..bbc5ea6c6b 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/SpringApplicationContext.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/SpringApplicationContext.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.persist; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @@ -17,52 +18,52 @@ import org.springframework.transaction.annotation.Transactional; @Component public class SpringApplicationContext implements ApplicationContextAware { - /** - * Default logger for this class. - */ - private static Logger logger = LogManager.getLogger(SpringApplicationContext.class); + /** + * Default logger for this class. + */ + private static Logger logger = LogManager.getLogger(SpringApplicationContext.class); - /** - * {@link ApplicationContext} used by the Spring framework. - */ - private static ApplicationContext context; + /** + * {@link ApplicationContext} used by the Spring framework. + */ + private static ApplicationContext context; - /** - * This method is called from within the ApplicationContext once it is done - * starting up, it will stick a reference to itself into this bean. - * - * @param context - * a reference to the ApplicationContext. - */ - @Override - public void setApplicationContext(ApplicationContext context) { - logger.debug("Setting application context: " + context.getDisplayName()); - SpringApplicationContext.context = context; - } + /** + * This is about the same as context.getBean("beanName"), except it has its own + * static handle to the Spring context, so calling this method statically will + * give access to the beans by name in the Spring application context. As in the + * context.getBean("beanName") call, the caller must cast to the appropriate + * target class. If the bean does not exist, then a Runtime error will be + * thrown. + * + * @param beanName + * the name of the bean to get. + * @return an Object reference to the named bean. + */ + public static Object getBean(String beanName) { + beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1); + return context.getBean(beanName); + } + + /** + * + * @return {@link #context} + */ + public static ApplicationContext getApplicationContext() { + return context; + } + + /** + * This method is called from within the ApplicationContext once it is done + * starting up, it will stick a reference to itself into this bean. + * + * @param context + * a reference to the ApplicationContext. + */ + @Override + public void setApplicationContext(ApplicationContext context) { + logger.debug("Setting application context: " + context.getDisplayName()); + SpringApplicationContext.context = context; + } - /** - * This is about the same as context.getBean("beanName"), except it has its - * own static handle to the Spring context, so calling this method statically - * will give access to the beans by name in the Spring application context. As - * in the context.getBean("beanName") call, the caller must cast to the - * appropriate target class. If the bean does not exist, then a Runtime error - * will be thrown. - * - * @param beanName - * the name of the bean to get. - * @return an Object reference to the named bean. - */ - public static Object getBean(String beanName) { - beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1); - return context.getBean(beanName); - } - - /** - * - * @return {@link #context} - */ - public static ApplicationContext getApplicationContext() { - return context; - } - } \ No newline at end of file diff --git a/persist/src/main/java/lcsb/mapviewer/persist/SpringPersistConfig.java b/persist/src/main/java/lcsb/mapviewer/persist/SpringPersistConfig.java index 546335ef10..06918a4891 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/SpringPersistConfig.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/SpringPersistConfig.java @@ -1,73 +1,73 @@ package lcsb.mapviewer.persist; -import com.zaxxer.hikari.HikariDataSource; +import java.util.Properties; + +import javax.sql.DataSource; + import org.hibernate.SessionFactory; import org.hibernate.cfg.Environment; import org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.*; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; -import java.util.Properties; +import com.zaxxer.hikari.HikariDataSource; @Configuration @EnableTransactionManagement -@ComponentScan(basePackages = {"lcsb.mapviewer.persist"}) +@ComponentScan(basePackages = { "lcsb.mapviewer.persist" }) public class SpringPersistConfig { - @Bean - public ConfigurationHolder config() { - return new ConfigurationHolder(); - } + @Bean + public ConfigurationHolder config() { + return new ConfigurationHolder(); + } - @Bean(destroyMethod = "close") - public HikariDataSource dataSource(ConfigurationHolder config) { - HikariDataSource dataSource = new HikariDataSource(); - dataSource.setDriverClassName("org.postgresql.Driver"); - dataSource.setJdbcUrl(config.getDbUri()); - dataSource.setUsername(config.getDbUsername()); - dataSource.setPassword(config.getDbPassword()); - dataSource.setIdleTimeout(30000); - dataSource.setMaximumPoolSize(40); - dataSource.setMinimumIdle(10); - dataSource.setConnectionTestQuery("select 1"); - return dataSource; - } + @Bean(destroyMethod = "close") + public HikariDataSource dataSource(ConfigurationHolder config) { + HikariDataSource dataSource = new HikariDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setJdbcUrl(config.getDbUri()); + dataSource.setUsername(config.getDbUsername()); + dataSource.setPassword(config.getDbPassword()); + dataSource.setIdleTimeout(30000); + dataSource.setMaximumPoolSize(40); + dataSource.setMinimumIdle(10); + dataSource.setConnectionTestQuery("select 1"); + return dataSource; + } - @Bean - public LocalSessionFactoryBean sessionFactory(DataSource dataSource) { - Properties props = new Properties(); - props.setProperty(Environment.DIALECT, "org.hibernate.dialect.PostgreSQL95Dialect"); - props.setProperty(Environment.SHOW_SQL, "false"); - LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); - factoryBean.setDataSource(dataSource); - factoryBean.setHibernateProperties(props); - factoryBean.setPackagesToScan("lcsb.mapviewer.model"); - factoryBean.setImplicitNamingStrategy(new CustomImplicitNamingStrategy()); - factoryBean.setPhysicalNamingStrategy(new SpringPhysicalNamingStrategy()); - return factoryBean; - } + @Bean + public LocalSessionFactoryBean sessionFactory(DataSource dataSource) { + Properties props = new Properties(); + props.setProperty(Environment.DIALECT, "org.hibernate.dialect.PostgreSQL95Dialect"); + props.setProperty(Environment.SHOW_SQL, "false"); + LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean(); + factoryBean.setDataSource(dataSource); + factoryBean.setHibernateProperties(props); + factoryBean.setPackagesToScan("lcsb.mapviewer.model"); + factoryBean.setImplicitNamingStrategy(new CustomImplicitNamingStrategy()); + factoryBean.setPhysicalNamingStrategy(new SpringPhysicalNamingStrategy()); + return factoryBean; + } - @Bean - public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { - HibernateTransactionManager transactionManager = new HibernateTransactionManager(); - transactionManager.setSessionFactory(sessionFactory); - return transactionManager; - } + @Bean + public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { + HibernateTransactionManager transactionManager = new HibernateTransactionManager(); + transactionManager.setSessionFactory(sessionFactory); + return transactionManager; + } - @Bean - public DataSourceInitializer dataSourceInitializer(DataSource dataSource, DatabasePopulator databasePopulator) { - DataSourceInitializer initializer = new DataSourceInitializer(); - initializer.setDataSource(dataSource); - initializer.setDatabasePopulator(databasePopulator); - initializer.setEnabled(true); - return initializer; - } + @Bean + public DataSourceInitializer dataSourceInitializer(DataSource dataSource, DatabasePopulator databasePopulator) { + DataSourceInitializer initializer = new DataSourceInitializer(); + initializer.setDataSource(dataSource); + initializer.setDatabasePopulator(databasePopulator); + initializer.setEnabled(true); + return initializer; + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/BaseDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/BaseDao.java index 3ccc22f2a8..5cb391fb19 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/BaseDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/BaseDao.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.persist.dao; import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import javax.persistence.criteria.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -46,10 +44,16 @@ public abstract class BaseDao<T> { * Class of the object that DAO works on. */ private Class<T> clazz; + /** + * Utils that help to manage the sessions in custom multithreaded + * implementation. + */ + @Autowired + private DbUtils dbUtils; /** * Default constructor. - * + * * @param theClass * class of the object that DAO will work on */ @@ -59,27 +63,20 @@ public abstract class BaseDao<T> { /** * Default constructor. - * + * * @param theClass * class of the object that DAO will work on * @param removableColumn * determines the column in the object table that indicates if object * should be considered as removed or not (see also: * {@link #removableColumn}. - * + * */ public BaseDao(Class<T> theClass, String removableColumn) { this(theClass); this.removableColumn = removableColumn; } - /** - * Utils that help to manage the sessions in custom multithreaded - * implementation. - */ - @Autowired - private DbUtils dbUtils; - /** * Adds object to the database. * diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/ConfigurationDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/ConfigurationDao.java index 244f38544f..f28d3fa6d0 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/ConfigurationDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/ConfigurationDao.java @@ -1,9 +1,10 @@ package lcsb.mapviewer.persist.dao; -import lcsb.mapviewer.model.user.ConfigurationOption; -import lcsb.mapviewer.model.user.ConfigurationElementType; import org.springframework.stereotype.Repository; +import lcsb.mapviewer.model.user.ConfigurationElementType; +import lcsb.mapviewer.model.user.ConfigurationOption; + /** * Data access object class for Configuration objects. * @@ -13,42 +14,41 @@ import org.springframework.stereotype.Repository; @Repository public class ConfigurationDao extends BaseDao<ConfigurationOption> { - /** - * Default constructor. - */ - public ConfigurationDao() { - super(ConfigurationOption.class); - } + /** + * Default constructor. + */ + public ConfigurationDao() { + super(ConfigurationOption.class); + } - /** - * Returns object with configuration value for the type given in the - * parameter. - * - * @param type - * type of the parameter that we are interested in - * @return object with configuration value for the type given in the parameter - */ - public ConfigurationOption getByType(ConfigurationElementType type) { - return getByParameter("type", type); - } + /** + * Returns object with configuration value for the type given in the parameter. + * + * @param type + * type of the parameter that we are interested in + * @return object with configuration value for the type given in the parameter + */ + public ConfigurationOption getByType(ConfigurationElementType type) { + return getByParameter("type", type); + } - /** - * Returns value by the type. - * - * @param type - * type of configuration parameter - * @return value of the specific configuration parameter - */ - public String getValueByType(ConfigurationElementType type) { - ConfigurationOption val = getByParameter("type", type); - if (val == null) { - if (type == null) { - return null; - } else { - return type.getDefaultValue(); - } - } else { - return val.getValue(); - } - } + /** + * Returns value by the type. + * + * @param type + * type of configuration parameter + * @return value of the specific configuration parameter + */ + public String getValueByType(ConfigurationElementType type) { + ConfigurationOption val = getByParameter("type", type); + if (val == null) { + if (type == null) { + return null; + } else { + return type.getDefaultValue(); + } + } else { + return val.getValue(); + } + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDao.java index fca6757cfb..fb3466fdd9 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDao.java @@ -2,11 +2,12 @@ package lcsb.mapviewer.persist.dao.cache; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Repository; import lcsb.mapviewer.model.cache.BigFileEntry; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for cached values. diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDao.java index b5b63df58e..bf3dc41300 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDao.java @@ -2,10 +2,11 @@ package lcsb.mapviewer.persist.dao.cache; import java.util.List; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.cache.CacheQuery; import lcsb.mapviewer.model.cache.CacheType; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for cached values. @@ -15,46 +16,47 @@ import org.springframework.stereotype.Repository; */ @Repository public class CacheQueryDao extends BaseDao<CacheQuery> { - - /** - * Default constructor. - */ - public CacheQueryDao() { - super(CacheQuery.class); - } - - /** - * Returns the cached value based on the type of resource and identifier in - * remote resource. - * - * @param identifier - * identifier in remote resource - * @param type - * type of the resource - * @return cached value, if value wasn't cached then null is returned - */ - public CacheQuery getByQuery(String identifier, Integer type) { - List<?> list = getSession() - .createQuery(" from " + this.getClazz().getSimpleName() + " where query = :query and type = :type").setParameter("query", identifier) - .setParameter("type", type).list(); - if (list.size() == 0) { - return null; - } - return (CacheQuery) list.get(0); - } - - /** - * Returns the cached value based on the type of resource and identifier in - * remote resource. - * - * @param identifier - * identifier in remote resource - * @param type - * type of the resource - * @return cached value, if value wasn't cached then null is returned - */ - public CacheQuery getByQuery(String identifier, CacheType type) { - return getByQuery(identifier, type.getId()); - } + + /** + * Default constructor. + */ + public CacheQueryDao() { + super(CacheQuery.class); + } + + /** + * Returns the cached value based on the type of resource and identifier in + * remote resource. + * + * @param identifier + * identifier in remote resource + * @param type + * type of the resource + * @return cached value, if value wasn't cached then null is returned + */ + public CacheQuery getByQuery(String identifier, Integer type) { + List<?> list = getSession() + .createQuery(" from " + this.getClazz().getSimpleName() + " where query = :query and type = :type") + .setParameter("query", identifier) + .setParameter("type", type).list(); + if (list.size() == 0) { + return null; + } + return (CacheQuery) list.get(0); + } + + /** + * Returns the cached value based on the type of resource and identifier in + * remote resource. + * + * @param identifier + * identifier in remote resource + * @param type + * type of the resource + * @return cached value, if value wasn't cached then null is returned + */ + public CacheQuery getByQuery(String identifier, CacheType type) { + return getByQuery(identifier, type.getId()); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDao.java index 9f92af8c70..1c7f5263ed 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/CacheTypeDao.java @@ -2,12 +2,13 @@ package lcsb.mapviewer.persist.dao.cache; import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.cache.CacheType; import lcsb.mapviewer.persist.dao.BaseDao; -import org.apache.logging.log4j.*; -import org.springframework.stereotype.Repository; - /** * Data access object for cached values. * @@ -16,32 +17,32 @@ import org.springframework.stereotype.Repository; */ @Repository public class CacheTypeDao extends BaseDao<CacheType> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(CacheTypeDao.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(CacheTypeDao.class); - /** - * Default constructor. - */ - public CacheTypeDao() { - super(CacheType.class); - } + /** + * Default constructor. + */ + public CacheTypeDao() { + super(CacheType.class); + } - /** - * Returns the cach type for the class name identified by a canonical name. - * - * @param className - * canonical name of the class - * @return type of cache that should be used by this cachable interface - */ - public CacheType getByClassName(String className) { - List<?> list = getElementsByParameter("className", className); - if (list.size() == 0) { - return null; - } - return (CacheType) list.get(0); - } + /** + * Returns the cach type for the class name identified by a canonical name. + * + * @param className + * canonical name of the class + * @return type of cache that should be used by this cachable interface + */ + public CacheType getByClassName(String className) { + List<?> list = getElementsByParameter("className", className); + if (list.size() == 0) { + return null; + } + return (CacheType) list.get(0); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDao.java index 897c5a5fc3..76abc6bcfe 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDao.java @@ -1,10 +1,11 @@ package lcsb.mapviewer.persist.dao.cache; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Repository; import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for cached values. @@ -14,23 +15,23 @@ import org.springframework.stereotype.Repository; */ @Repository public class UploadedFileEntryDao extends BaseDao<UploadedFileEntry> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(UploadedFileEntryDao.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(UploadedFileEntryDao.class); - /** - * Default constructor. - */ - public UploadedFileEntryDao() { - super(UploadedFileEntry.class, "removed"); - } + /** + * Default constructor. + */ + public UploadedFileEntryDao() { + super(UploadedFileEntry.class, "removed"); + } - @Override - public void delete(UploadedFileEntry entry) { - entry.setRemoved(true); - update(entry); - } + @Override + public void delete(UploadedFileEntry entry) { + entry.setRemoved(true); + update(entry); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/package-info.java index f2f2f5f53c..6f912da125 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/cache/package-info.java @@ -2,4 +2,3 @@ * Package with data access object for cached elements. */ package lcsb.mapviewer.persist.dao.cache; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/PolylineDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/PolylineDao.java index 2f428b692f..aefd24ce5d 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/PolylineDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/PolylineDao.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.persist.dao.graphics; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.graphics.PolylineData; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for {@link PolylineDao} class. @@ -13,11 +14,11 @@ import org.springframework.stereotype.Repository; @Repository public class PolylineDao extends BaseDao<PolylineData> { - /** - * Default constructor. - */ - public PolylineDao() { - super(PolylineData.class); - } + /** + * Default constructor. + */ + public PolylineDao() { + super(PolylineData.class); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/package-info.java index ae5ee40a47..87d3b407ab 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/graphics/package-info.java @@ -2,4 +2,3 @@ * Package with data access object for graphics elements. */ package lcsb.mapviewer.persist.dao.graphics; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/CommentDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/CommentDao.java index 64535fe2f2..b8150dcb89 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/CommentDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/CommentDao.java @@ -3,14 +3,15 @@ package lcsb.mapviewer.persist.dao.map; import java.util.ArrayList; import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.Comment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.persist.dao.BaseDao; -import org.apache.logging.log4j.*; -import org.springframework.stereotype.Repository; - /** * Data access object class for Comment objects. * @@ -19,117 +20,117 @@ import org.springframework.stereotype.Repository; */ @Repository public class CommentDao extends BaseDao<Comment> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(CommentDao.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(CommentDao.class); - /** - * Default constructor. - */ - public CommentDao() { - super(Comment.class); - } + /** + * Default constructor. + */ + public CommentDao() { + super(Comment.class); + } - /** - * Returns list of comments for a model given in the parameter. The comments - * are limited by the parameters. - * - * @param model - * in which model we want to find comments - * @param pinned - * this parameter defines what kind of comments we want to get: - * <ul> - * <li>null - all comments</li> - * <li>false - comments that are not visible on the map</li> - * <li>true - comments that are visible on the map</li> - * </ul> - * @param deleted - * this parameter defines what kind of comments we want to get: - * <ul> - * <li>null - all comments</li> - * <li>false - comments that are not deleted</li> - * <li>true - comments that are deleted</li> - * </ul> - * @return list of comments that fulfill parameters constraints - */ - public List<Comment> getCommentByModel(Model model, Boolean pinned, Boolean deleted) { - return getCommentByModel(model.getId(), pinned, deleted); - } + /** + * Returns list of comments for a model given in the parameter. The comments are + * limited by the parameters. + * + * @param model + * in which model we want to find comments + * @param pinned + * this parameter defines what kind of comments we want to get: + * <ul> + * <li>null - all comments</li> + * <li>false - comments that are not visible on the map</li> + * <li>true - comments that are visible on the map</li> + * </ul> + * @param deleted + * this parameter defines what kind of comments we want to get: + * <ul> + * <li>null - all comments</li> + * <li>false - comments that are not deleted</li> + * <li>true - comments that are deleted</li> + * </ul> + * @return list of comments that fulfill parameters constraints + */ + public List<Comment> getCommentByModel(Model model, Boolean pinned, Boolean deleted) { + return getCommentByModel(model.getId(), pinned, deleted); + } - /** - * Returns list of comments for a model given in the parameter. The comments - * are limited by the parameters. - * - * @param modelId - * in which model we want to find comments - * @param pinned - * this parameter defines what kind of comments we want to get: - * <ul> - * <li>null - all comments</li> - * <li>false - comments that are not visible on the map</li> - * <li>true - comments that are visible on the map</li> - * </ul> - * @param deleted - * this parameter defines what kind of comments we want to get: - * <ul> - * <li>null - all comments</li> - * <li>false - comments that are not deleted</li> - * <li>true - comments that are deleted</li> - * </ul> - * @return list of comments that fulfill parameters constraints - */ - private List<Comment> getCommentByModel(int modelId, Boolean pinned, Boolean deleted) { - List<Comment> comments = getElementsByParameter("model_id", modelId); - List<Comment> result = new ArrayList<Comment>(); - if (deleted != null) { - for (Comment comment : comments) { - if (comment.isDeleted() == deleted) { - result.add(comment); - } - } - } else { - result = comments; - } + /** + * Returns list of comments for a model given in the parameter. The comments are + * limited by the parameters. + * + * @param modelId + * in which model we want to find comments + * @param pinned + * this parameter defines what kind of comments we want to get: + * <ul> + * <li>null - all comments</li> + * <li>false - comments that are not visible on the map</li> + * <li>true - comments that are visible on the map</li> + * </ul> + * @param deleted + * this parameter defines what kind of comments we want to get: + * <ul> + * <li>null - all comments</li> + * <li>false - comments that are not deleted</li> + * <li>true - comments that are deleted</li> + * </ul> + * @return list of comments that fulfill parameters constraints + */ + private List<Comment> getCommentByModel(int modelId, Boolean pinned, Boolean deleted) { + List<Comment> comments = getElementsByParameter("model_id", modelId); + List<Comment> result = new ArrayList<Comment>(); + if (deleted != null) { + for (Comment comment : comments) { + if (comment.isDeleted() == deleted) { + result.add(comment); + } + } + } else { + result = comments; + } - if (pinned == null) { - return result; - } - comments = result; - result = new ArrayList<Comment>(); - for (Comment comment : comments) { - if (comment.isPinned() == pinned) { - result.add(comment); - } - } - return result; - } + if (pinned == null) { + return result; + } + comments = result; + result = new ArrayList<Comment>(); + for (Comment comment : comments) { + if (comment.isPinned() == pinned) { + result.add(comment); + } + } + return result; + } - /** - * Returns list of comments for a model given in the parameter. The comments - * are limited by the parameters. - * - * @param model - * in which model we want to find comments - * @param pinned - * this parameter defines what kind of comments we want to get: - * <ul> - * <li>null - all comments</li> - * <li>false - comments that are not visible on the map</li> - * <li>true - comments that are visible on the map</li> - * </ul> - * @param deleted - * this parameter defines what kind of comments we want to get: - * <ul> - * <li>null - all comments</li> - * <li>false - comments that are not deleted</li> - * <li>true - comments that are deleted</li> - * </ul> - * @return list of comments that fulfill parameters constraints - */ - public List<Comment> getCommentByModel(ModelData model, Boolean pinned, Boolean deleted) { - return getCommentByModel(model.getId(), pinned, deleted); - } + /** + * Returns list of comments for a model given in the parameter. The comments are + * limited by the parameters. + * + * @param model + * in which model we want to find comments + * @param pinned + * this parameter defines what kind of comments we want to get: + * <ul> + * <li>null - all comments</li> + * <li>false - comments that are not visible on the map</li> + * <li>true - comments that are visible on the map</li> + * </ul> + * @param deleted + * this parameter defines what kind of comments we want to get: + * <ul> + * <li>null - all comments</li> + * <li>false - comments that are not deleted</li> + * <li>true - comments that are deleted</li> + * </ul> + * @return list of comments that fulfill parameters constraints + */ + public List<Comment> getCommentByModel(ModelData model, Boolean pinned, Boolean deleted) { + return getCommentByModel(model.getId(), pinned, deleted); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/LayoutDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/LayoutDao.java index 5190ed5644..dcced37ff2 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/LayoutDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/LayoutDao.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.persist.dao.map; import java.util.List; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Root; +import javax.persistence.criteria.*; import org.springframework.stereotype.Repository; diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ModelDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ModelDao.java index 0d027da0fe..28b9f7f15f 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ModelDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ModelDao.java @@ -2,13 +2,14 @@ package lcsb.mapviewer.persist.dao.map; import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.persist.dao.BaseDao; -import org.apache.logging.log4j.*; -import org.springframework.stereotype.Repository; - /** * Data access object for {@link Model} class. * @@ -17,97 +18,97 @@ import org.springframework.stereotype.Repository; */ @Repository public class ModelDao extends BaseDao<ModelData> { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(ModelDao.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(ModelDao.class); - /** - * Default constructor. - */ - public ModelDao() { - super(ModelData.class); - } + /** + * Default constructor. + */ + public ModelDao() { + super(ModelData.class); + } - @Override - public void delete(ModelData model) { - if (model.getProject() != null) { - model.getProject().removeModel(model); - } - model.setProject(null); - super.delete(model); - } + @Override + public void delete(ModelData model) { + if (model.getProject() != null) { + model.getProject().removeModel(model); + } + model.setProject(null); + super.delete(model); + } - @Override - public ModelData getById(int id) { - ModelData result = super.getById(id); - return result; - } + @Override + public ModelData getById(int id) { + ModelData result = super.getById(id); + return result; + } - /** - * Return the latest model for the project with a given project identifier. - * - * @param projectId - * identifier of the project - * @param lazyLoad - * if <code>false</code>, the whole model (and all substructures) - * should be loaded at once, if <code>true</code> then some elements - * will be loaded on demand by hibernate proxy - * @return the latest model for the project with a given name - */ - public ModelData getLastModelForProjectIdentifier(String projectId, boolean lazyLoad) { - @SuppressWarnings("unchecked") - List<ModelData> list = getSession() - .createQuery( - "select model_t from " + getClazz().getSimpleName() - + " model_t join model_t.project project_t where project_t.projectId = :project_id order by model_t.id desc") - .setParameter("project_id", projectId).setMaxResults(1).list(); - if (list.size() > 0) { - return list.get(0); - } else { - return null; - } - } + /** + * Return the latest model for the project with a given project identifier. + * + * @param projectId + * identifier of the project + * @param lazyLoad + * if <code>false</code>, the whole model (and all substructures) + * should be loaded at once, if <code>true</code> then some elements + * will be loaded on demand by hibernate proxy + * @return the latest model for the project with a given name + */ + public ModelData getLastModelForProjectIdentifier(String projectId, boolean lazyLoad) { + @SuppressWarnings("unchecked") + List<ModelData> list = getSession() + .createQuery( + "select model_t from " + getClazz().getSimpleName() + + " model_t join model_t.project project_t where project_t.projectId = :project_id order by model_t.id desc") + .setParameter("project_id", projectId).setMaxResults(1).list(); + if (list.size() > 0) { + return list.get(0); + } else { + return null; + } + } - /** - * Adds model data to the database. - * - * @param model - * object containing model data to add to database - */ - public void add(Model model) { - add(model.getModelData()); - } + /** + * Adds model data to the database. + * + * @param model + * object containing model data to add to database + */ + public void add(Model model) { + add(model.getModelData()); + } - /** - * Removes model data from the database. - * - * @param model - * object containing model data - */ - public void delete(Model model) { - delete(model.getModelData()); - } + /** + * Removes model data from the database. + * + * @param model + * object containing model data + */ + public void delete(Model model) { + delete(model.getModelData()); + } - /** - * "Disconnects" model data from database. From this point on we cannot - * update/delete it in the database. - * - * @param model - * model containing model data to disconnect - */ - public void evict(Model model) { - evict(model.getModelData()); - } + /** + * "Disconnects" model data from database. From this point on we cannot + * update/delete it in the database. + * + * @param model + * model containing model data to disconnect + */ + public void evict(Model model) { + evict(model.getModelData()); + } - /** - * Removes model data int the database. - * - * @param model - * object containing model data - */ - public void update(Model model) { - update(model.getModelData()); - } + /** + * Removes model data int the database. + * + * @param model + * object containing model data + */ + public void update(Model model) { + update(model.getModelData()); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ReactionDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ReactionDao.java index e247e2ae12..1fb5802dc8 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ReactionDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/ReactionDao.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.persist.dao.map; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for {@link Reaction} class. @@ -13,11 +14,11 @@ import org.springframework.stereotype.Repository; @Repository public class ReactionDao extends BaseDao<Reaction> { - /** - * Default constructor. - */ - public ReactionDao() { - super(Reaction.class); - } + /** + * Default constructor. + */ + public ReactionDao() { + super(Reaction.class); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDao.java index 1d97a7c509..09e8415561 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDao.java @@ -2,10 +2,11 @@ package lcsb.mapviewer.persist.dao.map.layout; import java.util.List; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.layout.ReferenceGenome; import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for {@link ReferenceGenome} objects. @@ -16,22 +17,22 @@ import org.springframework.stereotype.Repository; @Repository public class ReferenceGenomeDao extends BaseDao<ReferenceGenome> { - /** - * Default constructor. - */ - public ReferenceGenomeDao() { - super(ReferenceGenome.class); - } + /** + * Default constructor. + */ + public ReferenceGenomeDao() { + super(ReferenceGenome.class); + } - /** - * List all reference genomes for specific reference genome type. - * - * @param ucsc - * reference genome type - * @return list of reference genomes for a given type - */ - public List<ReferenceGenome> getByType(ReferenceGenomeType ucsc) { - return getElementsByParameter("type", ucsc); - } + /** + * List all reference genomes for specific reference genome type. + * + * @param ucsc + * reference genome type + * @return list of reference genomes for a given type + */ + public List<ReferenceGenome> getByType(ReferenceGenomeType ucsc) { + return getElementsByParameter("type", ucsc); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDao.java index 603763c4af..57b2596140 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDao.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.persist.dao.map.layout; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object for {@link ReferenceGenomeGeneMapping} objects. @@ -13,11 +14,11 @@ import org.springframework.stereotype.Repository; @Repository public class ReferenceGenomeGeneMappingDao extends BaseDao<ReferenceGenomeGeneMapping> { - /** - * Default constructor. - */ - public ReferenceGenomeGeneMappingDao() { - super(ReferenceGenomeGeneMapping.class); - } + /** + * Default constructor. + */ + public ReferenceGenomeGeneMappingDao() { + super(ReferenceGenomeGeneMapping.class); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/package-info.java index 522503b60b..d3a51d7c5e 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/layout/package-info.java @@ -2,4 +2,3 @@ * Data access objects for layout substructures. */ package lcsb.mapviewer.persist.dao.map.layout; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/package-info.java index 4a4870b438..3ac42df8f3 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/package-info.java @@ -2,4 +2,3 @@ * Data access objects for model and all model substructures. */ package lcsb.mapviewer.persist.dao.map; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/ElementDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/ElementDao.java index b7dabc2922..8f6b494960 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/ElementDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/ElementDao.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.persist.dao.map.species; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data Access Object class for Alias class. @@ -13,11 +14,11 @@ import org.springframework.stereotype.Repository; @Repository public class ElementDao extends BaseDao<Element> { - /** - * Default constructor. - */ - public ElementDao() { - super(Element.class); - } + /** + * Default constructor. + */ + public ElementDao() { + super(Element.class); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/package-info.java index 0f52154a77..74d87ba037 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/species/package-info.java @@ -2,4 +2,3 @@ * Data access objects for aliases. */ package lcsb.mapviewer.persist.dao.map.species; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDao.java index ccb94767c2..367b79f605 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDao.java @@ -1,11 +1,12 @@ package lcsb.mapviewer.persist.dao.map.statistics; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.map.statistics.SearchHistory; import lcsb.mapviewer.persist.dao.BaseDao; -import org.apache.logging.log4j.*; -import org.springframework.stereotype.Repository; - /** * Data access object for {@link SearchHistory} class. * @@ -14,17 +15,17 @@ import org.springframework.stereotype.Repository; */ @Repository public class SearchHistoryDao extends BaseDao<SearchHistory> { - /** - * Default constructor. - */ - @SuppressWarnings("unused") - private static Logger logger = LogManager.getLogger(SearchHistoryDao.class); + /** + * Default constructor. + */ + @SuppressWarnings("unused") + private static Logger logger = LogManager.getLogger(SearchHistoryDao.class); - /** - * Default constructor. - */ - public SearchHistoryDao() { - super(SearchHistory.class); - } + /** + * Default constructor. + */ + public SearchHistoryDao() { + super(SearchHistory.class); + } } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/package-info.java index 9330947661..c3acfb04c8 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/map/statistics/package-info.java @@ -2,4 +2,3 @@ * Data access objects for statistic structures. */ package lcsb.mapviewer.persist.dao.map.statistics; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/package-info.java index b16509a62e..58ddacd73b 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/package-info.java @@ -2,4 +2,3 @@ * Package with data access object for all elements in the system. */ package lcsb.mapviewer.persist.dao; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDao.java index 353d1b08c6..492fa92d29 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDao.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.persist.dao.plugin; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.model.plugin.Plugin; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object class for {@link Plugin} objects. diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDao.java index e4c8acb74f..7d86a2da96 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDao.java @@ -3,12 +3,13 @@ package lcsb.mapviewer.persist.dao.plugin; import java.util.ArrayList; import java.util.List; +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.plugin.Plugin; import lcsb.mapviewer.model.plugin.PluginDataEntry; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; /** * Data access object class for {@link PluginDataEntry} objects. diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/security/PrivilegeDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/security/PrivilegeDao.java index 2ec5436193..9c5acdf318 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/security/PrivilegeDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/security/PrivilegeDao.java @@ -1,12 +1,14 @@ package lcsb.mapviewer.persist.dao.security; +import java.util.Arrays; +import java.util.List; + +import org.springframework.stereotype.Repository; + import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.security.Privilege; import lcsb.mapviewer.model.security.PrivilegeType; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; - -import java.util.*; @Repository public class PrivilegeDao extends BaseDao<Privilege> { diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/user/UserDao.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/user/UserDao.java index 9359eba087..4ea490640d 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/user/UserDao.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/user/UserDao.java @@ -1,10 +1,9 @@ package lcsb.mapviewer.persist.dao.user; -import java.util.List; +import org.springframework.stereotype.Repository; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.BaseDao; -import org.springframework.stereotype.Repository; @Repository public class UserDao extends BaseDao<User> { diff --git a/persist/src/main/java/lcsb/mapviewer/persist/dao/user/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/dao/user/package-info.java index 5718df5478..62c5cf4723 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/dao/user/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/dao/user/package-info.java @@ -2,4 +2,3 @@ * Package with data access object for user, privileges, etc. */ package lcsb.mapviewer.persist.dao.user; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapper.java b/persist/src/main/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapper.java index 9b6253809a..d01c888be9 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapper.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapper.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.persist.mapper; import java.awt.geom.Point2D; import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; @@ -12,9 +10,7 @@ import org.hibernate.type.StringType; import org.hibernate.type.Type; import org.hibernate.usertype.CompositeUserType; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.LineType; +import lcsb.mapviewer.model.graphics.*; /** * This class allows to put {@link Point2D} objects into hibernate based models. @@ -45,10 +41,6 @@ public class ArrowTypeDataMapper implements CompositeUserType { return returnValue; } - private String arrowTypeDataToString(final ArrowTypeData atd) { - return atd.getAngle() + ";" + atd.getLen() + ";" + atd.getArrowType().name() + ";" + atd.getArrowLineType(); - } - @Override public void setPropertyValue(Object component, int property, Object value) { final ArrowTypeData atd = (ArrowTypeData) component; @@ -81,21 +73,6 @@ public class ArrowTypeDataMapper implements CompositeUserType { return x.hashCode(); } - @Override - public Object deepCopy(Object value) { - if (value == null) { - return null; - } - final ArrowTypeData receivedParam = (ArrowTypeData) value; - final ArrowTypeData point = receivedParam.copy(); - return point; - } - - @Override - public boolean isMutable() { - return true; - } - @Override public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { @@ -107,14 +84,6 @@ public class ArrowTypeDataMapper implements CompositeUserType { return atd; } - private void assignSerializedProperties(ArrowTypeData atd, final String val) { - final String[] values = val.split(";"); - atd.setAngle(Double.parseDouble(values[0])); - atd.setLen(Double.parseDouble(values[1])); - atd.setArrowType(ArrowType.valueOf(values[2])); - atd.setArrowLineType(LineType.valueOf(values[3])); - } - @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException { @@ -126,6 +95,21 @@ public class ArrowTypeDataMapper implements CompositeUserType { } } + @Override + public Object deepCopy(Object value) { + if (value == null) { + return null; + } + final ArrowTypeData receivedParam = (ArrowTypeData) value; + final ArrowTypeData point = receivedParam.copy(); + return point; + } + + @Override + public boolean isMutable() { + return true; + } + @Override public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { return (Serializable) value; @@ -143,4 +127,16 @@ public class ArrowTypeDataMapper implements CompositeUserType { return this.deepCopy(original); } + private String arrowTypeDataToString(final ArrowTypeData atd) { + return atd.getAngle() + ";" + atd.getLen() + ";" + atd.getArrowType().name() + ";" + atd.getArrowLineType(); + } + + private void assignSerializedProperties(ArrowTypeData atd, final String val) { + final String[] values = val.split(";"); + atd.setAngle(Double.parseDouble(values[0])); + atd.setLen(Double.parseDouble(values[1])); + atd.setArrowType(ArrowType.valueOf(values[2])); + atd.setArrowLineType(LineType.valueOf(values[3])); + } + } diff --git a/persist/src/main/java/lcsb/mapviewer/persist/mapper/Point2DMapper.java b/persist/src/main/java/lcsb/mapviewer/persist/mapper/Point2DMapper.java index 9c1b536705..83ffb5b908 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/mapper/Point2DMapper.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/mapper/Point2DMapper.java @@ -2,9 +2,7 @@ package lcsb.mapviewer.persist.mapper; import java.awt.geom.Point2D; import java.io.Serializable; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; +import java.sql.*; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; @@ -73,21 +71,6 @@ public class Point2DMapper implements CompositeUserType { return x.hashCode(); } - @Override - public Object deepCopy(Object value) { - if (value == null) { - return null; - } - final Point2D recievedParam = (Point2D) value; - final Point2D point = new Point2D.Double(recievedParam.getX(), recievedParam.getY()); - return point; - } - - @Override - public boolean isMutable() { - return true; - } - @Override public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException { @@ -111,6 +94,21 @@ public class Point2DMapper implements CompositeUserType { } } + @Override + public Object deepCopy(Object value) { + if (value == null) { + return null; + } + final Point2D recievedParam = (Point2D) value; + final Point2D point = new Point2D.Double(recievedParam.getX(), recievedParam.getY()); + return point; + } + + @Override + public boolean isMutable() { + return true; + } + @Override public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException { return (Serializable) value; diff --git a/persist/src/main/java/lcsb/mapviewer/persist/mapper/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/mapper/package-info.java index 1cd2295a41..449e09f70c 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/mapper/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/mapper/package-info.java @@ -2,4 +2,3 @@ * Provides mappers for build-in java objects for our hibernate based model. */ package lcsb.mapviewer.persist.mapper; - diff --git a/persist/src/main/java/lcsb/mapviewer/persist/migration/V14_0_0_20190701__bcrypt_passwords.java b/persist/src/main/java/lcsb/mapviewer/persist/migration/V14_0_0_20190701__bcrypt_passwords.java index 95fc8f9e22..d24de9c4ee 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/migration/V14_0_0_20190701__bcrypt_passwords.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/migration/V14_0_0_20190701__bcrypt_passwords.java @@ -1,12 +1,12 @@ package lcsb.mapviewer.persist.migration; +import java.sql.ResultSet; +import java.sql.Statement; + import org.flywaydb.core.api.migration.BaseJavaMigration; import org.flywaydb.core.api.migration.Context; import org.springframework.security.crypto.bcrypt.BCrypt; -import java.sql.ResultSet; -import java.sql.Statement; - public class V14_0_0_20190701__bcrypt_passwords extends BaseJavaMigration { @Override diff --git a/persist/src/main/java/lcsb/mapviewer/persist/package-info.java b/persist/src/main/java/lcsb/mapviewer/persist/package-info.java index 0f558d88ba..21c502bed1 100644 --- a/persist/src/main/java/lcsb/mapviewer/persist/package-info.java +++ b/persist/src/main/java/lcsb/mapviewer/persist/package-info.java @@ -3,4 +3,3 @@ * stored in database. */ package lcsb.mapviewer.persist; - diff --git a/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java b/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java index a8394a73a6..3bee2e142f 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/ApplicationContextLoaderTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.persist; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.lang.reflect.Constructor; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java b/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java index e7144712bf..1048c09f89 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/DbUtilsTest.java @@ -10,10 +10,9 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.common.exception.InvalidStateException; public class DbUtilsTest extends PersistTestFunctions { - Logger logger = LogManager.getLogger(DbUtilsTest.class); - @Autowired protected DbUtils dbUtils; + Logger logger = LogManager.getLogger(DbUtilsTest.class); @Test public void testCreateSession() throws Exception { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/InitialStateTest.java b/persist/src/test/java/lcsb/mapviewer/persist/InitialStateTest.java index 950cbe3777..3897f40df2 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/InitialStateTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/InitialStateTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.persist; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; -import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java b/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java index f49eea32e4..12d8772d46 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/PersistTestFunctions.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.persist; -import java.awt.Color; +import java.awt.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -34,25 +34,17 @@ public abstract class PersistTestFunctions { @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(PersistTestFunctions.class); - - PointTransformation pt = new PointTransformation(); - public double EPSILON = 1e-6; - @Autowired protected ProjectDao projectDao; - @Autowired protected ModelDao modelDao; - @Autowired protected UserDao userDao; - protected int identifierCounter = 0; - + PointTransformation pt = new PointTransformation(); + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(PersistTestFunctions.class); private int zIndex = 0; protected User createUser() { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/SpringApplicationContextTest.java b/persist/src/test/java/lcsb/mapviewer/persist/SpringApplicationContextTest.java index 30dae41a84..2a0b2a0127 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/SpringApplicationContextTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/SpringApplicationContextTest.java @@ -1,29 +1,27 @@ package lcsb.mapviewer.persist; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class SpringApplicationContextTest extends PersistTestFunctions { - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetter() { - assertNotNull(SpringApplicationContext.getApplicationContext()); - } - - @Test - public void testGetBean() { - assertNotNull(SpringApplicationContext.getBean("DbUtils")); - } + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetter() { + assertNotNull(SpringApplicationContext.getApplicationContext()); + } + + @Test + public void testGetBean() { + assertNotNull(SpringApplicationContext.getBean("DbUtils")); + } } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/ConfigurationDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/ConfigurationDaoTest.java index ab254f8846..e40ed5d5c5 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/ConfigurationDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/ConfigurationDaoTest.java @@ -3,9 +3,7 @@ package lcsb.mapviewer.persist.dao; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.model.user.ConfigurationElementType; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/AllCacheDbTests.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/AllCacheDbTests.java index 774531dd15..68d002731f 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/AllCacheDbTests.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/AllCacheDbTests.java @@ -6,9 +6,9 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ BigFileEntryDaoTest.class, - CacheTypeDaoTest.class, - CacheQueryDaoTest.class, - UploadedFileEntryDaoTest.class, + CacheTypeDaoTest.class, + CacheQueryDaoTest.class, + UploadedFileEntryDaoTest.class, }) public class AllCacheDbTests { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java index c0bd4dea7e..80a27be126 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/BigFileEntryDaoTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java index 5cbb5ee9c0..067005709e 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/CacheQueryDaoTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java index 77b22f20f1..c29ceff111 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/cache/UploadedFileEntryDaoTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.persist.dao.cache; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/graphics/PolylineDataTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/graphics/PolylineDataTest.java index 619751e748..c483920daa 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/graphics/PolylineDataTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/graphics/PolylineDataTest.java @@ -1,20 +1,14 @@ package lcsb.mapviewer.persist.dao.graphics; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.awt.geom.Point2D; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.LineType; -import lcsb.mapviewer.model.graphics.PolylineData; +import lcsb.mapviewer.model.graphics.*; import lcsb.mapviewer.persist.PersistTestFunctions; public class PolylineDataTest extends PersistTestFunctions { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java index dc2df4e2a1..4a0e19615c 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/CommentDaoTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.persist.dao.map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; @@ -24,8 +25,8 @@ public class CommentDaoTest extends PersistTestFunctions { protected CommentDao commentDao; User user; - private Project project; String projectId = "Some_id"; + private Project project; @Before public void setUp() throws Exception { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java index 54f3d341f9..8948958f37 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/LayoutDaoTest.java @@ -27,11 +27,10 @@ import lcsb.mapviewer.persist.PersistTestFunctions; public class LayoutDaoTest extends PersistTestFunctions { + final static Logger logger = LogManager.getLogger(LayoutDaoTest.class); @Autowired private LayoutDao layoutDao; - final static Logger logger = LogManager.getLogger(LayoutDaoTest.class); - @Before public void setUp() throws Exception { } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java index f7983dae4b..07aff13865 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/ModelDaoTest.java @@ -24,9 +24,9 @@ public class ModelDaoTest extends PersistTestFunctions { ModelComparator modelComparator = new ModelComparator(); Logger logger = LogManager.getLogger(ModelDaoTest.class); - private Project project; String projectId = "Some_id"; int identifierCounter = 0; + private Project project; @Before public void setUp() throws Exception { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/AllLayoutTests.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/AllLayoutTests.java index fb3285bb7d..343374f35c 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/AllLayoutTests.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/AllLayoutTests.java @@ -8,8 +8,8 @@ import lcsb.mapviewer.persist.dao.map.layout.alias.AllAliasTests; @RunWith(Suite.class) @SuiteClasses({ AllAliasTests.class, - ReferenceGenomeDaoTest.class, - ReferenceGenomeGeneMappingDaoTest.class, + ReferenceGenomeDaoTest.class, + ReferenceGenomeGeneMappingDaoTest.class, }) public class AllLayoutTests { diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java index 1145263d3c..97ede00331 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeDaoTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.persist.dao.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java index fb301563a6..277b2ea1bd 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/layout/ReferenceGenomeGeneMappingDaoTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.persist.dao.map.layout; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java index d788a1c1e3..5f263b57cb 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/map/statistics/SearchHistoryDaoTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.persist.dao.map.statistics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.*; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDaoTest.java index 571c4dc906..e73250fe61 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDaoTest.java @@ -17,10 +17,10 @@ public class PluginDaoTest extends PersistTestFunctions { public void testGetPlugins() { assertTrue(pluginDao.getAll().size() >= 0); } - + @Test public void testAddPlugin() { - Plugin plugin =new Plugin(); + Plugin plugin = new Plugin(); plugin.setHash("x"); plugin.setName("Plugin name"); plugin.setVersion("0.0.1"); diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDaoTest.java index e0311262ea..fbcb0795e7 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/plugin/PluginDataEntryDaoTest.java @@ -21,17 +21,17 @@ public class PluginDataEntryDaoTest extends PersistTestFunctions { @Test public void testGetByKeyForGlobalParam() { - Plugin plugin =new Plugin(); + Plugin plugin = new Plugin(); plugin.setHash("x"); plugin.setName("Plugin name"); plugin.setVersion("0.0.1"); pluginDao.add(plugin); - + PluginDataEntry entry = new PluginDataEntry(); entry.setPlugin(plugin); entry.setKey("x"); entry.setValue("y"); - + pluginDataEntryDao.add(entry); PluginDataEntry entry2 = pluginDataEntryDao.getByKey(entry.getPlugin(), entry.getKey(), entry.getUser()); @@ -42,23 +42,23 @@ public class PluginDataEntryDaoTest extends PersistTestFunctions { @Test public void testGetByKeyForUserParam() { User user = createUser(); - Plugin plugin =new Plugin(); + Plugin plugin = new Plugin(); plugin.setHash("x"); plugin.setName("Plugin name"); plugin.setVersion("0.0.1"); pluginDao.add(plugin); - + PluginDataEntry entry = new PluginDataEntry(); entry.setPlugin(plugin); entry.setUser(user); entry.setKey("x"); entry.setValue("y"); - + pluginDataEntryDao.add(entry); PluginDataEntry entry2 = pluginDataEntryDao.getByKey(entry.getPlugin(), entry.getKey(), user); assertEquals(entry, entry2); - + assertNull(pluginDataEntryDao.getByKey(entry.getPlugin(), "blabla", user)); assertNull(pluginDataEntryDao.getByKey(entry.getPlugin(), entry.getKey(), null)); } diff --git a/persist/src/test/java/lcsb/mapviewer/persist/dao/user/UserDaoTest.java b/persist/src/test/java/lcsb/mapviewer/persist/dao/user/UserDaoTest.java index d1fd99e485..363cb67214 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/dao/user/UserDaoTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/dao/user/UserDaoTest.java @@ -85,7 +85,6 @@ public class UserDaoTest extends PersistTestFunctions { } } - @Test(expected = PropertyValueException.class) public void testTryUserWithNullLogin() { try { @@ -106,7 +105,7 @@ public class UserDaoTest extends PersistTestFunctions { user.setLogin(testLogin); user.setCryptedPassword(""); userDao.add(user); - + User user2 = new User(); user2.setLogin(testLogin); user2.setCryptedPassword(""); diff --git a/persist/src/test/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapperTest.java b/persist/src/test/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapperTest.java index 8c9b78c29b..1525c38493 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapperTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/mapper/ArrowTypeDataMapperTest.java @@ -5,14 +5,11 @@ import static org.junit.Assert.assertTrue; import java.io.Serializable; -import org.apache.logging.log4j.*; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.junit.*; -import lcsb.mapviewer.model.graphics.ArrowType; -import lcsb.mapviewer.model.graphics.ArrowTypeData; -import lcsb.mapviewer.model.graphics.LineType; +import lcsb.mapviewer.model.graphics.*; public class ArrowTypeDataMapperTest { Logger logger = LogManager.getLogger(ArrowTypeDataMapperTest.class); @@ -35,7 +32,7 @@ public class ArrowTypeDataMapperTest { atd2.setArrowLineType(LineType.DASHED); atd2.setArrowType(ArrowType.BLANK); atd2.setLen(33.3); - + } @After diff --git a/persist/src/test/java/lcsb/mapviewer/persist/mapper/Point2DMapperTest.java b/persist/src/test/java/lcsb/mapviewer/persist/mapper/Point2DMapperTest.java index 252cc6c5d1..83db3ca64d 100644 --- a/persist/src/test/java/lcsb/mapviewer/persist/mapper/Point2DMapperTest.java +++ b/persist/src/test/java/lcsb/mapviewer/persist/mapper/Point2DMapperTest.java @@ -6,9 +6,7 @@ import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; import java.io.Serializable; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; public class Point2DMapperTest { diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java index 2f9942b3e9..b7be8ff5af 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java @@ -1,28 +1,16 @@ package lcsb.mapviewer.api; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; +import java.util.*; + +import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.commons.lang3.math.NumberUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @@ -30,32 +18,19 @@ import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.Article; import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.services.MiriamConnector; -import lcsb.mapviewer.annotation.services.PubmedParser; -import lcsb.mapviewer.annotation.services.PubmedSearchException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.common.comparator.StringComparator; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.common.exception.NotImplementedException; +import lcsb.mapviewer.common.exception.*; import lcsb.mapviewer.converter.Converter; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; import lcsb.mapviewer.converter.model.sbgnml.SbgnmlXmlConverter; import lcsb.mapviewer.converter.model.sbml.SbmlParser; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; 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.user.annotator.AnnotatorConfigParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorParameter; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IProjectService; -import lcsb.mapviewer.services.interfaces.IUserService; +import lcsb.mapviewer.model.user.annotator.*; +import lcsb.mapviewer.services.interfaces.*; import lcsb.mapviewer.services.search.ElementMatcher; @Transactional diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/ContentNegotiationConfig.java b/rest-api/src/main/java/lcsb/mapviewer/api/ContentNegotiationConfig.java index 1a23890595..73ba8a2b47 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/ContentNegotiationConfig.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/ContentNegotiationConfig.java @@ -1,9 +1,7 @@ package lcsb.mapviewer.api; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.config.annotation.*; /** * This class is a configuration for spring that disables content type @@ -24,9 +22,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class ContentNegotiationConfig implements WebMvcConfigurer { - @Override - public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - // Turn off suffix-based content negotiation - configurer.favorPathExtension(false); - } + @Override + public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { + // Turn off suffix-based content negotiation + configurer.favorPathExtension(false); + } } \ No newline at end of file diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/ElementIdentifierType.java b/rest-api/src/main/java/lcsb/mapviewer/api/ElementIdentifierType.java index 5bae9785dd..82f8d7a448 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/ElementIdentifierType.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/ElementIdentifierType.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.api; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Enum identifying type of {@link ElementIdentifier}. @@ -25,13 +26,12 @@ public enum ElementIdentifierType { */ REACTION("REACTION"); + private static Logger logger = LogManager.getLogger(ElementIdentifierType.class); /** * String used in JavaScript code to identify type. */ private String jsName; - private static Logger logger = LogManager.getLogger(ElementIdentifierType.class); - /** * Constructor initializing enum type. * @@ -42,17 +42,9 @@ public enum ElementIdentifierType { this.jsName = jsName; } - /** - * @return the jsName - * @see #jsName - */ - public String getJsName() { - return jsName; - } - /** * Returns {@link ElementIdentifierType} by the JavaScript name. - * + * * @param jsName * JavaScript name of the type * @return {@link ElementIdentifierType} by the JavaScript name @@ -67,4 +59,12 @@ public enum ElementIdentifierType { return null; } + /** + * @return the jsName + * @see #jsName + */ + public String getJsName() { + return jsName; + } + } \ No newline at end of file diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/ObjectNotFoundException.java b/rest-api/src/main/java/lcsb/mapviewer/api/ObjectNotFoundException.java index 5754c1c7d3..d0c05917af 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/ObjectNotFoundException.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/ObjectNotFoundException.java @@ -8,31 +8,31 @@ package lcsb.mapviewer.api; */ public class ObjectNotFoundException extends QueryException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * error message - */ - public ObjectNotFoundException(String message) { - super(message); - } + /** + * Default constructor. + * + * @param message + * error message + */ + public ObjectNotFoundException(String message) { + super(message); + } - /** - * Constructor with error message and parent exception. - * - * @param message - * error message - * @param reason - * parent exception that caused this one - */ - public ObjectNotFoundException(String message, Exception reason) { - super(message, reason); - } + /** + * Constructor with error message and parent exception. + * + * @param message + * error message + * @param reason + * parent exception that caused this one + */ + public ObjectNotFoundException(String message, Exception reason) { + super(message, reason); + } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/QueryException.java b/rest-api/src/main/java/lcsb/mapviewer/api/QueryException.java index 11abd5a073..01b2f8dd15 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/QueryException.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/QueryException.java @@ -8,35 +8,35 @@ package lcsb.mapviewer.api; */ public class QueryException extends Exception { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Default constructor. - * - * @param message - * error message - */ - public QueryException(String message) { - super(message); - } + /** + * Default constructor. + * + * @param message + * error message + */ + public QueryException(String message) { + super(message); + } public QueryException(Exception e) { super(e); } - /** - * Constructor with error message and parent exception. - * - * @param message - * error message - * @param reason - * parent exception that caused this one - */ - public QueryException(String message, Exception reason) { - super(message, reason); - } + /** + * Constructor with error message and parent exception. + * + * @param message + * error message + * @param reason + * parent exception that caused this one + */ + public QueryException(String message, Exception reason) { + super(message, reason); + } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/SpringRestApiConfig.java b/rest-api/src/main/java/lcsb/mapviewer/api/SpringRestApiConfig.java index 4be01b64b1..2836562969 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/SpringRestApiConfig.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/SpringRestApiConfig.java @@ -1,16 +1,14 @@ package lcsb.mapviewer.api; -import lcsb.mapviewer.services.SpringServiceConfig; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.*; import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import lcsb.mapviewer.services.SpringServiceConfig; + @Configuration @EnableWebMvc -@Import({SpringServiceConfig.class}) -@ComponentScan(basePackages = {"lcsb.mapviewer.api"}) +@Import({ SpringServiceConfig.class }) +@ComponentScan(basePackages = { "lcsb.mapviewer.api" }) public class SpringRestApiConfig { } - diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java index 177fd53650..2fa57722c1 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java @@ -1,16 +1,9 @@ package lcsb.mapviewer.api.configuration; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.TreeMap; +import java.util.*; -import lcsb.mapviewer.model.security.PrivilegeType; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -32,9 +25,8 @@ import lcsb.mapviewer.model.map.model.SubmodelType; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.field.ModificationState; -import lcsb.mapviewer.model.user.ConfigurationElementEditType; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.ConfigurationOption; +import lcsb.mapviewer.model.security.PrivilegeType; +import lcsb.mapviewer.model.user.*; import lcsb.mapviewer.model.user.annotator.BioEntityField; import lcsb.mapviewer.modelutils.map.ClassTreeNode; import lcsb.mapviewer.modelutils.map.ElementUtils; @@ -61,7 +53,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { public List<Map<String, Object>> getAllValues() { List<Map<String, Object>> result = new ArrayList<>(); - for (ConfigurationOption option : configurationService.getAllValues()){ + for (ConfigurationOption option : configurationService.getAllValues()) { result.add(optionToMap(option)); } return result; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertController.java b/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertController.java index f7287da9c9..6bfd47dbc4 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertController.java @@ -4,7 +4,8 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.sbml.jsbml.SBMLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -21,48 +22,47 @@ import lcsb.mapviewer.model.map.InconsistentModelException; @RestController @RequestMapping(value = "/convert", produces = MediaType.APPLICATION_JSON_VALUE) public class ConvertController extends BaseController { - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(ConvertController.class); + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(ConvertController.class); - private ConvertRestImpl convertController; + private ConvertRestImpl convertController; - @Autowired - public ConvertController(ConvertRestImpl convertController) { - this.convertController = convertController; - } + @Autowired + public ConvertController(ConvertRestImpl convertController) { + this.convertController = convertController; + } - @PostMapping(value = "/{fromFormat}:{toFormat}", produces = MediaType.APPLICATION_XML_VALUE) - public String convertInput(@PathVariable(value = "fromFormat") String fromFormat, - @PathVariable(value = "toFormat") String toFormat, - @RequestBody String body) - throws IOException, QueryException, SBMLException, - InvalidInputDataExecption, InconsistentModelException, ConverterException - { - return convertController.convert(fromFormat, toFormat, body); - } + @PostMapping(value = "/{fromFormat}:{toFormat}", produces = MediaType.APPLICATION_XML_VALUE) + public String convertInput(@PathVariable(value = "fromFormat") String fromFormat, + @PathVariable(value = "toFormat") String toFormat, + @RequestBody String body) + throws IOException, QueryException, SBMLException, + InvalidInputDataExecption, InconsistentModelException, ConverterException { + return convertController.convert(fromFormat, toFormat, body); + } - @PostMapping(value = "/image/{fromFormat}:{toFormat}") - public @ResponseBody ResponseEntity<byte[]> convertInputToImage( - @PathVariable(value = "fromFormat") String fromFormat, - @PathVariable(value = "toFormat") String toFormat, - @RequestBody String body) - throws IOException, QueryException, SBMLException, InvalidInputDataExecption, ConverterException, DrawingException - { - ByteArrayOutputStream os = convertController.converToImage(fromFormat, toFormat, body); - return ResponseEntity.ok().contentLength(os.size()) - .contentType(MediaType.APPLICATION_OCTET_STREAM) - .header("Content-Disposition", "attachment; filename=model" + toFormat ) - .body(os.toByteArray()); - } + @PostMapping(value = "/image/{fromFormat}:{toFormat}") + public @ResponseBody ResponseEntity<byte[]> convertInputToImage( + @PathVariable(value = "fromFormat") String fromFormat, + @PathVariable(value = "toFormat") String toFormat, + @RequestBody String body) + throws IOException, QueryException, SBMLException, InvalidInputDataExecption, ConverterException, + DrawingException { + ByteArrayOutputStream os = convertController.converToImage(fromFormat, toFormat, body); + return ResponseEntity.ok().contentLength(os.size()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .header("Content-Disposition", "attachment; filename=model" + toFormat) + .body(os.toByteArray()); + } - @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }) - public Map<String, Object> getInformation() { - return convertController.getInformation(); - } + @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }) + public Map<String, Object> getInformation() { + return convertController.getInformation(); + } - @RequestMapping(value = "/image/", method = { RequestMethod.GET, RequestMethod.POST }) - public Map<String, Object> getInformationImage() { - return convertController.getInformationImage(); - } + @RequestMapping(value = "/image/", method = { RequestMethod.GET, RequestMethod.POST }) + public Map<String, Object> getInformationImage() { + return convertController.getInformationImage(); + } } \ No newline at end of file diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertRestImpl.java index 1824c0bcf4..d763144b87 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/convert/ConvertRestImpl.java @@ -1,16 +1,10 @@ package lcsb.mapviewer.api.convert; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; @@ -22,13 +16,9 @@ import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.api.BaseRestImpl; import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.converter.ConverterException; +import lcsb.mapviewer.converter.*; import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.Converter; -import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.DrawingException; -import lcsb.mapviewer.converter.graphics.ImageGenerators; +import lcsb.mapviewer.converter.graphics.*; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.model.Model; @@ -36,156 +26,154 @@ import lcsb.mapviewer.model.map.model.Model; @Service public class ConvertRestImpl extends BaseRestImpl { - private Logger logger = LogManager.getLogger(ConvertRestImpl.class); - + private Logger logger = LogManager.getLogger(ConvertRestImpl.class); public String convert(String fromFormat, String toFormat, String input) - throws InvalidInputDataExecption, SBMLException, InconsistentModelException, IOException, ConverterException, QueryException - { - ConverterParams params = createConvertParams(input); - Model model = getModelParserByNameOrClass(fromFormat).createModel(params); - - Converter exporter = getModelParserByNameOrClass(toFormat); - return IOUtils.toString(exporter.model2InputStream(model), StandardCharsets.UTF_8); + throws InvalidInputDataExecption, SBMLException, InconsistentModelException, IOException, ConverterException, + QueryException { + ConverterParams params = createConvertParams(input); + Model model = getModelParserByNameOrClass(fromFormat).createModel(params); + + Converter exporter = getModelParserByNameOrClass(toFormat); + return IOUtils.toString(exporter.model2InputStream(model), StandardCharsets.UTF_8); } - + public ByteArrayOutputStream converToImage(String fromFormat, String toFormat, String input, - Double targetWidth, Double targetHeight) - throws InvalidInputDataExecption, SBMLException, IOException, ConverterException, DrawingException, QueryException - { - Model model = getModelParserByNameOrClass(fromFormat).createModel(createConvertParams(input)); - - AbstractImageGenerator generator = getImageGenerator(toFormat, createImageParams(model, targetWidth, targetHeight)); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - generator.saveToOutputStream(os); - return os; + Double targetWidth, Double targetHeight) + throws InvalidInputDataExecption, SBMLException, IOException, ConverterException, DrawingException, + QueryException { + Model model = getModelParserByNameOrClass(fromFormat).createModel(createConvertParams(input)); + + AbstractImageGenerator generator = getImageGenerator(toFormat, createImageParams(model, targetWidth, targetHeight)); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + generator.saveToOutputStream(os); + return os; } - + public ByteArrayOutputStream converToImage(String fromFormat, String toFormat, String input) - throws InvalidInputDataExecption, SBMLException, IOException, ConverterException, DrawingException, QueryException - { - return converToImage(fromFormat, toFormat, input, 0.0, 0.0); + throws InvalidInputDataExecption, SBMLException, IOException, ConverterException, DrawingException, + QueryException { + return converToImage(fromFormat, toFormat, input, 0.0, 0.0); } - - public Map<String, Object> getInformation(){ - Map<String, Object> info = new LinkedHashMap<>(); - - - List<Object> converters = new ArrayList<>(); - for (Converter converter: getModelConverters()) { - - List<String> names = new ArrayList<>(); - names.add(removeWhiteSpaces(converter.getCommonName())); - names.add(converter.getClass().getCanonicalName()); - - Map<String, Object> names_item = new LinkedHashMap<>(); - names_item.put("available_names", names); - converters.add(names_item); - } - - info.put("inputs", converters); - info.put("outputs", converters); - return info; + + public Map<String, Object> getInformation() { + Map<String, Object> info = new LinkedHashMap<>(); + + List<Object> converters = new ArrayList<>(); + for (Converter converter : getModelConverters()) { + + List<String> names = new ArrayList<>(); + names.add(removeWhiteSpaces(converter.getCommonName())); + names.add(converter.getClass().getCanonicalName()); + + Map<String, Object> names_item = new LinkedHashMap<>(); + names_item.put("available_names", names); + converters.add(names_item); + } + + info.put("inputs", converters); + info.put("outputs", converters); + return info; } - - public Map<String, Object> getInformationImage(){ - Map<String, Object> info = getInformation(); - - List<Object> generators = new ArrayList<>(); - ImageGenerators igs = new ImageGenerators(); - for (Pair<String, Class<? extends AbstractImageGenerator>> generator: igs.getAvailableImageGenerators()) { - - List<String> names = new ArrayList<>(); - names.add(igs.getExtension(generator.getRight())); - names.add(generator.getRight().getCanonicalName()); - - Map<String, Object> names_item = new LinkedHashMap<>(); - names_item.put("available_names", names); - generators.add(names_item); - } - - info.remove("outputs"); - info.put("outputs", generators); - return info; + + public Map<String, Object> getInformationImage() { + Map<String, Object> info = getInformation(); + + List<Object> generators = new ArrayList<>(); + ImageGenerators igs = new ImageGenerators(); + for (Pair<String, Class<? extends AbstractImageGenerator>> generator : igs.getAvailableImageGenerators()) { + + List<String> names = new ArrayList<>(); + names.add(igs.getExtension(generator.getRight())); + names.add(generator.getRight().getCanonicalName()); + + Map<String, Object> names_item = new LinkedHashMap<>(); + names_item.put("available_names", names); + generators.add(names_item); + } + + info.remove("outputs"); + info.put("outputs", generators); + return info; } - + private Converter getModelParserByNameOrClass(String id) throws QueryException { - try { - return getModelParserByName(id); - } catch (QueryException e) { - return getModelParser(id); - } + try { + return getModelParserByName(id); + } catch (QueryException e) { + return getModelParser(id); + } } - + private String removeWhiteSpaces(String str) { - return str.replace(' ', '_'); + return str.replace(' ', '_'); } - + private Converter getModelParserByName(String name) throws QueryException { - for (Converter converter : getModelConverters()) { - if (removeWhiteSpaces(converter.getCommonName()).equals(name)) { - return converter; - } - } - throw new QueryException("Unknown parser name: " + name); + for (Converter converter : getModelConverters()) { + if (removeWhiteSpaces(converter.getCommonName()).equals(name)) { + return converter; + } + } + throw new QueryException("Unknown parser name: " + name); } - - private AbstractImageGenerator getImageGenerator(String extOrClass, AbstractImageGenerator.Params params) throws QueryException - { - for (Pair<String, Class<? extends AbstractImageGenerator>> element : new ImageGenerators().getAvailableImageGenerators()) { - - try { - Class<? extends AbstractImageGenerator> clazz = element.getRight(); - Constructor<?> ctor = clazz.getConstructor(AbstractImageGenerator.Params.class); - AbstractImageGenerator generator = (AbstractImageGenerator) ctor.newInstance(params); - if (extOrClass.equals(clazz.getCanonicalName()) || extOrClass.equals(generator.getFileExtension())) { - return generator; - } - - } catch (NoSuchMethodException | java.lang.SecurityException | InstantiationException - | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - logger.error("Creation of image generator class for '" + element.getLeft() + "' failed."); - throw new QueryException("Issue with obtaining image generator for extension " + extOrClass + "."); - } - - } - - throw new QueryException("Image generator for extension " + extOrClass + " not available."); - } - - private AbstractImageGenerator.Params createImageParams(Model model, Double targetWidth, Double targetHeight){ - Double padding = 5.0; - Double maxDim = 10000.0; - - Double w = model.getWidth(); - Double h = model.getHeight(); - - if (targetHeight == 0) targetHeight = Math.min(h, maxDim); - if (targetWidth == 0) targetWidth = Math.min(w, maxDim); - - Double scale = targetWidth / w; - if (h * scale > targetHeight) { - scale = targetHeight / h; - } - - Double wScaled = w*scale; - Double hScaled = h*scale; - - return new AbstractImageGenerator.Params(). - model(model). - width(wScaled + padding). - height(hScaled + padding). - scale(1/scale) - .x(0); - - } - -private ConverterParams createConvertParams(String input) { - ConverterParams params = new ConverterParams(); - InputStream is = new ByteArrayInputStream(input.getBytes()); - - params.inputStream(is); - - return params; + + private AbstractImageGenerator getImageGenerator(String extOrClass, AbstractImageGenerator.Params params) + throws QueryException { + for (Pair<String, Class<? extends AbstractImageGenerator>> element : new ImageGenerators() + .getAvailableImageGenerators()) { + + try { + Class<? extends AbstractImageGenerator> clazz = element.getRight(); + Constructor<?> ctor = clazz.getConstructor(AbstractImageGenerator.Params.class); + AbstractImageGenerator generator = (AbstractImageGenerator) ctor.newInstance(params); + if (extOrClass.equals(clazz.getCanonicalName()) || extOrClass.equals(generator.getFileExtension())) { + return generator; + } + + } catch (NoSuchMethodException | java.lang.SecurityException | InstantiationException + | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + logger.error("Creation of image generator class for '" + element.getLeft() + "' failed."); + throw new QueryException("Issue with obtaining image generator for extension " + extOrClass + "."); + } + + } + + throw new QueryException("Image generator for extension " + extOrClass + " not available."); + } + + private AbstractImageGenerator.Params createImageParams(Model model, Double targetWidth, Double targetHeight) { + Double padding = 5.0; + Double maxDim = 10000.0; + + Double w = model.getWidth(); + Double h = model.getHeight(); + + if (targetHeight == 0) + targetHeight = Math.min(h, maxDim); + if (targetWidth == 0) + targetWidth = Math.min(w, maxDim); + + Double scale = targetWidth / w; + if (h * scale > targetHeight) { + scale = targetHeight / h; + } + + Double wScaled = w * scale; + Double hScaled = h * scale; + + return new AbstractImageGenerator.Params().model(model).width(wScaled + padding).height(hScaled + padding) + .scale(1 / scale) + .x(0); + + } + + private ConverterParams createConvertParams(String input) { + ConverterParams params = new ConverterParams(); + InputStream is = new ByteArrayInputStream(input.getBytes()); + + params.inputStream(is); + + return params; } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/files/FileController.java b/rest-api/src/main/java/lcsb/mapviewer/api/files/FileController.java index ca66ec9014..fee30ce281 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/files/FileController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/files/FileController.java @@ -2,7 +2,6 @@ package lcsb.mapviewer.api.files; import java.util.Map; -import lcsb.mapviewer.services.interfaces.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PostAuthorize; @@ -12,6 +11,7 @@ import org.springframework.web.bind.annotation.*; import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.ObjectNotFoundException; +import lcsb.mapviewer.services.interfaces.IUserService; @RestController @RequestMapping(value = "/files", produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeController.java b/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeController.java index ca2fa051d2..e3aa38fe52 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeController.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.util.List; import java.util.Map; -import lcsb.mapviewer.api.ObjectNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; @@ -12,8 +11,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnectorException; -import lcsb.mapviewer.api.BaseController; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; @RestController @RequestMapping(value = "/genomics", produces = MediaType.APPLICATION_JSON_VALUE) @@ -50,11 +48,11 @@ public class ReferenceGenomeController extends BaseController { @PreAuthorize("hasAuthority('IS_ADMIN')") @PostMapping(value = "/") public Map<String, Object> addGenome(@RequestBody MultiValueMap<String, Object> formData) - throws QueryException, IOException, ReferenceGenomeConnectorException { + throws QueryException, IOException, ReferenceGenomeConnectorException { return referenceGenomeController.addReferenceGenome(formData); } - @GetMapping(value = "/" ) + @GetMapping(value = "/") public List<Map<String, Object>> getDownloaded() { return referenceGenomeController.getReferenceGenomes(); } @@ -82,9 +80,8 @@ public class ReferenceGenomeController extends BaseController { @DeleteMapping(value = "/{genomeId}/geneMapping/{mappingId}/") public Map<String, Object> removeGeneMapping( @PathVariable(value = "genomeId") String genomeId, - @PathVariable(value = "mappingId") String mappingId - ) throws IOException, ObjectNotFoundException { - return referenceGenomeController.removeGeneMapping(genomeId,mappingId); + @PathVariable(value = "mappingId") String mappingId) throws IOException, ObjectNotFoundException { + return referenceGenomeController.removeGeneMapping(genomeId, mappingId); } @PreAuthorize("hasAuthority('IS_ADMIN')") @@ -92,7 +89,7 @@ public class ReferenceGenomeController extends BaseController { public Map<String, Object> addGeneMapping( @PathVariable(value = "genomeId") String genomeId, @RequestBody MultiValueMap<String, Object> formData) - throws QueryException, IOException, ReferenceGenomeConnectorException { + throws QueryException, IOException, ReferenceGenomeConnectorException { return referenceGenomeController.addGeneMapping(formData, genomeId); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java index 9de6bd5bc9..d6271f6d2b 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java @@ -3,15 +3,10 @@ package lcsb.mapviewer.api.genomics; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -19,15 +14,10 @@ import org.springframework.util.MultiValueMap; import lcsb.mapviewer.annotation.cache.BigFileCache; import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnectorException; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ObjectExistsException; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; import lcsb.mapviewer.services.utils.ReferenceGenomeExistsException; @@ -64,8 +54,7 @@ public class ReferenceGenomeRestImpl extends BaseRestImpl { try { ReferenceGenomeType genomeType = ReferenceGenomeType.valueOf(type); version = version.replaceAll("\\*", ""); - ReferenceGenome genome = referenceGenomeService.getReferenceGenomeViewByParams(organism, genomeType, version - ); + ReferenceGenome genome = referenceGenomeService.getReferenceGenomeViewByParams(organism, genomeType, version); if (genome == null) { throw new ObjectNotFoundException("Cannot find requested reference genome"); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java b/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java index 5fa4891dd9..a308997f26 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java @@ -2,14 +2,15 @@ package lcsb.mapviewer.api.mesh; import java.util.Map; -import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; -import lcsb.mapviewer.api.ObjectNotFoundException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; +import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.api.BaseController; +import lcsb.mapviewer.api.ObjectNotFoundException; @RestController @RequestMapping(value = "/mesh", produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshRestImpl.java index b6ae5237bc..5988f8cced 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshRestImpl.java @@ -1,9 +1,10 @@ package lcsb.mapviewer.api.mesh; -import java.util.TreeMap; import java.util.Map; +import java.util.TreeMap; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/MinervaNetController.java b/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/MinervaNetController.java index 8077da81e0..798531448e 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/MinervaNetController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/MinervaNetController.java @@ -1,10 +1,9 @@ package lcsb.mapviewer.api.minervanet; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import lcsb.mapviewer.api.BaseController; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.services.interfaces.IConfigurationService; +import java.io.IOException; + +import javax.servlet.ServletContext; + import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; @@ -13,12 +12,17 @@ import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import javax.servlet.ServletContext; -import java.io.IOException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +import lcsb.mapviewer.api.BaseController; +import lcsb.mapviewer.model.user.ConfigurationElementType; +import lcsb.mapviewer.services.interfaces.IConfigurationService; @RestController @RequestMapping("/minervanet") diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/ReportSubmissionException.java b/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/ReportSubmissionException.java index edf3480c67..d211dd2518 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/ReportSubmissionException.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/minervanet/ReportSubmissionException.java @@ -22,7 +22,8 @@ public class ReportSubmissionException extends RuntimeException { super(cause); } - protected ReportSubmissionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + protected ReportSubmissionException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginController.java b/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginController.java index 0a874b9635..68d9cc937e 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginController.java @@ -3,9 +3,8 @@ package lcsb.mapviewer.api.plugins; import java.util.List; import java.util.Map; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IUserService; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; @@ -14,6 +13,8 @@ import org.springframework.web.bind.annotation.*; import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.ObjectNotFoundException; +import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.services.interfaces.IUserService; @RestController @RequestMapping(value = "/plugins", produces = MediaType.APPLICATION_JSON_VALUE) @@ -67,8 +68,7 @@ public class PluginController extends BaseController { Authentication authentication, @PathVariable(value = "hash") String hash, @PathVariable(value = "key") String key, - @RequestParam(value = "value", defaultValue = "") String value - ) throws ObjectNotFoundException { + @RequestParam(value = "value", defaultValue = "") String value) throws ObjectNotFoundException { User user = userService.getUserByLogin(authentication.getName()); return pluginRest.createPluginDataEntry(hash, user, key, value); } @@ -77,8 +77,7 @@ public class PluginController extends BaseController { public Map<String, Object> createPluginDataEntry( @PathVariable(value = "hash") String hash, @PathVariable(value = "key") String key, - @RequestParam(value = "value", defaultValue = "") String value - ) throws ObjectNotFoundException { + @RequestParam(value = "value", defaultValue = "") String value) throws ObjectNotFoundException { return pluginRest.createPluginDataEntry(hash, null, key, value); } @@ -86,8 +85,7 @@ public class PluginController extends BaseController { public Map<String, Object> getPluginDataEntry( Authentication authentication, @PathVariable(value = "hash") String hash, - @PathVariable(value = "key") String key - ) throws ObjectNotFoundException { + @PathVariable(value = "key") String key) throws ObjectNotFoundException { User user = userService.getUserByLogin(authentication.getName()); return pluginRest.getPluginDataEntry(hash, user, key); } @@ -95,8 +93,7 @@ public class PluginController extends BaseController { @GetMapping(value = "/{hash}/data/global/{key}") public Map<String, Object> getPluginDataEntry( @PathVariable(value = "hash") String hash, - @PathVariable(value = "key") String key - ) throws ObjectNotFoundException { + @PathVariable(value = "key") String key) throws ObjectNotFoundException { return pluginRest.getPluginDataEntry(hash, null, key); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginRestImpl.java index 57b0994f20..8a676d07ac 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/plugins/PluginRestImpl.java @@ -1,10 +1,6 @@ package lcsb.mapviewer.api.plugins; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java index 5424d80a2e..00139e1e0f 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java @@ -509,35 +509,6 @@ public class ProjectRestImpl extends BaseRestImpl { return getProject(projectId); } - private enum LogSortColumn { - ID("id"), - CONTENT("content"); - - private String commonName; - - LogSortColumn(String commonName) { - this.commonName = commonName; - } - } - - private class LogEntry implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - public LogEntry(int id, String content, String level) { - this.id = id; - this.content = content; - this.level = level; - } - - public Integer id; - public String content; - @SuppressWarnings("unused") - public String level; - } - public Map<String, Object> getLogs(String projectId, String level, String startString, Integer length, String sortColumn, String sortOrder, String search) throws QueryException { Project project = getProjectService().getProjectByProjectId(projectId); @@ -721,4 +692,31 @@ public class ProjectRestImpl extends BaseRestImpl { } } + private enum LogSortColumn { + ID("id"), + CONTENT("content"); + + private String commonName; + + LogSortColumn(String commonName) { + this.commonName = commonName; + } + } + + private class LogEntry implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + public Integer id; + public String content; + @SuppressWarnings("unused") + public String level; + public LogEntry(int id, String content, String level) { + this.id = id; + this.content = content; + this.level = level; + } + } + } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalController.java index 7ab8ad17d0..1490893a5b 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalController.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.api.projects.chemicals; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -30,8 +28,7 @@ public class ChemicalController extends BaseController { @PathVariable(value = "projectId") String projectId, @RequestParam(value = "columns", defaultValue = "") String columns, @RequestParam(value = "query", defaultValue = "") String query, - @RequestParam(value = "target", defaultValue = "") String target - ) throws QueryException { + @RequestParam(value = "target", defaultValue = "") String target) throws QueryException { if (!query.equals("")) { return chemicalController.getChemicalsByQuery(projectId, columns, query); } else if (target.contains(":")) { diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java index 7c11c2a048..f154db8981 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java @@ -2,21 +2,17 @@ package lcsb.mapviewer.api.projects.chemicals; import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.Chemical; import lcsb.mapviewer.annotation.data.MeSH; -import lcsb.mapviewer.annotation.services.ChemicalParser; -import lcsb.mapviewer.annotation.services.ChemicalSearchException; -import lcsb.mapviewer.annotation.services.MeSHParser; -import lcsb.mapviewer.annotation.services.TaxonomyBackend; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ElementIdentifierType; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.model.Model; @@ -81,57 +77,57 @@ public class ChemicalRestImpl extends BaseRestImpl { String description = "Mesh term not available"; List<String> synonyms = new ArrayList<>(); - try { - MeSH mesh = meSHParser.getMeSH(chemical.getChemicalId()); - if (mesh != null) { - description = mesh.getDescription(); - synonyms = mesh.getSynonyms(); - } else { - logger.warn("Mesh used by chemical is invalid: " + chemical.getChemicalId()); - } - } catch (AnnotatorException e) { - logger.error("Problem with accessing mesh database", e); - } + try { + MeSH mesh = meSHParser.getMeSH(chemical.getChemicalId()); + if (mesh != null) { + description = mesh.getDescription(); + synonyms = mesh.getSynonyms(); + } else { + logger.warn("Mesh used by chemical is invalid: " + chemical.getChemicalId()); + } + } catch (AnnotatorException e) { + logger.error("Problem with accessing mesh database", e); + } for (String string : columnsSet) { String column = string.toLowerCase(); Object value = null; switch (column) { - case "id": - case "idobject": - value = chemical.getChemicalId(); - break; - case "name": - value = chemical.getChemicalName(); - break; - case "references": - List<Map<String, Object>> references = new ArrayList<>(); - references.add(createAnnotation(chemical.getChemicalId())); - if (chemical.getCasID() != null) { - references.add(createAnnotation(chemical.getCasID())); - } - value = references; - break; - case "directevidencereferences": - value = createAnnotations(chemical.getDirectEvidencePublication()); - break; - case "description": - value = description; - break; - case "directevidence": - if (chemical.getDirectEvidence() != null) { - value = chemical.getDirectEvidence().getValue(); - } - break; - case "synonyms": - value = synonyms; - break; - case "targets": - value = prepareTargets(chemical.getInferenceNetwork(), models); - break; - default: - value = "Unknown column"; - break; + case "id": + case "idobject": + value = chemical.getChemicalId(); + break; + case "name": + value = chemical.getChemicalName(); + break; + case "references": + List<Map<String, Object>> references = new ArrayList<>(); + references.add(createAnnotation(chemical.getChemicalId())); + if (chemical.getCasID() != null) { + references.add(createAnnotation(chemical.getCasID())); + } + value = references; + break; + case "directevidencereferences": + value = createAnnotations(chemical.getDirectEvidencePublication()); + break; + case "description": + value = description; + break; + case "directevidence": + if (chemical.getDirectEvidence() != null) { + value = chemical.getDirectEvidence().getValue(); + } + break; + case "synonyms": + value = synonyms; + break; + case "targets": + value = prepareTargets(chemical.getInferenceNetwork(), models); + break; + default: + value = "Unknown column"; + break; } result.put(string, value); } @@ -156,7 +152,7 @@ public class ChemicalRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getChemicalsByTarget(String projectId, String targetType, - String targetId, String columns) throws QueryException { + String targetId, String columns) throws QueryException { Model model = getModelService().getLastModelByProjectId(projectId); if (model == null) { throw new QueryException("Project with given id doesn't exist"); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentController.java index 27a107f30d..e1a9f7d38e 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentController.java @@ -21,7 +21,7 @@ import lcsb.mapviewer.model.security.PrivilegeType; @RestController @RequestMapping(value = "/projects/{projectId}/comments", produces = MediaType.APPLICATION_JSON_VALUE) public class CommentController extends BaseController { - + Logger logger = LogManager.getLogger(); private CommentRestImpl commentController; @@ -41,11 +41,13 @@ public class CommentController extends BaseController { Authentication authentication, @PathVariable(value = "projectId") String projectId, @RequestParam(value = "columns", defaultValue = "") String columns, - @RequestParam(value = "removed", defaultValue = "") String removed - ) throws QueryException { - boolean isAdmin = authentication.getAuthorities().contains(new SimpleGrantedAuthority(PrivilegeType.IS_ADMIN.name())); - boolean isProjectCurator = authentication.getAuthorities().contains(new SimpleGrantedAuthority(PrivilegeType.IS_CURATOR.name())) - && authentication.getAuthorities().contains(new SimpleGrantedAuthority(PrivilegeType.READ_PROJECT.name() + ":" + projectId)); + @RequestParam(value = "removed", defaultValue = "") String removed) throws QueryException { + boolean isAdmin = authentication.getAuthorities() + .contains(new SimpleGrantedAuthority(PrivilegeType.IS_ADMIN.name())); + boolean isProjectCurator = authentication.getAuthorities() + .contains(new SimpleGrantedAuthority(PrivilegeType.IS_CURATOR.name())) + && authentication.getAuthorities() + .contains(new SimpleGrantedAuthority(PrivilegeType.READ_PROJECT.name() + ":" + projectId)); List<Map<String, Object>> comments = commentController.getCommentList( projectId, columns, "", "", removed); @@ -66,8 +68,7 @@ public class CommentController extends BaseController { public Map<String, Object> removeComment( @RequestBody(required = false) String body, @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "commentId") String commentId - ) throws QueryException, IOException { + @PathVariable(value = "commentId") String commentId) throws QueryException, IOException { Map<String, Object> node = parseBody(body); String reason = (String) node.get("reason"); return commentController.removeComment(projectId, commentId, reason); @@ -83,8 +84,7 @@ public class CommentController extends BaseController { @PathVariable(value = "projectId") String projectId, @RequestParam(value = "columns", defaultValue = "") String columns, @PathVariable(value = "reactionId") String reactionId, - @RequestParam(value = "removed", defaultValue = "") String removed - ) throws QueryException { + @RequestParam(value = "removed", defaultValue = "") String removed) throws QueryException { return commentController.getCommentList(projectId, columns, reactionId, ElementIdentifierType.REACTION.getJsName(), removed); } @@ -99,8 +99,7 @@ public class CommentController extends BaseController { @PathVariable(value = "projectId") String projectId, @RequestParam(value = "columns", defaultValue = "") String columns, @PathVariable(value = "elementId") String elementId, - @RequestParam(value = "removed", defaultValue = "") String removed - ) throws QueryException { + @RequestParam(value = "removed", defaultValue = "") String removed) throws QueryException { return commentController.getCommentList( projectId, columns, elementId, ElementIdentifierType.ALIAS.getJsName(), removed); } @@ -115,8 +114,7 @@ public class CommentController extends BaseController { @PathVariable(value = "projectId") String projectId, @RequestParam(value = "columns", defaultValue = "") String columns, @PathVariable(value = "coordinates") String coordinates, - @RequestParam(value = "removed", defaultValue = "") String removed - ) throws QueryException { + @RequestParam(value = "removed", defaultValue = "") String removed) throws QueryException { return commentController.getCommentList(projectId, columns, coordinates, ElementIdentifierType.POINT.getJsName(), removed); } @@ -131,8 +129,7 @@ public class CommentController extends BaseController { @RequestParam(value = "content") String content, @RequestParam(value = "pinned", defaultValue = "true") String pinned, @RequestParam(value = "coordinates") String coordinates, - @PathVariable(value = "modelId") String modelId - ) throws QueryException { + @PathVariable(value = "modelId") String modelId) throws QueryException { Point2D pointCoordinates = parseCoordinates(coordinates); return commentController.addComment(projectId, ElementIdentifierType.ALIAS.getJsName(), elementId, name, email, content, pinned.toLowerCase().equals("true"), pointCoordinates, modelId); @@ -148,8 +145,7 @@ public class CommentController extends BaseController { @RequestParam(value = "content") String content, @RequestParam(value = "pinned", defaultValue = "true") String pinned, @RequestParam(value = "coordinates") String coordinates, - @PathVariable(value = "modelId") String modelId - ) throws QueryException { + @PathVariable(value = "modelId") String modelId) throws QueryException { Point2D pointCoordinates = parseCoordinates(coordinates); return commentController.addComment(projectId, ElementIdentifierType.REACTION.getJsName(), reactionId, name, email, content, pinned.toLowerCase().equals("true"), pointCoordinates, modelId); @@ -164,8 +160,7 @@ public class CommentController extends BaseController { @RequestParam(value = "content") String content, @RequestParam(value = "pinned", defaultValue = "true") String pinned, @PathVariable(value = "coordinates") String coordinates, - @PathVariable(value = "modelId") String modelId - ) throws QueryException { + @PathVariable(value = "modelId") String modelId) throws QueryException { Point2D pointCoordinates = parseCoordinates(coordinates); return commentController.addComment(projectId, ElementIdentifierType.POINT.getJsName(), coordinates, name, email, content, pinned.toLowerCase().equals("true"), pointCoordinates, modelId); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugController.java index 92e263860c..fe9519beb2 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugController.java @@ -1,8 +1,6 @@ package lcsb.mapviewer.api.projects.drugs; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -30,8 +28,7 @@ public class DrugController extends BaseController { @PathVariable(value = "projectId") String projectId, @RequestParam(value = "columns", defaultValue = "") String columns, @RequestParam(value = "query", defaultValue = "") String query, - @RequestParam(value = "target", defaultValue = "") String target - ) throws QueryException { + @RequestParam(value = "target", defaultValue = "") String target) throws QueryException { if (!query.equals("")) { return drugController.getDrugsByQuery(projectId, columns, query); } else if (target.contains(":")) { diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java index 6747226e25..420e788f38 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.api.projects.drugs; import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -10,9 +11,7 @@ import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.Drug; import lcsb.mapviewer.annotation.services.DrugSearchException; import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ElementIdentifierType; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.model.Model; @@ -129,7 +128,7 @@ public class DrugRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getDrugsByTarget(String projectId, String targetType, String targetId, - String columns) throws QueryException { + String columns) throws QueryException { Model model = getModelService().getLastModelByProjectId(projectId); if (model == null) { throw new QueryException("Project with given id doesn't exist"); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java index 73e888a601..82250cbc06 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java @@ -2,18 +2,15 @@ package lcsb.mapviewer.api.projects.mirnas; import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.MiRNA; -import lcsb.mapviewer.annotation.services.MiRNAParser; -import lcsb.mapviewer.annotation.services.MiRNASearchException; -import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ElementIdentifierType; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.annotation.services.*; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.model.Model; @@ -73,17 +70,17 @@ public class MiRnaRestImpl extends BaseRestImpl { String column = string.toLowerCase(); Object value; switch (column) { - case "id": - case "idobject": - case "name": - value = miRna.getName(); - break; - case "targets": - value = prepareTargets(miRna.getTargets(), models); - break; - default: - value = "Unknown column"; - break; + case "id": + case "idobject": + case "name": + value = miRna.getName(); + break; + case "targets": + value = prepareTargets(miRna.getTargets(), models); + break; + default: + value = "Unknown column"; + break; } result.put(string, value); } @@ -103,7 +100,7 @@ public class MiRnaRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getMiRnasByTarget(String projectId, String targetType, String targetId, - String columns) throws QueryException { + String columns) throws QueryException { Model model = getModelService().getLastModelByProjectId(projectId); if (model == null) { throw new QueryException("Project with given id doesn't exist"); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelController.java index b4310eff3f..dabceafea3 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelController.java @@ -4,9 +4,6 @@ import java.io.IOException; import java.util.List; import java.util.Map; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.impl.UserService; -import lcsb.mapviewer.services.interfaces.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -14,15 +11,15 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.*; -import lcsb.mapviewer.api.BaseController; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.converter.ConverterException; import lcsb.mapviewer.converter.graphics.DrawingException; import lcsb.mapviewer.model.cache.FileEntry; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; +import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.services.interfaces.IUserService; @RestController @RequestMapping(value = "/projects/{projectId:.+}/models", produces = MediaType.APPLICATION_JSON_VALUE) @@ -48,8 +45,7 @@ public class ModelController extends BaseController { @GetMapping(value = "/{modelId:.+}") public Object getModel( @PathVariable(value = "modelId") String modelId, - @PathVariable(value = "projectId") String projectId - ) throws ObjectNotFoundException { + @PathVariable(value = "projectId") String projectId) throws ObjectNotFoundException { if (modelId.equals("*")) { return modelController.getModels(projectId); } else { @@ -62,8 +58,7 @@ public class ModelController extends BaseController { public Object updateModel( @PathVariable(value = "modelId") String modelId, @PathVariable(value = "projectId") String projectId, - @RequestBody String body - ) throws IOException, QueryException { + @RequestBody String body) throws IOException, QueryException { Map<String, Object> node = parseBody(body); Map<String, Object> data = getData(node, "model"); return modelController.updateModel(projectId, modelId, data); @@ -79,8 +74,8 @@ public class ModelController extends BaseController { @RequestParam(value = "backgroundOverlayId", defaultValue = "") String backgroundOverlayId, @RequestParam(value = "overlayIds", defaultValue = "") String overlayIds, @RequestParam(value = "zoomLevel", defaultValue = "") String zoomLevel, - @RequestParam(value = "polygonString", defaultValue = "") String polygonString - ) throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, DrawingException { + @RequestParam(value = "polygonString", defaultValue = "") String polygonString) + throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, DrawingException { User user = userService.getUserByLogin(authentication.getName()); FileEntry file = modelController.getModelAsImage( projectId, modelId, handlerClass, backgroundOverlayId, overlayIds, zoomLevel, polygonString, user); @@ -100,8 +95,8 @@ public class ModelController extends BaseController { @RequestParam(value = "overlayIds", defaultValue = "") String overlayIds, @RequestParam(value = "polygonString", defaultValue = "") String polygonString, @RequestParam(value = "elementIds", defaultValue = "") String elementIds, - @RequestParam(value = "reactionIds", defaultValue = "") String reactionIds - ) throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, + @RequestParam(value = "reactionIds", defaultValue = "") String reactionIds) + throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, ConverterException, InconsistentModelException { User user = userService.getUserByLogin(authentication.getName()); FileEntry file = modelController.getModelAsModelFile( diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java index 4cc9e73a85..15c1affd90 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java @@ -1,20 +1,10 @@ package lcsb.mapviewer.api.projects.models; -import java.awt.Color; -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; -import java.awt.geom.Point2D; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; +import java.awt.*; +import java.awt.geom.*; +import java.io.*; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; @@ -23,16 +13,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; -import lcsb.mapviewer.commands.ClearColorModelCommand; -import lcsb.mapviewer.commands.ColorExtractor; -import lcsb.mapviewer.commands.ColorModelCommand; -import lcsb.mapviewer.commands.CommandExecutionException; -import lcsb.mapviewer.commands.CopyCommand; -import lcsb.mapviewer.commands.SetFixedHierarchyLevelCommand; -import lcsb.mapviewer.commands.SubModelCommand; +import lcsb.mapviewer.api.*; +import lcsb.mapviewer.commands.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.converter.Converter; import lcsb.mapviewer.converter.ConverterException; @@ -43,12 +25,8 @@ import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.cache.FileEntry; import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.map.InconsistentModelException; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelData; -import lcsb.mapviewer.model.map.model.SubmodelType; +import lcsb.mapviewer.model.map.layout.*; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.services.interfaces.ILayoutService; @@ -188,8 +166,8 @@ public class ModelRestImpl extends BaseRestImpl { } public FileEntry getModelAsModelFile(String projectId, String modelId, String handlerClass, - String overlayIds, String polygonString, String elementIds, - String reactionIds, User user) + String overlayIds, String polygonString, String elementIds, + String reactionIds, User user) throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, ConverterException, InconsistentModelException { Model originalModel = getModelByModelId(projectId, modelId); @@ -273,7 +251,8 @@ public class ModelRestImpl extends BaseRestImpl { } public FileEntry getModelAsImage(String projectId, String modelId, String handlerClass, - String backgroundOverlayId, String overlayIds, String zoomLevel, String polygonString, User user) throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, DrawingException { + String backgroundOverlayId, String overlayIds, String zoomLevel, String polygonString, User user) + throws QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, DrawingException { Project project = getProjectService().getProjectByProjectId(projectId); Model topModel = getModelService().getLastModelByProjectId(projectId); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesController.java index ffa3eab335..d50410936b 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesController.java @@ -1,9 +1,7 @@ package lcsb.mapviewer.api.projects.models.bioEntities; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -14,8 +12,7 @@ import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.QueryException; @RestController -@RequestMapping(value = "/projects/{projectId}/models/{modelId}/", - produces = MediaType.APPLICATION_JSON_VALUE) +@RequestMapping(value = "/projects/{projectId}/models/{modelId}/", produces = MediaType.APPLICATION_JSON_VALUE) public class BioEntitiesController extends BaseController { private BioEntitiesRestImpl bioEntitiesRestImpl; @@ -34,8 +31,7 @@ public class BioEntitiesController extends BaseController { @RequestParam(value = "query", defaultValue = "") String query, @RequestParam(value = "count", defaultValue = "") String count, @RequestParam(value = "type", defaultValue = "") String type, - @RequestParam(value = "perfectMatch", defaultValue = "false") String perfectMatch - ) throws QueryException { + @RequestParam(value = "perfectMatch", defaultValue = "false") String perfectMatch) throws QueryException { if (!coordinates.trim().isEmpty()) { if (modelId.equals("*")) { throw new QueryException("modelId must be defined when searching by coordinates"); @@ -70,7 +66,7 @@ public class BioEntitiesController extends BaseController { } @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") - @RequestMapping(value = "bioEntities/suggestedQueryList", method = {RequestMethod.GET, RequestMethod.POST }) + @RequestMapping(value = "bioEntities/suggestedQueryList", method = { RequestMethod.GET, RequestMethod.POST }) public String[] getSuggestedQueryList(@PathVariable(value = "projectId") String projectId) { return bioEntitiesRestImpl.getSuggestedQueryList(projectId); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java index be11ccf537..8fbc50e6ae 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java @@ -1,13 +1,10 @@ package lcsb.mapviewer.api.projects.models.bioEntities; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -59,7 +56,7 @@ public class BioEntitiesRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getElementsByQuery(String projectId, String query, - Integer maxElements, String perfectMatch) { + Integer maxElements, String perfectMatch) { List<Map<String, Object>> resultMap = new ArrayList<>(); Model model = getModelService().getLastModelByProjectId(projectId); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsController.java index ac752def6e..79dfaf50ef 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsController.java @@ -6,38 +6,34 @@ import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.QueryException; @RestController -@RequestMapping(value = "/projects/{projectId}/models/{modelId}/bioEntities/elements", - produces = MediaType.APPLICATION_JSON_VALUE) +@RequestMapping(value = "/projects/{projectId}/models/{modelId}/bioEntities/elements", produces = MediaType.APPLICATION_JSON_VALUE) public class ElementsController extends BaseController { - private ElementsRestImpl projectController; + private ElementsRestImpl projectController; - @Autowired - public ElementsController(ElementsRestImpl projectController) { - this.projectController = projectController; - } + @Autowired + public ElementsController(ElementsRestImpl projectController) { + this.projectController = projectController; + } - @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") - @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }) - public List<Map<String, Object>> getElements( - @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "modelId") String modelId, - @RequestParam(value = "id", defaultValue = "") String id, - @RequestParam(value = "type", defaultValue = "") String type, - @RequestParam(value = "columns", defaultValue = "") String columns, - @RequestParam(value = "includedCompartmentIds", defaultValue = "") String includedCompartmentIds, - @RequestParam(value = "excludedCompartmentIds", defaultValue = "") String excludedCompartmentIds - ) throws QueryException { - return projectController.getElements(projectId, id, columns, modelId, type, includedCompartmentIds, excludedCompartmentIds); - } + @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") + @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }) + public List<Map<String, Object>> getElements( + @PathVariable(value = "projectId") String projectId, + @PathVariable(value = "modelId") String modelId, + @RequestParam(value = "id", defaultValue = "") String id, + @RequestParam(value = "type", defaultValue = "") String type, + @RequestParam(value = "columns", defaultValue = "") String columns, + @RequestParam(value = "includedCompartmentIds", defaultValue = "") String includedCompartmentIds, + @RequestParam(value = "excludedCompartmentIds", defaultValue = "") String excludedCompartmentIds) + throws QueryException { + return projectController.getElements(projectId, id, columns, modelId, type, includedCompartmentIds, + excludedCompartmentIds); + } } \ No newline at end of file diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsRestImpl.java index 756a4dabfd..8baf0a46d5 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementsRestImpl.java @@ -2,7 +2,8 @@ package lcsb.mapviewer.api.projects.models.bioEntities.elements; import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -13,23 +14,8 @@ import lcsb.mapviewer.converter.model.celldesigner.structure.fields.Modification import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Element; -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.model.map.species.field.AbstractSiteModification; -import lcsb.mapviewer.model.map.species.field.BindingRegion; -import lcsb.mapviewer.model.map.species.field.CodingRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.ModificationSite; -import lcsb.mapviewer.model.map.species.field.ProteinBindingDomain; -import lcsb.mapviewer.model.map.species.field.RegulatoryRegion; -import lcsb.mapviewer.model.map.species.field.Residue; -import lcsb.mapviewer.model.map.species.field.Structure; -import lcsb.mapviewer.model.map.species.field.TranscriptionSite; -import lcsb.mapviewer.model.map.species.field.UniprotRecord; +import lcsb.mapviewer.model.map.species.*; +import lcsb.mapviewer.model.map.species.field.*; @Transactional @Service @@ -42,7 +28,7 @@ public class ElementsRestImpl extends BaseRestImpl { private Logger logger = LogManager.getLogger(ElementsRestImpl.class); public List<Map<String, Object>> getElements(String projectId, String id, String columns, String modelId, - String type, String includedCompartmentIds, String excludedCompartmentIds) + String type, String includedCompartmentIds, String excludedCompartmentIds) throws QueryException { Set<Integer> ids = new LinkedHashSet<>(); if (!id.equals("")) { @@ -138,98 +124,98 @@ public class ElementsRestImpl extends BaseRestImpl { String column = string.toLowerCase(); Object value = null; switch (column) { - case "id": - case "idobject": - value = element.getId(); - break; - case "modelid": - value = element.getModelData().getId(); - break; - case "elementid": - value = element.getElementId(); - break; - case "name": - value = element.getName(); - break; - case "type": - value = element.getStringType(); - break; - case "symbol": - value = element.getSymbol(); - break; - case "fullname": - value = element.getFullName(); - break; - case "abbreviation": - value = element.getAbbreviation(); - break; - case "compartmentid": - if (element.getCompartment() != null) { - value = element.getCompartment().getId(); - } - break; - case "complexid": - if (element instanceof Species) { - if (((Species) element).getComplex() != null) { - value = ((Species) element).getComplex().getId(); - } - } - break; - case "initialconcentration": - if (element instanceof Species) { - value = ((Species) element).getInitialConcentration(); - } - break; - case "initialamount": - if (element instanceof Species) { - value = ((Species) element).getInitialAmount(); - } - break; - case "boundarycondition": - if (element instanceof Species) { - value = ((Species) element).isBoundaryCondition(); - } - break; - case "constant": - if (element instanceof Species) { - value = ((Species) element).isConstant(); - } - break; - case "references": - value = createAnnotations(element.getMiriamData()); - break; - case "synonyms": - value = element.getSynonyms(); - break; - case "formula": - value = element.getFormula(); - break; - case "notes": - value = element.getNotes(); - break; - case "other": - value = getOthersForElement(element); - break; - case "formersymbols": - value = element.getFormerSymbols(); - break; - case "hierarchyvisibilitylevel": - value = element.getVisibilityLevel(); - break; - case "transparencylevel": - value = element.getTransparencyLevel(); - break; - case "linkedsubmodel": - if (element.getSubmodel() != null) { - value = element.getSubmodel().getSubmodel().getId(); + case "id": + case "idobject": + value = element.getId(); + break; + case "modelid": + value = element.getModelData().getId(); + break; + case "elementid": + value = element.getElementId(); + break; + case "name": + value = element.getName(); + break; + case "type": + value = element.getStringType(); + break; + case "symbol": + value = element.getSymbol(); + break; + case "fullname": + value = element.getFullName(); + break; + case "abbreviation": + value = element.getAbbreviation(); + break; + case "compartmentid": + if (element.getCompartment() != null) { + value = element.getCompartment().getId(); + } + break; + case "complexid": + if (element instanceof Species) { + if (((Species) element).getComplex() != null) { + value = ((Species) element).getComplex().getId(); } - break; - case "bounds": - value = createBounds(element.getX(), element.getY(), element.getWidth(), element.getHeight()); - break; - default: - value = "Unknown column"; - break; + } + break; + case "initialconcentration": + if (element instanceof Species) { + value = ((Species) element).getInitialConcentration(); + } + break; + case "initialamount": + if (element instanceof Species) { + value = ((Species) element).getInitialAmount(); + } + break; + case "boundarycondition": + if (element instanceof Species) { + value = ((Species) element).isBoundaryCondition(); + } + break; + case "constant": + if (element instanceof Species) { + value = ((Species) element).isConstant(); + } + break; + case "references": + value = createAnnotations(element.getMiriamData()); + break; + case "synonyms": + value = element.getSynonyms(); + break; + case "formula": + value = element.getFormula(); + break; + case "notes": + value = element.getNotes(); + break; + case "other": + value = getOthersForElement(element); + break; + case "formersymbols": + value = element.getFormerSymbols(); + break; + case "hierarchyvisibilitylevel": + value = element.getVisibilityLevel(); + break; + case "transparencylevel": + value = element.getTransparencyLevel(); + break; + case "linkedsubmodel": + if (element.getSubmodel() != null) { + value = element.getSubmodel().getSubmodel().getId(); + } + break; + case "bounds": + value = createBounds(element.getX(), element.getY(), element.getWidth(), element.getHeight()); + break; + default: + value = "Unknown column"; + break; } result.put(string, value); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsController.java index 38ff797d2b..630088f526 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsController.java @@ -5,11 +5,7 @@ import java.util.Map; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.QueryException; @@ -18,23 +14,22 @@ import lcsb.mapviewer.api.QueryException; @RequestMapping("/projects/{projectId}/models/{modelId}/bioEntities/reactions") public class ReactionsController extends BaseController { - private ReactionsRestImpl reactionController; - - public ReactionsController(ReactionsRestImpl reactionController) { - this.reactionController = reactionController; - } - - @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") - @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }, - produces = { MediaType.APPLICATION_JSON_VALUE }) - public List<Map<String, Object>> getReactions( - @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "modelId") String modelId, - @RequestParam(value = "id", defaultValue = "") String id, - @RequestParam(value = "columns", defaultValue = "") String columns, - @RequestParam(value = "participantId", defaultValue = "") String participantId - ) throws QueryException { - return reactionController.getReactions(projectId, id, columns, modelId, participantId); - } + private ReactionsRestImpl reactionController; + + public ReactionsController(ReactionsRestImpl reactionController) { + this.reactionController = reactionController; + } + + @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") + @RequestMapping(value = "/", method = { RequestMethod.GET, RequestMethod.POST }, produces = { + MediaType.APPLICATION_JSON_VALUE }) + public List<Map<String, Object>> getReactions( + @PathVariable(value = "projectId") String projectId, + @PathVariable(value = "modelId") String modelId, + @RequestParam(value = "id", defaultValue = "") String id, + @RequestParam(value = "columns", defaultValue = "") String columns, + @RequestParam(value = "participantId", defaultValue = "") String participantId) throws QueryException { + return reactionController.getReactions(projectId, id, columns, modelId, participantId); + } } \ No newline at end of file diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImpl.java index d677547b21..19aaf9f02c 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImpl.java @@ -6,7 +6,8 @@ import java.util.*; import javax.xml.transform.TransformerException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -15,17 +16,9 @@ import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; import lcsb.mapviewer.common.geometry.PointTransformation; import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; -import lcsb.mapviewer.model.map.kinetics.SbmlKinetics; -import lcsb.mapviewer.model.map.kinetics.SbmlParameter; +import lcsb.mapviewer.model.map.kinetics.*; 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.reaction.*; import lcsb.mapviewer.model.map.species.Element; @Transactional @@ -43,7 +36,7 @@ public class ReactionsRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getReactions(String projectId, String id, String columns, String modelId, - String participantElementId) throws QueryException { + String participantElementId) throws QueryException { Set<Integer> ids = new LinkedHashSet<>(); if (!id.equals("")) { for (String str : id.split(",")) { @@ -97,68 +90,68 @@ public class ReactionsRestImpl extends BaseRestImpl { String column = string.toLowerCase(); Object value; switch (column) { - case "id": - case "idobject": - value = reaction.getId(); - break; - case "modelid": - value = reaction.getModelData().getId(); - break; - case "reactionid": - value = reaction.getIdReaction(); - break; - case "name": - value = reaction.getName(); - break; - case "centerpoint": - Line2D centerLine = reaction.getLine().getLines().get(reaction.getLine().getLines().size() / 2); - value = pt.getPointOnLine(centerLine.getP1(), centerLine.getP2(), 0.5); - break; - case "products": { - List<Map<String, Object>> ids = new ArrayList<>(); - for (Product product : reaction.getProducts()) { - ids.add(createReactionNode(product)); - } - value = ids; - break; + case "id": + case "idobject": + value = reaction.getId(); + break; + case "modelid": + value = reaction.getModelData().getId(); + break; + case "reactionid": + value = reaction.getIdReaction(); + break; + case "name": + value = reaction.getName(); + break; + case "centerpoint": + Line2D centerLine = reaction.getLine().getLines().get(reaction.getLine().getLines().size() / 2); + value = pt.getPointOnLine(centerLine.getP1(), centerLine.getP2(), 0.5); + break; + case "products": { + List<Map<String, Object>> ids = new ArrayList<>(); + for (Product product : reaction.getProducts()) { + ids.add(createReactionNode(product)); } - case "reactants": { - List<Map<String, Object>> ids = new ArrayList<>(); - for (Reactant reactant : reaction.getReactants()) { - ids.add(createReactionNode(reactant)); - } - value = ids; - break; + value = ids; + break; + } + case "reactants": { + List<Map<String, Object>> ids = new ArrayList<>(); + for (Reactant reactant : reaction.getReactants()) { + ids.add(createReactionNode(reactant)); } - case "modifiers": { - List<Map<String, Object>> ids = new ArrayList<>(); - for (Modifier modifier : reaction.getModifiers()) { - ids.add(createReactionNode(modifier)); - } - value = ids; - break; + value = ids; + break; + } + case "modifiers": { + List<Map<String, Object>> ids = new ArrayList<>(); + for (Modifier modifier : reaction.getModifiers()) { + ids.add(createReactionNode(modifier)); } - case "type": - value = reaction.getStringType(); - break; - case "hierarchyvisibilitylevel": - value = reaction.getVisibilityLevel(); - break; - case "lines": - value = getLines(reaction); - break; - case "notes": - value = reaction.getNotes(); - break; - case "kineticlaw": - value = kineticsToMap(reaction.getKinetics()); - break; - case "references": - value = createAnnotations(reaction.getMiriamData()); - break; - default: - value = "Unknown column"; - break; + value = ids; + break; + } + case "type": + value = reaction.getStringType(); + break; + case "hierarchyvisibilitylevel": + value = reaction.getVisibilityLevel(); + break; + case "lines": + value = getLines(reaction); + break; + case "notes": + value = reaction.getNotes(); + break; + case "kineticlaw": + value = kineticsToMap(reaction.getKinetics()); + break; + case "references": + value = createAnnotations(reaction.getMiriamData()); + break; + default: + value = "Unknown column"; + break; } result.put(string, value); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsController.java index 8237c947b8..28fe17044f 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsController.java @@ -27,8 +27,7 @@ public class FunctionsController extends BaseController { public Map<String, Object> getFunction( @PathVariable(value = "projectId") String projectId, @PathVariable(value = "modelId") String modelId, - @PathVariable(value = "functionId") String functionId - ) throws QueryException { + @PathVariable(value = "functionId") String functionId) throws QueryException { return functionController.getFunction(projectId, modelId, functionId); } @@ -36,8 +35,7 @@ public class FunctionsController extends BaseController { @GetMapping(value = "/") public List<Map<String, Object>> getFunctions( @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "modelId") String modelId - ) throws QueryException { + @PathVariable(value = "modelId") String modelId) throws QueryException { return functionController.getFunctions(projectId, modelId); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImpl.java index e2dc966ac3..af01f2ecf9 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImpl.java @@ -1,18 +1,11 @@ package lcsb.mapviewer.api.projects.models.functions; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +import java.io.*; +import java.util.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; +import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; @@ -20,15 +13,11 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.map.kinetics.SbmlFunction; import lcsb.mapviewer.model.map.model.Model; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersController.java index 6c45b34dcf..e9d2aebe0b 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersController.java @@ -12,8 +12,7 @@ import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.QueryException; @RestController -@RequestMapping(value = "/projects/{projectId}/models/{modelId}/parameters", - produces = MediaType.APPLICATION_JSON_VALUE) +@RequestMapping(value = "/projects/{projectId}/models/{modelId}/parameters", produces = MediaType.APPLICATION_JSON_VALUE) public class ParametersController extends BaseController { private ParametersRestImpl parameterController; @@ -28,8 +27,7 @@ public class ParametersController extends BaseController { public Map<String, Object> getParameter( @PathVariable(value = "projectId") String projectId, @PathVariable(value = "modelId") String modelId, - @PathVariable(value = "parameterId") String parameterId - ) throws QueryException { + @PathVariable(value = "parameterId") String parameterId) throws QueryException { return parameterController.getParameter(projectId, modelId, parameterId); } @@ -37,8 +35,7 @@ public class ParametersController extends BaseController { @GetMapping(value = "/") public List<Map<String, Object>> getParameters( @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "modelId") String modelId - ) throws QueryException { + @PathVariable(value = "modelId") String modelId) throws QueryException { return parameterController.getParameters(projectId, modelId); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImpl.java index 337029b853..62ef329cc8 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/parameters/ParametersRestImpl.java @@ -1,19 +1,13 @@ package lcsb.mapviewer.api.projects.models.parameters; -import java.util.ArrayList; -import java.util.TreeMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.map.kinetics.SbmlParameter; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsController.java index 2bfe2e6093..cbf66d0a60 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsController.java @@ -11,29 +11,27 @@ import lcsb.mapviewer.api.BaseController; import lcsb.mapviewer.api.QueryException; @RestController -@RequestMapping(value = "/projects/{projectId}/models/{modelId}/publications", - produces = MediaType.APPLICATION_JSON_VALUE) +@RequestMapping(value = "/projects/{projectId}/models/{modelId}/publications", produces = MediaType.APPLICATION_JSON_VALUE) public class PublicationsController extends BaseController { - private PublicationsRestImpl projectController; - - @Autowired - public PublicationsController(PublicationsRestImpl projectController) { - this.projectController = projectController; - } - - @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") - @GetMapping(value = "/") - public Map<String, Object> getPublications( - @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "modelId") String modelId, - @RequestParam(value = "start", defaultValue = "0") String start, - @RequestParam(value = "length", defaultValue = "10") Integer length, - @RequestParam(value = "sortColumn", defaultValue = "pubmedId") String sortColumn, - @RequestParam(value = "sortOrder", defaultValue = "asc") String sortOrder, - @RequestParam(value = "search", defaultValue = "") String search - ) throws QueryException { - return projectController.getPublications(projectId, modelId, start, length, sortColumn, sortOrder, search); - } + private PublicationsRestImpl projectController; + + @Autowired + public PublicationsController(PublicationsRestImpl projectController) { + this.projectController = projectController; + } + + @PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)") + @GetMapping(value = "/") + public Map<String, Object> getPublications( + @PathVariable(value = "projectId") String projectId, + @PathVariable(value = "modelId") String modelId, + @RequestParam(value = "start", defaultValue = "0") String start, + @RequestParam(value = "length", defaultValue = "10") Integer length, + @RequestParam(value = "sortColumn", defaultValue = "pubmedId") String sortColumn, + @RequestParam(value = "sortOrder", defaultValue = "asc") String sortOrder, + @RequestParam(value = "search", defaultValue = "") String search) throws QueryException { + return projectController.getPublications(projectId, modelId, start, length, sortColumn, sortOrder, search); + } } \ No newline at end of file diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImpl.java index 0cec45bf48..8ba10793a1 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImpl.java @@ -1,18 +1,11 @@ package lcsb.mapviewer.api.projects.models.publications; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; import org.apache.commons.lang3.math.NumberUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,9 +17,7 @@ import lcsb.mapviewer.api.BaseRestImpl; import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.common.comparator.IntegerComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; @Transactional @@ -65,20 +56,6 @@ public class PublicationsRestImpl extends BaseRestImpl { return publications; } - enum SortColumn { - PUBMED_ID("pubmedId"), - YEAR("year"), - JOURNAL("journal"), - TITLE("title"), - AUTHORS("authors"); - - private String commonName; - - SortColumn(String commonName) { - this.commonName = commonName; - } - } - public Map<String, Object> getPublications( String projectId, String modelId, String startString, Integer length, String sortColumn, String sortOrder, String search) throws QueryException { @@ -94,8 +71,8 @@ public class PublicationsRestImpl extends BaseRestImpl { List<Map.Entry<MiriamData, List<BioEntity>>> filteredList = new ArrayList<>(); for (Map.Entry<MiriamData, List<BioEntity>> entry : publications.entrySet()) { - Set<Model> publicationModels= new LinkedHashSet<>(); - for (BioEntity bioEntity: entry.getValue()) { + Set<Model> publicationModels = new LinkedHashSet<>(); + for (BioEntity bioEntity : entry.getValue()) { publicationModels.add(bioEntity.getModel()); } if (isSearchResult(entry.getKey(), search, publicationModels)) { @@ -282,4 +259,18 @@ public class PublicationsRestImpl extends BaseRestImpl { } + enum SortColumn { + PUBMED_ID("pubmedId"), + YEAR("year"), + JOURNAL("journal"), + TITLE("title"), + AUTHORS("authors"); + + private String commonName; + + SortColumn(String commonName) { + this.commonName = commonName; + } + } + } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsController.java index 64643ca83c..9b815e03ae 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsController.java @@ -27,8 +27,7 @@ public class UnitsController extends BaseController { public Map<String, Object> getUnit( @PathVariable(value = "projectId") String projectId, @PathVariable(value = "modelId") String modelId, - @PathVariable(value = "unitId") String unitId - ) throws QueryException { + @PathVariable(value = "unitId") String unitId) throws QueryException { return unitController.getUnit(projectId, modelId, unitId); } @@ -36,8 +35,7 @@ public class UnitsController extends BaseController { @GetMapping(value = "/") public List<Map<String, Object>> getUnits( @PathVariable(value = "projectId") String projectId, - @PathVariable(value = "modelId") String modelId - ) throws QueryException { + @PathVariable(value = "modelId") String modelId) throws QueryException { return unitController.getUnits(projectId, modelId); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsRestImpl.java index 5ae03239d7..b276f87957 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/units/UnitsRestImpl.java @@ -1,17 +1,13 @@ package lcsb.mapviewer.api.projects.models.units; -import java.util.ArrayList; -import java.util.TreeMap; -import java.util.List; -import java.util.Map; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.model.map.kinetics.SbmlUnit; import lcsb.mapviewer.model.map.kinetics.SbmlUnitTypeFactor; import lcsb.mapviewer.model.map.model.Model; @@ -54,7 +50,7 @@ public class UnitsRestImpl extends BaseRestImpl { } private Map<String, Object> factorToMap(SbmlUnitTypeFactor factor) { - Map<String, Object> result = new TreeMap<>(); + Map<String, Object> result = new TreeMap<>(); result.put("id", factor.getId()); result.put("exponent", factor.getExponent()); result.put("multiplier", factor.getMultiplier()); diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayController.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayController.java index ea8ab18960..fd8a5c6044 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayController.java @@ -42,7 +42,8 @@ public class OverlayController extends BaseController { @RequestParam(value = "publicOverlay", defaultValue = "false") boolean publicOverlay) { return overlayRestImp.getOverlayList(projectId).stream() .filter(overlay -> !publicOverlay || (Boolean) overlay.get("publicOverlay")) - .filter(overlay -> creator.isEmpty() || (overlay.get("creator") != null && overlay.get("creator").equals(creator))) + .filter( + overlay -> creator.isEmpty() || (overlay.get("creator") != null && overlay.get("creator").equals(creator))) .collect(Collectors.toList()); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyController.java b/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyController.java index eb5e97fce8..ea6dbf812f 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyController.java @@ -2,14 +2,15 @@ package lcsb.mapviewer.api.taxonomy; import java.util.Map; -import lcsb.mapviewer.annotation.services.TaxonomySearchException; -import lcsb.mapviewer.api.ObjectNotFoundException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; +import lcsb.mapviewer.annotation.services.TaxonomySearchException; import lcsb.mapviewer.api.BaseController; +import lcsb.mapviewer.api.ObjectNotFoundException; @RestController @RequestMapping(value = "/taxonomy", produces = MediaType.APPLICATION_JSON_VALUE) diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyRestImpl.java index 9285e330a5..d2290bcfa1 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/taxonomy/TaxonomyRestImpl.java @@ -3,7 +3,8 @@ package lcsb.mapviewer.api.taxonomy; import java.util.Map; import java.util.TreeMap; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java index 69d1187ba0..4ff58ffd83 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.util.*; import java.util.stream.Collectors; -import lcsb.mapviewer.common.Configuration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -15,7 +14,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.*; import lcsb.mapviewer.api.*; -import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.services.interfaces.IUserService; @RestController @@ -23,7 +22,7 @@ import lcsb.mapviewer.services.interfaces.IUserService; public class UserController extends BaseController { Logger logger = LogManager.getLogger(); - + private IUserService userService; private UserRestImpl userRest; @@ -41,7 +40,7 @@ public class UserController extends BaseController { @GetMapping(value = "/isSessionValid") @PreAuthorize("isAuthenticated() and authentication.name != '" + Configuration.ANONYMOUS_LOGIN + "'") public Object isSessionValid(Authentication authentication) { - Map<String,Object> result = new TreeMap<>(); + Map<String, Object> result = new TreeMap<>(); result.put("login", authentication.getName()); return result; } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java index 6ad901b578..64a2d48d50 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java @@ -2,36 +2,22 @@ package lcsb.mapviewer.api.users; import java.util.*; -import lcsb.mapviewer.model.security.PrivilegeType; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.MultiValueMap; -import lcsb.mapviewer.api.BaseRestImpl; -import lcsb.mapviewer.api.ObjectExistsException; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.OperationNotAllowedException; -import lcsb.mapviewer.api.QueryException; +import lcsb.mapviewer.api.*; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.user.AnnotatorParamDefinition; import lcsb.mapviewer.model.security.Privilege; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.model.user.UserAnnotationSchema; -import lcsb.mapviewer.model.user.UserClassAnnotators; -import lcsb.mapviewer.model.user.UserClassRequiredAnnotations; -import lcsb.mapviewer.model.user.UserClassValidAnnotations; -import lcsb.mapviewer.model.user.UserGuiPreference; -import lcsb.mapviewer.model.user.annotator.AnnotatorConfigParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorData; -import lcsb.mapviewer.model.user.annotator.AnnotatorInputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorOutputParameter; -import lcsb.mapviewer.model.user.annotator.AnnotatorParameter; -import lcsb.mapviewer.model.user.annotator.BioEntityField; +import lcsb.mapviewer.model.security.PrivilegeType; +import lcsb.mapviewer.model.user.*; +import lcsb.mapviewer.model.user.annotator.*; @Transactional @Service diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/BaseControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/BaseControllerTest.java index 91a4f789eb..25d4046b49 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/BaseControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/BaseControllerTest.java @@ -6,10 +6,7 @@ import static org.mockito.Mockito.CALLS_REAL_METHODS; import java.util.Map; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; import org.mockito.Mockito; public class BaseControllerTest { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java index b8956aa191..77e415ea34 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/BaseRestImplTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.api; import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.CALLS_REAL_METHODS; import java.util.List; import java.util.Map; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java b/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java index 819a8d1da9..52c60423bf 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.api; -import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.anyString; import java.io.*; import java.net.URL; @@ -47,11 +47,9 @@ import lcsb.mapviewer.services.interfaces.*; @RunWith(SpringJUnit4ClassRunner.class) public abstract class RestTestFunctions { + private static Map<String, Model> models = new HashMap<>(); @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - - private Logger logger = LogManager.getLogger(RestTestFunctions.class); - public double EPSILON = 1e-6; @Autowired @@ -66,6 +64,7 @@ public abstract class RestTestFunctions { protected String username; protected String adminToken; + private Logger logger = LogManager.getLogger(RestTestFunctions.class); @Before public void generalSetUp() { @@ -142,8 +141,6 @@ public abstract class RestTestFunctions { return doc; } - private static Map<String, Model> models = new HashMap<>(); - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { Model result = null; if (!fromCache) { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/SpringRestApiTestConfig.java b/rest-api/src/test/java/lcsb/mapviewer/api/SpringRestApiTestConfig.java index ac7262267a..697a1f1860 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/SpringRestApiTestConfig.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/SpringRestApiTestConfig.java @@ -1,12 +1,11 @@ package lcsb.mapviewer.api; +import org.springframework.context.annotation.*; +import org.springframework.security.core.session.SessionRegistryImpl; + import lcsb.mapviewer.annotation.SpringAnnotationConfig; import lcsb.mapviewer.persist.SpringPersistConfig; import lcsb.mapviewer.services.SpringServiceConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.core.session.SessionRegistryImpl; @Configuration @Import({ diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java index 5fb67137f0..84615b6126 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java @@ -19,11 +19,10 @@ import lcsb.mapviewer.model.user.annotator.BioEntityField; public class ConfigurationRestImplTest extends RestTestFunctions { - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(ConfigurationRestImplTest.class); - @Autowired public ConfigurationRestImpl configurationRestImpl; + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(ConfigurationRestImplTest.class); @AfterClass public static void tearDownAfterClass() throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java index b94871d6fb..0c69b7ff2f 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/convert/ConvertRestImplTest.java @@ -24,11 +24,10 @@ import lcsb.mapviewer.model.map.InconsistentModelException; public class ConvertRestImplTest extends RestTestFunctions { - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(ConvertRestImplTest.class); - @Autowired public ConvertRestImpl convertRestImpl; + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(ConvertRestImplTest.class); @AfterClass public static void tearDownAfterClass() throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java index c282688096..413ae7eadb 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java @@ -1,20 +1,18 @@ package lcsb.mapviewer.api.files; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.*; import java.util.Map; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IUserService; import org.apache.commons.lang3.ArrayUtils; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.RestTestFunctions; import lcsb.mapviewer.model.cache.UploadedFileEntry; +import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.cache.UploadedFileEntryDao; +import lcsb.mapviewer.services.interfaces.IUserService; public class FileRestImplTest extends RestTestFunctions { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java index 3caee1b2fe..feb41d73e4 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.api.genomics; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Map; @@ -14,10 +15,9 @@ import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.api.RestTestFunctions; public class ReferenceGenomeControllerTest extends RestTestFunctions { - Logger logger = LogManager.getLogger(ReferenceGenomeControllerTest.class); - @Autowired public ReferenceGenomeRestImpl referenceGenomeRestImpl; + Logger logger = LogManager.getLogger(ReferenceGenomeControllerTest.class); @AfterClass public static void tearDownAfterClass() throws Exception { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java index 3faec73672..5cf68a4d88 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java @@ -5,7 +5,8 @@ import static org.junit.Assert.assertTrue; import java.util.Map; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java index 1e03f78932..d97c2772b4 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.api.projects; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; import java.util.*; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java index a89809ec7d..476579347e 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImplTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.api.projects.chemicals; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.anyString; import java.util.ArrayList; import java.util.Map; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java index 56729f273b..a41ef74ff9 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java @@ -1,7 +1,8 @@ package lcsb.mapviewer.api.projects.comments; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.times; import java.util.ArrayList; import java.util.List; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java index 94c82b5e78..b1ee837dba 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.api.projects.drugs; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.util.List; import java.util.Map; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java index 0cc98a4983..8a1d5e8c6b 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.api.projects.mirnas; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; import java.util.*; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java index e61b549aa1..0c494545f7 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java @@ -1,7 +1,9 @@ package lcsb.mapviewer.api.projects.models; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.ArgumentMatchers.refEq; import java.util.*; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java index 9483cb1af5..26935e8e93 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java @@ -1,7 +1,8 @@ package lcsb.mapviewer.api.projects.models.bioEntities; -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.anyString; import java.awt.geom.Point2D; import java.util.List; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java index bf4ffea57d..13e2a706c1 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.api.projects.models.bioEntities.elements; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.anyString; import java.util.List; import java.util.Map; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImplTest.java index e5ca846db1..39825c8d23 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/reactions/ReactionsRestImplTest.java @@ -10,9 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.RestTestFunctions; import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; +import lcsb.mapviewer.model.map.reaction.*; import lcsb.mapviewer.model.map.species.GenericProtein; public class ReactionsRestImplTest extends RestTestFunctions { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImplTest.java index 2d5b428fc7..2b2ca8b6ec 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/functions/FunctionsRestImplTest.java @@ -1,10 +1,9 @@ package lcsb.mapviewer.api.projects.models.functions; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -17,7 +16,7 @@ public class FunctionsRestImplTest extends RestTestFunctions { FunctionsRestImpl functionRestImpl; @Test - public void testExtractLambda() throws Exception{ + public void testExtractLambda() throws Exception { String lambda = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n<lambda>\n<bvar>\n<ci> x </ci>\n</bvar>\n<bvar>\n<ci> y </ci>\n</bvar>\n<apply>\n<plus/>\n<ci> x </ci>\n<ci> y </ci>\n<cn type=\"integer\"> 2 </cn>\n</apply>\n</lambda>\n\n</math>"; String definition = functionRestImpl.extractLambda(lambda); assertNotNull(definition); diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java index 738a8cbabc..778f7bebe4 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.api.projects.models.publications; import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.*; +import static org.mockito.ArgumentMatchers.anyString; import java.util.*; import java.util.Map.Entry; @@ -104,8 +104,8 @@ public class PublicationsRestImplTest extends RestTestFunctions { Entry<MiriamData, List<BioEntity>> valid = new Entry<MiriamData, List<BioEntity>>() { @Override - public List<BioEntity> setValue(List<BioEntity> value) { - return null; + public MiriamData getKey() { + return new MiriamData(MiriamType.PUBMED, "12345"); } @Override @@ -114,15 +114,15 @@ public class PublicationsRestImplTest extends RestTestFunctions { } @Override - public MiriamData getKey() { - return new MiriamData(MiriamType.PUBMED, "12345"); + public List<BioEntity> setValue(List<BioEntity> value) { + return null; } }; Entry<MiriamData, List<BioEntity>> invalid = new Entry<MiriamData, List<BioEntity>>() { @Override - public List<BioEntity> setValue(List<BioEntity> value) { - return null; + public MiriamData getKey() { + return new MiriamData(MiriamType.PUBMED, ""); } @Override @@ -131,8 +131,8 @@ public class PublicationsRestImplTest extends RestTestFunctions { } @Override - public MiriamData getKey() { - return new MiriamData(MiriamType.PUBMED, ""); + public List<BioEntity> setValue(List<BioEntity> value) { + return null; } }; for (SortColumn sortColumn : SortColumn.values()) { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java index 219f1f7fc1..40702e8a56 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImplTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.api.projects.overlays; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java index 6a6d678f9d..45db6982c7 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.api.users; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.util.*; diff --git a/service/src/main/java/lcsb/mapviewer/services/AuthenticationTokenExpireException.java b/service/src/main/java/lcsb/mapviewer/services/AuthenticationTokenExpireException.java index 4a184fd3e2..e52ae97df7 100644 --- a/service/src/main/java/lcsb/mapviewer/services/AuthenticationTokenExpireException.java +++ b/service/src/main/java/lcsb/mapviewer/services/AuthenticationTokenExpireException.java @@ -2,13 +2,13 @@ package lcsb.mapviewer.services; public class AuthenticationTokenExpireException extends SecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - public AuthenticationTokenExpireException(String message) { - super(message); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + public AuthenticationTokenExpireException(String message) { + super(message); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/InvalidTokenException.java b/service/src/main/java/lcsb/mapviewer/services/InvalidTokenException.java index a82e8327f9..99d9bd620a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/InvalidTokenException.java +++ b/service/src/main/java/lcsb/mapviewer/services/InvalidTokenException.java @@ -2,13 +2,13 @@ package lcsb.mapviewer.services; public class InvalidTokenException extends SecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - public InvalidTokenException(String message) { - super(message); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + public InvalidTokenException(String message) { + super(message); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/SpringServiceConfig.java b/service/src/main/java/lcsb/mapviewer/services/SpringServiceConfig.java index a096e18f1a..c6adf62708 100644 --- a/service/src/main/java/lcsb/mapviewer/services/SpringServiceConfig.java +++ b/service/src/main/java/lcsb/mapviewer/services/SpringServiceConfig.java @@ -1,17 +1,15 @@ package lcsb.mapviewer.services; -import lcsb.mapviewer.annotation.SpringAnnotationConfig; -import lcsb.mapviewer.persist.SpringPersistConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.*; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.core.session.SessionRegistryImpl; +import lcsb.mapviewer.annotation.SpringAnnotationConfig; +import lcsb.mapviewer.persist.SpringPersistConfig; + @Configuration -@Import({SpringPersistConfig.class, SpringAnnotationConfig.class}) -@ComponentScan(basePackages = {"lcsb.mapviewer.services"}) +@Import({ SpringPersistConfig.class, SpringAnnotationConfig.class }) +@ComponentScan(basePackages = { "lcsb.mapviewer.services" }) public class SpringServiceConfig { @Bean diff --git a/service/src/main/java/lcsb/mapviewer/services/UserAccessException.java b/service/src/main/java/lcsb/mapviewer/services/UserAccessException.java index 53c705b7ba..6db890b9f7 100644 --- a/service/src/main/java/lcsb/mapviewer/services/UserAccessException.java +++ b/service/src/main/java/lcsb/mapviewer/services/UserAccessException.java @@ -2,13 +2,13 @@ package lcsb.mapviewer.services; public class UserAccessException extends SecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - - public UserAccessException(String message) { - super(message); - } + /** + * + */ + private static final long serialVersionUID = 1L; + + public UserAccessException(String message) { + super(message); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java b/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java index 71dc451801..3e4268803e 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java @@ -1,14 +1,12 @@ package lcsb.mapviewer.services.impl; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import javax.mail.MessagingException; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -23,10 +21,7 @@ import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.map.CommentDao; -import lcsb.mapviewer.services.interfaces.ICommentService; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IUserService; +import lcsb.mapviewer.services.interfaces.*; import lcsb.mapviewer.services.utils.EmailSender; /** @@ -74,9 +69,9 @@ public class CommentService implements ICommentService { @Autowired public CommentService(CommentDao commentDao, - IModelService modelService, - IUserService userService, - IConfigurationService configurationService) { + IModelService modelService, + IUserService userService, + IConfigurationService configurationService) { this.commentDao = commentDao; this.modelService = modelService; this.userService = userService; @@ -85,7 +80,7 @@ public class CommentService implements ICommentService { @Override public Comment addComment(String name, String email, String content, Model model, Point2D coordinates, Object object, - boolean pinned, Model submodel) { + boolean pinned, Model submodel) { Comment comment = new Comment(); comment.setName(name); comment.setEmail(email); @@ -120,6 +115,74 @@ public class CommentService implements ICommentService { return comment; } + @Override + public void deleteComment(User loggedUser, String commentId, String reason) { + int id = -1; + try { + id = Integer.parseInt(commentId); + + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + Comment comment = commentDao.getById(id); + if (comment == null) { + logger.error("Invalid comment id: " + commentId); + } else { + comment.setDeleted(true); + comment.setRemoveReason(reason); + commentDao.update(comment); + } + } + + @Override + public void deleteComment(Comment comment, String reason) { + comment.setDeleted(true); + comment.setRemoveReason(reason); + commentDao.update(comment); + } + + @Override + public List<Comment> getCommentsByProject(Project project) { + List<Comment> comments = new ArrayList<>(); + for (ModelData model : project.getModels()) { + List<Comment> modelComments = commentDao.getCommentByModel(model, null, null); + comments.addAll(modelComments); + } + + return comments; + } + + @Override + public long getCommentCount() { + return commentDao.getCount(); + } + + @Override + public void removeCommentsForModel(Model model) { + List<Comment> comments = commentDao.getCommentByModel(model, null, null); + for (Comment comment : comments) { + commentDao.delete(comment); + } + } + + @Override + public void removeCommentsForModel(ModelData model) { + List<Comment> comments = commentDao.getCommentByModel(model, null, null); + for (Comment comment : comments) { + commentDao.delete(comment); + } + } + + @Override + public Comment getCommentById(String commentId) { + int id = -1; + try { + id = Integer.parseInt(commentId); + } catch (NumberFormatException e) { + } + return commentDao.getById(id); + } + /** * This method returns all comments for model agregated by commented elements. * @@ -159,38 +222,6 @@ public class CommentService implements ICommentService { return result; } - @Override - public void deleteComment(User loggedUser, String commentId, String reason) { - int id = -1; - try { - id = Integer.parseInt(commentId); - - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - Comment comment = commentDao.getById(id); - if (comment == null) { - logger.error("Invalid comment id: " + commentId); - } else { - comment.setDeleted(true); - comment.setRemoveReason(reason); - commentDao.update(comment); - } - } - - @Override - public long getCommentCount() { - return commentDao.getCount(); - } - - @Override - public void removeCommentsForModel(Model model) { - List<Comment> comments = commentDao.getCommentByModel(model, null, null); - for (Comment comment : comments) { - commentDao.delete(comment); - } - } - /** * @return the commentDao * @see #commentDao @@ -259,14 +290,6 @@ public class CommentService implements ICommentService { this.configurationService = configurationService; } - @Override - public void removeCommentsForModel(ModelData model) { - List<Comment> comments = commentDao.getCommentByModel(model, null, null); - for (Comment comment : comments) { - commentDao.delete(comment); - } - } - /** * Checks if identifier of the points refer to the same point. * @@ -292,32 +315,4 @@ public class CommentService implements ICommentService { && !(Math.abs(y1 - y2) > COMMENT_POINT_DISTANCE_EPSILON); } - @Override - public List<Comment> getCommentsByProject(Project project) { - List<Comment> comments = new ArrayList<>(); - for (ModelData model : project.getModels()) { - List<Comment> modelComments = commentDao.getCommentByModel(model, null, null); - comments.addAll(modelComments); - } - - return comments; - } - - @Override - public void deleteComment(Comment comment, String reason) { - comment.setDeleted(true); - comment.setRemoveReason(reason); - commentDao.update(comment); - } - - @Override - public Comment getCommentById(String commentId) { - int id = -1; - try { - id = Integer.parseInt(commentId); - } catch (NumberFormatException e) { - } - return commentDao.getById(id); - } - } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ConfigurationService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ConfigurationService.java index 768f520835..abce6cca70 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ConfigurationService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ConfigurationService.java @@ -3,10 +3,10 @@ package lcsb.mapviewer.services.impl; import java.util.ArrayList; import java.util.List; -import lcsb.mapviewer.model.security.PrivilegeType; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -14,9 +14,8 @@ import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.FrameworkVersion; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.user.ConfigurationElementEditType; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.ConfigurationOption; +import lcsb.mapviewer.model.security.PrivilegeType; +import lcsb.mapviewer.model.user.*; import lcsb.mapviewer.persist.dao.ConfigurationDao; import lcsb.mapviewer.services.interfaces.IConfigurationService; @@ -119,16 +118,6 @@ public class ConfigurationService implements IConfigurationService { return result; } - @Override - public ConfigurationOption getValue(ConfigurationElementType type) { - ConfigurationOption configuration = configurationDao.getByType(type); - if (configuration == null) { - getConfigurationValue(type); - configuration = configurationDao.getByType(type); - } - return configuration; - } - @Override public void updateConfiguration(List<ConfigurationOption> values) { for (ConfigurationOption configurationElement : values) { @@ -142,13 +131,17 @@ public class ConfigurationService implements IConfigurationService { } @Override - public String getSystemGitVersion(String baseDir) { - return lcsb.mapviewer.common.Configuration.getSystemBuildVersion(baseDir); + public Long getMemoryUsage() { + Runtime runtime = Runtime.getRuntime(); + + return (runtime.totalMemory() - runtime.freeMemory()) / MEGABYTE_SIZE; } @Override - public String getSystemBuild(String baseDir) { - return lcsb.mapviewer.common.Configuration.getSystemBuild(baseDir); + public Long getMaxMemory() { + Runtime runtime = Runtime.getRuntime(); + + return runtime.maxMemory() / MEGABYTE_SIZE; } @Override @@ -157,17 +150,23 @@ public class ConfigurationService implements IConfigurationService { } @Override - public Long getMemoryUsage() { - Runtime runtime = Runtime.getRuntime(); - - return (runtime.totalMemory() - runtime.freeMemory()) / MEGABYTE_SIZE; + public String getSystemBuild(String baseDir) { + return lcsb.mapviewer.common.Configuration.getSystemBuild(baseDir); } @Override - public Long getMaxMemory() { - Runtime runtime = Runtime.getRuntime(); + public String getSystemGitVersion(String baseDir) { + return lcsb.mapviewer.common.Configuration.getSystemBuildVersion(baseDir); + } - return runtime.maxMemory() / MEGABYTE_SIZE; + @Override + public ConfigurationOption getValue(ConfigurationElementType type) { + ConfigurationOption configuration = configurationDao.getByType(type); + if (configuration == null) { + getConfigurationValue(type); + configuration = configurationDao.getByType(type); + } + return configuration; } @Override diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoder.java b/service/src/main/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoder.java index 5e170d0197..1b36d9175e 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoder.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoder.java @@ -16,42 +16,42 @@ import org.springframework.security.crypto.password.PasswordEncoder; */ public class CustomMd5PasswordEncoder implements PasswordEncoder { - @Override - public String encode(CharSequence password) { + /** + * Transforms {@link CharSequence} into byte array. + * + * @param string + * input {@link CharSequence} + * @return byte array representation of the input {@link CharSequence} + */ + private static byte[] encodeUtf8(CharSequence string) { + ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(string)); + byte[] result = new byte[bb.remaining()]; + bb.get(result); + return result; + } - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] thedigest = md.digest(encodeUtf8(password)); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < thedigest.length; ++i) { - // CHECKSTYLE:OFF - // this line transforms single byte into hex representation - sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3)); - // CHECKSTYLE:ON - } - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - e.printStackTrace(); - } - return null; - } + @Override + public String encode(CharSequence password) { - @Override - public boolean matches(CharSequence arg0, String arg1) { - return encode(arg0).equals(arg1); - } + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + byte[] thedigest = md.digest(encodeUtf8(password)); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < thedigest.length; ++i) { + // CHECKSTYLE:OFF + // this line transforms single byte into hex representation + sb.append(Integer.toHexString((thedigest[i] & 0xFF) | 0x100).substring(1, 3)); + // CHECKSTYLE:ON + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return null; + } - /** - * Transforms {@link CharSequence} into byte array. - * - * @param string - * input {@link CharSequence} - * @return byte array representation of the input {@link CharSequence} - */ - private static byte[] encodeUtf8(CharSequence string) { - ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(string)); - byte[] result = new byte[bb.remaining()]; - bb.get(result); - return result; - } + @Override + public boolean matches(CharSequence arg0, String arg1) { + return encode(arg0).equals(arg1); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/FileService.java b/service/src/main/java/lcsb/mapviewer/services/impl/FileService.java index fe9cd97e3a..8519510c35 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/FileService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/FileService.java @@ -1,12 +1,13 @@ package lcsb.mapviewer.services.impl; -import lcsb.mapviewer.model.cache.UploadedFileEntry; -import lcsb.mapviewer.persist.dao.cache.UploadedFileEntryDao; -import lcsb.mapviewer.services.interfaces.IFileService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import lcsb.mapviewer.model.cache.UploadedFileEntry; +import lcsb.mapviewer.persist.dao.cache.UploadedFileEntryDao; +import lcsb.mapviewer.services.interfaces.IFileService; + @Transactional @Service public class FileService implements IFileService { diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java b/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java index 0cf9d42a3b..83cc8fe1e6 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java @@ -1,29 +1,22 @@ package lcsb.mapviewer.services.impl; -import java.awt.Color; +import java.awt.*; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; +import java.util.*; import java.util.Comparator; import java.util.List; -import java.util.Map; import javax.mail.MessagingException; import org.apache.commons.io.IOUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.annotation.services.MiriamConnector; -import lcsb.mapviewer.commands.ColorExtractor; -import lcsb.mapviewer.commands.ColorModelCommand; -import lcsb.mapviewer.commands.CommandExecutionException; -import lcsb.mapviewer.commands.CopyCommand; -import lcsb.mapviewer.common.IProgressUpdater; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.TextFileUtils; +import lcsb.mapviewer.commands.*; +import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidStateException; import lcsb.mapviewer.converter.graphics.MapGenerator; @@ -33,14 +26,7 @@ import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.DataOverlayImageLayer; -import lcsb.mapviewer.model.map.layout.GeneVariation; -import lcsb.mapviewer.model.map.layout.GeneVariationColorSchema; -import lcsb.mapviewer.model.map.layout.GenericColorSchema; -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.layout.LayoutStatus; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; import lcsb.mapviewer.model.map.reaction.Reaction; @@ -48,9 +34,7 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.DbUtils; import lcsb.mapviewer.persist.dao.map.LayoutDao; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.interfaces.IUserService; +import lcsb.mapviewer.services.interfaces.*; import lcsb.mapviewer.services.utils.ColorSchemaReader; import lcsb.mapviewer.services.utils.EmailSender; import lcsb.mapviewer.services.utils.data.ColorSchemaColumn; @@ -65,8 +49,8 @@ import lcsb.mapviewer.services.utils.data.ColorSchemaColumn; @Service public class LayoutService implements ILayoutService { - private static final Comparator<? super Pair<? extends BioEntity, ColorSchema>> ELEMENT_PAIR_COMPARATOR = - Comparator.comparingInt(o -> o.getLeft().getId()); + private static final Comparator<? super Pair<? extends BioEntity, ColorSchema>> ELEMENT_PAIR_COMPARATOR = Comparator + .comparingInt(o -> o.getLeft().getId()); /** * Default class logger. @@ -101,9 +85,9 @@ public class LayoutService implements ILayoutService { @Autowired public LayoutService(LayoutDao layoutDao, - IUserService userService, - IConfigurationService configurationService, - DbUtils dbUtils) { + IUserService userService, + IConfigurationService configurationService, + DbUtils dbUtils) { this.layoutDao = layoutDao; this.userService = userService; this.configurationService = configurationService; @@ -164,6 +148,65 @@ public class LayoutService implements ILayoutService { layoutDao.update(layout); } + @Override + public Layout createLayout(final CreateLayoutParams params) throws IOException, InvalidColorSchemaException { + ColorSchemaReader reader = new ColorSchemaReader(); + Map<String, String> parameters = TextFileUtils.getHeaderParametersFromFile(params.getColorInputStream()); + if (parameters.get(ZipEntryFileFactory.LAYOUT_HEADER_PARAM_TYPE) == null && params.getColorSchemaType() != null) { + parameters.put(ZipEntryFileFactory.LAYOUT_HEADER_PARAM_TYPE, params.getColorSchemaType().name()); + } + final Collection<ColorSchema> schemas = reader.readColorSchema(params.getColorInputStream(), parameters); + + // check if we can color our model using this schema, + // if not then exception will be thrown and passed up + try { + Model model = params.getProject().getModels().iterator().next().getModel(); + Model copy = new CopyCommand(model).execute(); + new ColorModelCommand(copy, schemas, userService.getColorExtractorForUser(params.getUser())).execute(); + } catch (CommandExecutionException e) { + throw new InvalidColorSchemaException(e); + } + + layoutDao.flush(); + + Layout topLayout = new Layout(params.getName(), false); + topLayout.setColorSchemaType(params.getColorSchemaType()); + if (params.getUser() == null) { + topLayout.setPublicLayout(true); + } else { + topLayout.setPublicLayout(false); + } + topLayout.setGoogleLicenseConsent(params.isGoogleLicenseConsent()); + topLayout.setStatus(LayoutStatus.OK); + topLayout.setProgress(0.0); + UploadedFileEntry fileEntry = new UploadedFileEntry(); + fileEntry.setFileContent(IOUtils.toByteArray(params.getColorInputStream())); + fileEntry.setOriginalFileName(params.getLayoutFileName()); + fileEntry.setLength(fileEntry.getFileContent().length); + fileEntry.setOwner(params.getUser()); + topLayout.setInputData(fileEntry); + topLayout.setDescription(params.getDescription()); + topLayout.setProject(params.getProject()); + topLayout.setCreator(params.getUser()); + layoutDao.add(topLayout); + + Thread sendEmailThread = new Thread(() -> { + try { + // open transaction for this thread + dbUtils.createSessionForCurrentThread(); + sendSuccessfullGenerationEmail(params, schemas); + } catch (MessagingException e) { + logger.error("Problem with sending email", e); + } finally { + dbUtils.closeSessionForCurrentThread(); + } + }); + + logger.info("Data overlay " + topLayout.getId() + " created successfully"); + sendEmailThread.start(); + return topLayout; + } + @Override public Layout createLayoutWithImages(final CreateLayoutParams params) throws IOException, InvalidColorSchemaException, CommandExecutionException { @@ -304,62 +347,134 @@ public class LayoutService implements ILayoutService { } @Override - public Layout createLayout(final CreateLayoutParams params) throws IOException, InvalidColorSchemaException { - ColorSchemaReader reader = new ColorSchemaReader(); - Map<String, String> parameters = TextFileUtils.getHeaderParametersFromFile(params.getColorInputStream()); - if (parameters.get(ZipEntryFileFactory.LAYOUT_HEADER_PARAM_TYPE) == null && params.getColorSchemaType() != null) { - parameters.put(ZipEntryFileFactory.LAYOUT_HEADER_PARAM_TYPE, params.getColorSchemaType().name()); + public List<Pair<Element, ColorSchema>> getAliasesForLayout(Model model, int layoutId) { + try { + Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); + // colors here are not important + ColorModelCommand command = new ColorModelCommand(model, schemas, + new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); + List<Pair<Element, ColorSchema>> result = new ArrayList<>(); + for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { + if (entry.getKey() instanceof Element) { + result.add(new Pair<>((Element) entry.getKey(), entry.getValue())); + } + } + result.sort(LayoutService.ELEMENT_PAIR_COMPARATOR); + return result; + } catch (InvalidColorSchemaException | IOException e) { + throw new InvalidStateException(e); } - final Collection<ColorSchema> schemas = reader.readColorSchema(params.getColorInputStream(), parameters); + } - // check if we can color our model using this schema, - // if not then exception will be thrown and passed up + @Override + public List<Pair<Reaction, ColorSchema>> getReactionsForLayout(Model model, int layoutId) { try { - Model model = params.getProject().getModels().iterator().next().getModel(); - Model copy = new CopyCommand(model).execute(); - new ColorModelCommand(copy, schemas, userService.getColorExtractorForUser(params.getUser())).execute(); - } catch (CommandExecutionException e) { - throw new InvalidColorSchemaException(e); + Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); + // colors here are not important + ColorModelCommand command = new ColorModelCommand(model, schemas, + new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); + List<Pair<Reaction, ColorSchema>> result = new ArrayList<>(); + for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { + if (entry.getKey() instanceof Reaction) { + result.add(new Pair<>((Reaction) entry.getKey(), entry.getValue())); + } + } + result.sort(LayoutService.ELEMENT_PAIR_COMPARATOR); + return result; + } catch (InvalidColorSchemaException | IOException e) { + throw new InvalidStateException(e); } + } - layoutDao.flush(); + @Override + public Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId) { + try { + Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); + // colors here are not important + ColorModelCommand command = new ColorModelCommand(model, schemas, + new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); + return command.getModifiedElements(); + } catch (InvalidColorSchemaException | IOException e) { + throw new InvalidStateException(e); + } + } - Layout topLayout = new Layout(params.getName(), false); - topLayout.setColorSchemaType(params.getColorSchemaType()); - if (params.getUser() == null) { - topLayout.setPublicLayout(true); - } else { - topLayout.setPublicLayout(false); + @Override + public Pair<Element, ColorSchema> getFullAliasForLayout(Model model, Integer id, int layoutId) { + try { + Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); + // colors here are not important + ColorModelCommand command = new ColorModelCommand(model, schemas, + new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); + + for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { + if (entry.getKey() instanceof Element) { + Element alias = (Element) entry.getKey(); + if (id.equals(alias.getId())) { + return new Pair<>(alias, entry.getValue()); + } + } + } + return null; + } catch (InvalidColorSchemaException | IOException e) { + throw new InvalidStateException(e); } - topLayout.setGoogleLicenseConsent(params.isGoogleLicenseConsent()); - topLayout.setStatus(LayoutStatus.OK); - topLayout.setProgress(0.0); - UploadedFileEntry fileEntry = new UploadedFileEntry(); - fileEntry.setFileContent(IOUtils.toByteArray(params.getColorInputStream())); - fileEntry.setOriginalFileName(params.getLayoutFileName()); - fileEntry.setLength(fileEntry.getFileContent().length); - fileEntry.setOwner(params.getUser()); - topLayout.setInputData(fileEntry); - topLayout.setDescription(params.getDescription()); - topLayout.setProject(params.getProject()); - topLayout.setCreator(params.getUser()); - layoutDao.add(topLayout); + } - Thread sendEmailThread = new Thread(() -> { - try { - // open transaction for this thread - dbUtils.createSessionForCurrentThread(); - sendSuccessfullGenerationEmail(params, schemas); - } catch (MessagingException e) { - logger.error("Problem with sending email", e); - } finally { - dbUtils.closeSessionForCurrentThread(); + @Override + public Pair<Reaction, ColorSchema> getFullReactionForLayout(Model model, Integer id, int layoutId) { + try { + Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); + // colors here are not important + ColorModelCommand command = new ColorModelCommand(model, schemas, + new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); + + for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { + if (entry.getKey() instanceof Reaction) { + Reaction alias = (Reaction) entry.getKey(); + if (id.equals(alias.getId())) { + return new Pair<>(alias, entry.getValue()); + } + } } - }); + return null; + } catch (InvalidColorSchemaException | IOException e) { + throw new InvalidStateException(e); + } + } - logger.info("Data overlay " + topLayout.getId() + " created successfully"); - sendEmailThread.start(); - return topLayout; + @Override + public EmailSender getEmailSender() { + if (emailSender == null) { + emailSender = new EmailSender(configurationService); + } + return emailSender; + } + + @Override + public void setEmailSender(EmailSender emailSender) { + this.emailSender = emailSender; + } + + @Override + public List<Layout> getLayoutsByProject(Project project) { + List<Layout> result = new ArrayList<>(); + if (project == null) { + return result; + } + List<Layout> overlays = layoutDao.getLayoutsByProject(project); + result.addAll(overlays); + result.sort(Layout.ID_COMPARATOR); + return result; + } + + @Override + public Layout getLayoutById(int overlayId) { + return layoutDao.getById(overlayId); + } + + public void setLayoutDao(LayoutDao layoutDao) { + this.layoutDao = layoutDao; } /** @@ -541,125 +656,125 @@ public class LayoutService implements ILayoutService { return sb.toString(); } - /** - * Returns String representing data of {@link GenericColorSchema} that should - * appear in a given {@link ColorSchemaColumn}. - * - * @param schema - * object for which data will be returned - * @param column - * column for which data should be returned - * @return {@link String} representing data of {@link GenericColorSchema} that - * should appear in a given {@link ColorSchemaColumn} - */ - protected String prepareTableCellForGenericSchema(GenericColorSchema schema, ColorSchemaColumn column) { - StringBuilder sb = new StringBuilder(); - if (column.equals(ColorSchemaColumn.COLOR)) { - if (schema.getColor() != null) { - sb.append("#" + Integer.toHexString(schema.getColor().getRGB()).substring(2).toUpperCase()); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.NAME)) { - sb.append(schema.getName() + "\t"); - } else if (column.equals(ColorSchemaColumn.MAP_NAME)) { - sb.append(schema.getModelName() + "\t"); - } else if (column.equals(ColorSchemaColumn.VALUE)) { - sb.append(schema.getValue() + "\t"); - } else if (column.equals(ColorSchemaColumn.COMPARTMENT)) { - for (String str : schema.getCompartments()) { - sb.append(str + ", "); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.TYPE)) { - for (Class<? extends Element> str : schema.getTypes()) { - sb.append(str.getSimpleName() + ", "); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.IDENTIFIER)) { - for (MiriamData md : schema.getMiriamData()) { - sb.append(md.getDataType().getCommonName() + ": " + md.getResource() + ", "); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.ELEMENT_IDENTIFIER)) { - sb.append(schema.getElementId() + "\t"); - } else if (column.equals(ColorSchemaColumn.LINE_WIDTH)) { - sb.append(schema.getLineWidth() + "\t"); - } else if (column.equals(ColorSchemaColumn.REVERSE_REACTION)) { - sb.append(schema.getReverseReaction() + "\t"); - } else if (column.equals(ColorSchemaColumn.POSITION)) { - sb.append(schema.getReverseReaction() + "\t"); - } else if (column.equals(ColorSchemaColumn.DESCRIPTION)) { - sb.append(schema.getDescription() + "\t"); - } else { - throw new InvalidArgumentException("Unknown column type: " + column + " for schema type: " + schema.getClass()); - } - return sb.toString(); + /** + * Returns String representing data of {@link GenericColorSchema} that should + * appear in a given {@link ColorSchemaColumn}. + * + * @param schema + * object for which data will be returned + * @param column + * column for which data should be returned + * @return {@link String} representing data of {@link GenericColorSchema} that + * should appear in a given {@link ColorSchemaColumn} + */ + protected String prepareTableCellForGenericSchema(GenericColorSchema schema, ColorSchemaColumn column) { + StringBuilder sb = new StringBuilder(); + if (column.equals(ColorSchemaColumn.COLOR)) { + if (schema.getColor() != null) { + sb.append("#" + Integer.toHexString(schema.getColor().getRGB()).substring(2).toUpperCase()); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.NAME)) { + sb.append(schema.getName() + "\t"); + } else if (column.equals(ColorSchemaColumn.MAP_NAME)) { + sb.append(schema.getModelName() + "\t"); + } else if (column.equals(ColorSchemaColumn.VALUE)) { + sb.append(schema.getValue() + "\t"); + } else if (column.equals(ColorSchemaColumn.COMPARTMENT)) { + for (String str : schema.getCompartments()) { + sb.append(str + ", "); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.TYPE)) { + for (Class<? extends Element> str : schema.getTypes()) { + sb.append(str.getSimpleName() + ", "); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.IDENTIFIER)) { + for (MiriamData md : schema.getMiriamData()) { + sb.append(md.getDataType().getCommonName() + ": " + md.getResource() + ", "); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.ELEMENT_IDENTIFIER)) { + sb.append(schema.getElementId() + "\t"); + } else if (column.equals(ColorSchemaColumn.LINE_WIDTH)) { + sb.append(schema.getLineWidth() + "\t"); + } else if (column.equals(ColorSchemaColumn.REVERSE_REACTION)) { + sb.append(schema.getReverseReaction() + "\t"); + } else if (column.equals(ColorSchemaColumn.POSITION)) { + sb.append(schema.getReverseReaction() + "\t"); + } else if (column.equals(ColorSchemaColumn.DESCRIPTION)) { + sb.append(schema.getDescription() + "\t"); + } else { + throw new InvalidArgumentException("Unknown column type: " + column + " for schema type: " + schema.getClass()); } + return sb.toString(); + } - /** - * Returns String representing data of {@link GeneVariationColorSchema} that - * should appear in a given {@link ColorSchemaColumn}. - * - * @param schema - * object for which data will be returned - * @param column - * column for which data should be returned - * @return {@link String} representing data of {@link GeneVariationColorSchema} - * that should appear in a given {@link ColorSchemaColumn} - */ - protected String prepareTableCellForGeneVariationSchema(GeneVariationColorSchema schema, ColorSchemaColumn column) { - StringBuilder sb = new StringBuilder(); - if (column.equals(ColorSchemaColumn.COLOR)) { - if (schema.getColor() != null) { - sb.append("#" + Integer.toHexString(schema.getColor().getRGB()).substring(2).toUpperCase()); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.NAME)) { - sb.append(schema.getName() + "\t"); - } else if (column.equals(ColorSchemaColumn.MAP_NAME)) { - sb.append(schema.getModelName() + "\t"); - } else if (column.equals(ColorSchemaColumn.VALUE)) { - sb.append(schema.getValue() + "\t"); - } else if (column.equals(ColorSchemaColumn.COMPARTMENT)) { - for (String str : schema.getCompartments()) { - sb.append(str + ", "); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.TYPE)) { - for (Class<? extends Element> str : schema.getTypes()) { - sb.append(str.getSimpleName() + ", "); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.IDENTIFIER)) { - for (MiriamData md : schema.getMiriamData()) { - sb.append(md.getDataType().getCommonName() + ": " + md.getResource() + ", "); - } - sb.append("\t"); - } else if (column.equals(ColorSchemaColumn.ELEMENT_IDENTIFIER)) { - sb.append(schema.getElementId() + "\t"); - } else if (column.equals(ColorSchemaColumn.LINE_WIDTH)) { - sb.append(schema.getLineWidth() + "\t"); - } else if (column.equals(ColorSchemaColumn.REVERSE_REACTION)) { - sb.append(schema.getReverseReaction() + "\t"); - } else if (column.equals(ColorSchemaColumn.POSITION)) { - sb.append(schema.getGeneVariations().get(0).getPosition() + "\t"); - } else if (column.equals(ColorSchemaColumn.DESCRIPTION)) { - sb.append(schema.getDescription() + "\t"); - } else if (column.equals(ColorSchemaColumn.ORIGINAL_DNA)) { - sb.append(schema.getGeneVariations().get(0).getOriginalDna() + "\t"); - } else if (column.equals(ColorSchemaColumn.ALTERNATIVE_DNA)) { - sb.append(schema.getGeneVariations().get(0).getModifiedDna() + "\t"); - } else if (column.equals(ColorSchemaColumn.REFERENCE_GENOME_TYPE)) { - sb.append(schema.getGeneVariations().get(0).getReferenceGenomeType() + "\t"); - } else if (column.equals(ColorSchemaColumn.REFERENCE_GENOME_VERSION)) { - sb.append(schema.getGeneVariations().get(0).getReferenceGenomeVersion() + "\t"); - } else if (column.equals(ColorSchemaColumn.CONTIG)) { - sb.append(schema.getGeneVariations().get(0).getContig() + "\t"); - } else { - throw new InvalidArgumentException("Unknown column type: " + column + " for schema type: " + schema.getClass()); - } - return sb.toString(); + /** + * Returns String representing data of {@link GeneVariationColorSchema} that + * should appear in a given {@link ColorSchemaColumn}. + * + * @param schema + * object for which data will be returned + * @param column + * column for which data should be returned + * @return {@link String} representing data of {@link GeneVariationColorSchema} + * that should appear in a given {@link ColorSchemaColumn} + */ + protected String prepareTableCellForGeneVariationSchema(GeneVariationColorSchema schema, ColorSchemaColumn column) { + StringBuilder sb = new StringBuilder(); + if (column.equals(ColorSchemaColumn.COLOR)) { + if (schema.getColor() != null) { + sb.append("#" + Integer.toHexString(schema.getColor().getRGB()).substring(2).toUpperCase()); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.NAME)) { + sb.append(schema.getName() + "\t"); + } else if (column.equals(ColorSchemaColumn.MAP_NAME)) { + sb.append(schema.getModelName() + "\t"); + } else if (column.equals(ColorSchemaColumn.VALUE)) { + sb.append(schema.getValue() + "\t"); + } else if (column.equals(ColorSchemaColumn.COMPARTMENT)) { + for (String str : schema.getCompartments()) { + sb.append(str + ", "); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.TYPE)) { + for (Class<? extends Element> str : schema.getTypes()) { + sb.append(str.getSimpleName() + ", "); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.IDENTIFIER)) { + for (MiriamData md : schema.getMiriamData()) { + sb.append(md.getDataType().getCommonName() + ": " + md.getResource() + ", "); + } + sb.append("\t"); + } else if (column.equals(ColorSchemaColumn.ELEMENT_IDENTIFIER)) { + sb.append(schema.getElementId() + "\t"); + } else if (column.equals(ColorSchemaColumn.LINE_WIDTH)) { + sb.append(schema.getLineWidth() + "\t"); + } else if (column.equals(ColorSchemaColumn.REVERSE_REACTION)) { + sb.append(schema.getReverseReaction() + "\t"); + } else if (column.equals(ColorSchemaColumn.POSITION)) { + sb.append(schema.getGeneVariations().get(0).getPosition() + "\t"); + } else if (column.equals(ColorSchemaColumn.DESCRIPTION)) { + sb.append(schema.getDescription() + "\t"); + } else if (column.equals(ColorSchemaColumn.ORIGINAL_DNA)) { + sb.append(schema.getGeneVariations().get(0).getOriginalDna() + "\t"); + } else if (column.equals(ColorSchemaColumn.ALTERNATIVE_DNA)) { + sb.append(schema.getGeneVariations().get(0).getModifiedDna() + "\t"); + } else if (column.equals(ColorSchemaColumn.REFERENCE_GENOME_TYPE)) { + sb.append(schema.getGeneVariations().get(0).getReferenceGenomeType() + "\t"); + } else if (column.equals(ColorSchemaColumn.REFERENCE_GENOME_VERSION)) { + sb.append(schema.getGeneVariations().get(0).getReferenceGenomeVersion() + "\t"); + } else if (column.equals(ColorSchemaColumn.CONTIG)) { + sb.append(schema.getGeneVariations().get(0).getContig() + "\t"); + } else { + throw new InvalidArgumentException("Unknown column type: " + column + " for schema type: " + schema.getClass()); } + return sb.toString(); + } /** * Returns byte array containing data from original input file that was used to @@ -684,141 +799,10 @@ public class LayoutService implements ILayoutService { } } - @Override - public List<Pair<Element, ColorSchema>> getAliasesForLayout(Model model, int layoutId) { - try { - Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); - // colors here are not important - ColorModelCommand command = new ColorModelCommand(model, schemas, - new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); - List<Pair<Element, ColorSchema>> result = new ArrayList<>(); - for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { - if (entry.getKey() instanceof Element) { - result.add(new Pair<>((Element) entry.getKey(), entry.getValue())); - } - } - result.sort(LayoutService.ELEMENT_PAIR_COMPARATOR); - return result; - } catch (InvalidColorSchemaException | IOException e) { - throw new InvalidStateException(e); - } - } - private Collection<ColorSchema> createColorSchemaCollection(int overlayId) throws IOException, InvalidColorSchemaException { ColorSchemaReader reader = new ColorSchemaReader(); Layout overlay = getLayoutById(overlayId); return reader.readColorSchema(getInputDataForLayout(overlayId), overlay.getColorSchemaType()); } - - @Override - public List<Pair<Reaction, ColorSchema>> getReactionsForLayout(Model model, int layoutId) { - try { - Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); - // colors here are not important - ColorModelCommand command = new ColorModelCommand(model, schemas, - new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); - List<Pair<Reaction, ColorSchema>> result = new ArrayList<>(); - for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { - if (entry.getKey() instanceof Reaction) { - result.add(new Pair<>((Reaction) entry.getKey(), entry.getValue())); - } - } - result.sort(LayoutService.ELEMENT_PAIR_COMPARATOR); - return result; - } catch (InvalidColorSchemaException | IOException e) { - throw new InvalidStateException(e); - } - } - - @Override - public Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId) { - try { - Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); - // colors here are not important - ColorModelCommand command = new ColorModelCommand(model, schemas, - new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); - return command.getModifiedElements(); - } catch (InvalidColorSchemaException | IOException e) { - throw new InvalidStateException(e); - } - } - - @Override - public EmailSender getEmailSender() { - if (emailSender == null) { - emailSender = new EmailSender(configurationService); - } - return emailSender; - } - - @Override - public void setEmailSender(EmailSender emailSender) { - this.emailSender = emailSender; - } - - @Override - public List<Layout> getLayoutsByProject(Project project) { - List<Layout> result = new ArrayList<>(); - if (project == null) { - return result; - } - List<Layout> overlays = layoutDao.getLayoutsByProject(project); - result.addAll(overlays); - result.sort(Layout.ID_COMPARATOR); - return result; - } - - @Override - public Layout getLayoutById(int overlayId) { - return layoutDao.getById(overlayId); - } - - @Override - public Pair<Element, ColorSchema> getFullAliasForLayout(Model model, Integer id, int layoutId) { - try { - Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); - // colors here are not important - ColorModelCommand command = new ColorModelCommand(model, schemas, - new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); - - for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { - if (entry.getKey() instanceof Element) { - Element alias = (Element) entry.getKey(); - if (id.equals(alias.getId())) { - return new Pair<>(alias, entry.getValue()); - } - } - } - return null; - } catch (InvalidColorSchemaException | IOException e) { - throw new InvalidStateException(e); - } - } - - @Override - public Pair<Reaction, ColorSchema> getFullReactionForLayout(Model model, Integer id, int layoutId) { - try { - Collection<ColorSchema> schemas = createColorSchemaCollection(layoutId); - // colors here are not important - ColorModelCommand command = new ColorModelCommand(model, schemas, - new ColorExtractor(Color.BLACK, Color.BLACK, Color.BLACK)); - - for (Map.Entry<Object, ColorSchema> entry : command.getModifiedElements().entrySet()) { - if (entry.getKey() instanceof Reaction) { - Reaction alias = (Reaction) entry.getKey(); - if (id.equals(alias.getId())) { - return new Pair<>(alias, entry.getValue()); - } - } - } - return null; - } catch (InvalidColorSchemaException | IOException e) { - throw new InvalidStateException(e); - } - } - - public void setLayoutDao(LayoutDao layoutDao) { - this.layoutDao = layoutDao; - } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/LdapService.java b/service/src/main/java/lcsb/mapviewer/services/impl/LdapService.java index 88046b8928..f89a7f1ad5 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/LdapService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/LdapService.java @@ -4,21 +4,13 @@ import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import com.unboundid.ldap.sdk.Attribute; -import com.unboundid.ldap.sdk.BindResult; -import com.unboundid.ldap.sdk.Filter; -import com.unboundid.ldap.sdk.LDAPConnection; -import com.unboundid.ldap.sdk.LDAPException; -import com.unboundid.ldap.sdk.ResultCode; -import com.unboundid.ldap.sdk.SearchResult; -import com.unboundid.ldap.sdk.SearchResultEntry; -import com.unboundid.ldap.sdk.SearchScope; -import com.unboundid.ldap.sdk.SimpleBindRequest; +import com.unboundid.ldap.sdk.*; import com.unboundid.util.ssl.SSLUtil; import com.unboundid.util.ssl.TrustAllTrustManager; @@ -202,6 +194,25 @@ public class LdapService implements ILdapService { } } + @Override + public boolean isValidConfiguration() { + try { + String baseDn = configurationService.getConfigurationValue(ConfigurationElementType.LDAP_BASE_DN); + if (baseDn == null || baseDn.trim().isEmpty()) { + return false; + } + LDAPConnection connection = getConnection(); + if (connection != null) { + connection.close(); + return true; + } + return false; + } catch (Exception e) { + logger.error(e, e); + return false; + } + } + private Filter createObjectClassFilter() throws LDAPException { String objectClass = configurationService.getConfigurationValue(ConfigurationElementType.LDAP_OBJECT_CLASS); @@ -234,23 +245,4 @@ public class LdapService implements ILdapService { public void setConfigurationService(IConfigurationService configurationService) { this.configurationService = configurationService; } - - @Override - public boolean isValidConfiguration() { - try { - String baseDn = configurationService.getConfigurationValue(ConfigurationElementType.LDAP_BASE_DN); - if (baseDn == null || baseDn.trim().isEmpty()) { - return false; - } - LDAPConnection connection = getConnection(); - if (connection != null) { - connection.close(); - return true; - } - return false; - } catch (Exception e) { - logger.error(e, e); - return false; - } - } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/MiriamService.java b/service/src/main/java/lcsb/mapviewer/services/impl/MiriamService.java index d4562371c1..fa4ba2a636 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/MiriamService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/MiriamService.java @@ -1,14 +1,14 @@ package lcsb.mapviewer.services.impl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + import lcsb.mapviewer.annotation.services.MiriamConnector; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.services.interfaces.IMiriamService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - /** * Implementation of service responsible for accessing miriam registry. * @@ -19,42 +19,42 @@ import org.springframework.transaction.annotation.Transactional; @Service public class MiriamService implements IMiriamService { - /** - * Object accessing <a href= "http://www.ebi.ac.uk/miriam/main/" >miriam - * registry</a>. - */ - private MiriamConnector miriamConnector; - - @Autowired - public MiriamService(MiriamConnector miriamConnector) { - this.miriamConnector = miriamConnector; - } - - @Override - public String getUrlForMiriamData(MiriamData md) { - return miriamConnector.getUrlString(md); - } - - /** - * @return the miriamConnector - * @see #miriamConnector - */ - public MiriamConnector getMiriamConnector() { - return miriamConnector; - } - - /** - * @param miriamConnector - * the miriamConnector to set - * @see #miriamConnector - */ - public void setMiriamConnector(MiriamConnector miriamConnector) { - this.miriamConnector = miriamConnector; - } - - @Override - public MiriamType getTypeForUri(String uri) { - return MiriamType.getTypeByUri(uri); - } + /** + * Object accessing <a href= "http://www.ebi.ac.uk/miriam/main/" >miriam + * registry</a>. + */ + private MiriamConnector miriamConnector; + + @Autowired + public MiriamService(MiriamConnector miriamConnector) { + this.miriamConnector = miriamConnector; + } + + @Override + public String getUrlForMiriamData(MiriamData md) { + return miriamConnector.getUrlString(md); + } + + @Override + public MiriamType getTypeForUri(String uri) { + return MiriamType.getTypeByUri(uri); + } + + /** + * @return the miriamConnector + * @see #miriamConnector + */ + public MiriamConnector getMiriamConnector() { + return miriamConnector; + } + + /** + * @param miriamConnector + * the miriamConnector to set + * @see #miriamConnector + */ + public void setMiriamConnector(MiriamConnector miriamConnector) { + this.miriamConnector = miriamConnector; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java index 46ef85f5d0..953f5f404e 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java @@ -1,9 +1,6 @@ package lcsb.mapviewer.services.impl; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -12,19 +9,13 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.Article; -import lcsb.mapviewer.annotation.services.MiriamConnector; -import lcsb.mapviewer.annotation.services.PubmedParser; -import lcsb.mapviewer.annotation.services.PubmedSearchException; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.commands.CopyCommand; import lcsb.mapviewer.common.IProgressUpdater; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -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.model.SubmodelConnection; +import lcsb.mapviewer.model.map.model.*; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.persist.dao.ProjectDao; @@ -42,21 +33,18 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Service public class ModelService implements IModelService { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(ModelService.class); - /** * List of cached models. */ private static Map<String, Model> models = new HashMap<String, Model>(); - /** * List of models that are currently being loaded from database. */ private static Set<String> modelsInLoadStage = new HashSet<>(); - + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(ModelService.class); /** * Service that manages and gives access to user information. */ @@ -74,7 +62,6 @@ public class ModelService implements IModelService { */ private PubmedParser backend; - /** * Connector used for accessing data from miriam registry. */ @@ -82,10 +69,10 @@ public class ModelService implements IModelService { @Autowired public ModelService(IUserService userService, - ModelDao modelDao, - ProjectDao projectDao, - PubmedParser backend, - MiriamConnector miriamConnector) { + ModelDao modelDao, + ProjectDao projectDao, + PubmedParser backend, + MiriamConnector miriamConnector) { this.userService = userService; this.modelDao = modelDao; this.projectDao = projectDao; @@ -240,6 +227,29 @@ public class ModelService implements IModelService { models.remove(projectId); } + @Override + public void updateModel(ModelData model) { + Project project = model.getProject(); + if (project == null) { + for (SubmodelConnection sc : model.getParentModels()) { + if (sc instanceof ModelSubmodelConnection) { + project = ((ModelSubmodelConnection) sc).getParentModel().getModel().getProject(); + if (project != null) { + break; + } + } + } + } + + Model topCachedData = getLastModelByProjectId(project.getProjectId()); + Model cachedData = topCachedData.getSubmodelById(model.getId()); + cachedData.setDefaultCenterX(model.getDefaultCenterX()); + cachedData.setDefaultCenterY(model.getDefaultCenterY()); + cachedData.setDefaultZoomLevel(model.getDefaultZoomLevel()); + modelDao.update(model); + + } + /** * @return the userService * @see #userService @@ -274,27 +284,4 @@ public class ModelService implements IModelService { this.projectDao = projectDao; } - @Override - public void updateModel(ModelData model) { - Project project = model.getProject(); - if (project == null) { - for (SubmodelConnection sc : model.getParentModels()) { - if (sc instanceof ModelSubmodelConnection) { - project = ((ModelSubmodelConnection) sc).getParentModel().getModel().getProject(); - if (project != null) { - break; - } - } - } - } - - Model topCachedData = getLastModelByProjectId(project.getProjectId()); - Model cachedData = topCachedData.getSubmodelById(model.getId()); - cachedData.setDefaultCenterX(model.getDefaultCenterX()); - cachedData.setDefaultCenterY(model.getDefaultCenterY()); - cachedData.setDefaultZoomLevel(model.getDefaultZoomLevel()); - modelDao.update(model); - - } - } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/PrivilegeService.java b/service/src/main/java/lcsb/mapviewer/services/impl/PrivilegeService.java index 4b2c3b6e29..51ee7b264b 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/PrivilegeService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/PrivilegeService.java @@ -1,12 +1,13 @@ package lcsb.mapviewer.services.impl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + import lcsb.mapviewer.model.security.Privilege; import lcsb.mapviewer.model.security.PrivilegeType; import lcsb.mapviewer.persist.dao.security.PrivilegeDao; import lcsb.mapviewer.services.interfaces.IPrivilegeService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; @Transactional @Service diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java index 6e092f2b1b..fbe11c351d 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java @@ -309,11 +309,273 @@ public class ProjectService implements IProjectService { } + @Override + public void addProject(Project project) { + projectDao.add(project); + + } + + @Override + public void createProject(final CreateProjectParams params) throws SecurityException { + // this count down is used to wait for asynchronous thread to initialize + // data in the db (probably it would be better to move the initialization to + // main thread) + final CountDownLatch waitForInitialData = new CountDownLatch(1); + + Thread computations = new Thread(new Runnable() { + + @Override + public void run() { + if (params.isAsync()) { + // because we are running this in separate thread we need to open a + // new session for db connection + dbUtils.createSessionForCurrentThread(); + } + + Project project = createProjectFromParams(params); + projectDao.add(project); + if (params.isAsync()) { + projectDao.commit(); + } + waitForInitialData.countDown(); + double[] outOfMemoryBuffer; + MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); + try { + logger.debug("Running: " + params.getProjectId() + "; " + params.getProjectFile()); + outOfMemoryBuffer = new double[OUT_OF_MEMORY_BACKUP_BUFFER_SIZE]; + for (int i = 0; i < OUT_OF_MEMORY_BACKUP_BUFFER_SIZE; i++) { + outOfMemoryBuffer[i] = Math.random() * OUT_OF_MEMORY_BACKUP_BUFFER_SIZE; + } + + UploadedFileEntry file = params.getProjectFile(); + project.setInputData(file); + + createModel(params, project); + Model originalModel = project.getModels().iterator().next().getModel(); + new CreateHierarchyCommand(originalModel, generator.computeZoomLevels(originalModel), + generator.computeZoomFactor(originalModel)).execute(); + for (Model model : originalModel.getSubmodels()) { + new CreateHierarchyCommand(model, generator.computeZoomLevels(model), generator.computeZoomFactor(model)) + .execute(); + } + + createImages(project, params); + + for (Layout layout : project.getLayouts()) { + for (DataOverlayImageLayer imageLayer : layout.getDataOverlayImageLayers()) { + String[] tmp = imageLayer.getDirectory().split("[\\\\/]"); + imageLayer.setDirectory(tmp[tmp.length - 1]); + } + } + + projectDao.update(project); + + if (params.isAnalyzeAnnotations()) { + analyzeAnnotations(originalModel, params); + } + MinervaLoggerAppender.unregisterLogEventStorage(appender); + project.addLoggingInfo(appender); + + if (params.isCacheModel()) { + cacheData(originalModel, params); + } + + updateProjectStatus(project, ProjectStatus.DONE, IProgressUpdater.MAX_PROGRESS, params); + if (project.getNotifyEmail() != null && !project.getNotifyEmail().equals("")) { + try { + sendSuccesfullEmail(originalModel); + } catch (MessagingException e) { + logger.error(e, e); + } + } + + logger.info("Project " + project.getProjectId() + " created successfully."); + } catch (HibernateException e) { + outOfMemoryBuffer = null; + logger.error("Problem with database", e); + handleHibernateExceptionReporting(params, e); + } catch (Exception e) { + outOfMemoryBuffer = null; + handleCreateProjectException(params, e); + } catch (OutOfMemoryError oome) { + // release some memory + outOfMemoryBuffer = null; + logger.error("Out of memory", oome); + if (project != null) { + project.setErrors("Out of memory: " + oome.getMessage()); + } + updateProjectStatus(project, ProjectStatus.FAIL, IProgressUpdater.MAX_PROGRESS, params); + } finally { + if (params.isAsync()) { + // close the transaction for this thread + dbUtils.closeSessionForCurrentThread(); + } + MinervaLoggerAppender.unregisterLogEventStorage(appender); + } + } + + }); + if (params.isAsync()) { + computations.start(); + } else { + computations.run(); + } + + try { + waitForInitialData.await(); + } catch (InterruptedException e1) { + logger.error(e1, e1); + } + + } + + @Override + public TreeNode createClassAnnotatorTree(User user) { + + UserAnnotationSchema annotationSchema = prepareUserAnnotationSchema(user); + + ElementUtils elementUtils = new ElementUtils(); + + ClassTreeNode top = elementUtils.getAnnotatedElementClassTree(); + + Class<?> clazz = top.getClazz(); + top.setData(annotationSchema.requiresAtLeastOneAnnotation(clazz)); + List<AnnotatorData> annotators = annotationSchema.getAnnotatorsForClass(clazz); + if (annotators == null) { + annotators = new ArrayList<>(); + } + TreeNode root = new DefaultTreeNode(new AnnotatedObjectTreeRow(top, modelAnnotator.getAvailableAnnotators(clazz), + modelAnnotator.getAnnotatorsFromCommonNames(annotators), + annotationSchema.getValidAnnotations(clazz), annotationSchema.getRequiredAnnotations(clazz)), null); + + root.setExpanded(true); + + Queue<Pair<ClassTreeNode, TreeNode>> nodes = new LinkedList<Pair<ClassTreeNode, TreeNode>>(); + nodes.add(new Pair<ClassTreeNode, TreeNode>(top, root)); + // create children + + Queue<TreeNode> expandParents = new LinkedList<TreeNode>(); + + while (!nodes.isEmpty()) { + Pair<ClassTreeNode, TreeNode> element = nodes.poll(); + + for (ClassTreeNode node : element.getLeft().getChildren()) { + + clazz = node.getClazz(); + node.setData(annotationSchema.requiresAtLeastOneAnnotation(clazz)); + annotators = annotationSchema.getAnnotatorsForClass(clazz); + if (annotators == null) { + annotators = new ArrayList<>(); + } + AnnotatedObjectTreeRow data = new AnnotatedObjectTreeRow(node, modelAnnotator.getAvailableAnnotators(clazz), + modelAnnotator.getAnnotatorsFromCommonNames(annotators), + annotationSchema.getValidAnnotations(clazz), annotationSchema.getRequiredAnnotations(clazz)); + TreeNode treeNode = new DefaultTreeNode(data, element.getRight()); + nodes.add(new Pair<ClassTreeNode, TreeNode>(node, treeNode)); + if (data.getUsedAnnotators().size() > 0 || data.getValidAnnotators().size() > 0) { + expandParents.add(treeNode); + } + } + } + while (!expandParents.isEmpty()) { + TreeNode node = expandParents.poll(); + if (node.getParent() != null && !node.getParent().isExpanded()) { + node.getParent().setExpanded(true); + expandParents.add(node.getParent()); + } + } + + return root; + + } + + @Override + public void updateClassAnnotatorTreeForUser(User user, TreeNode annotatorsTree, boolean sbgnFormat, + boolean networkLayoutAsDefault) { + User dbUser = userDao.getById(user.getId()); + if (dbUser.getAnnotationSchema() == null) { + dbUser.setAnnotationSchema(new UserAnnotationSchema()); + } + UserAnnotationSchema annotationSchema = dbUser.getAnnotationSchema(); + + Queue<TreeNode> queue = new LinkedList<TreeNode>(); + queue.add(annotatorsTree); + while (!queue.isEmpty()) { + TreeNode node = queue.poll(); + queue.addAll(node.getChildren()); + AnnotatedObjectTreeRow data = (AnnotatedObjectTreeRow) node.getData(); + annotationSchema.addClassAnnotator(new UserClassAnnotators(data.getClazz(), data.getUsedAnnotators())); + annotationSchema.addClassRequiredAnnotations( + new UserClassRequiredAnnotations(data.getClazz(), data.getRequiredAnnotations())); + annotationSchema + .addClassValidAnnotations(new UserClassValidAnnotations(data.getClazz(), data.getValidAnnotations())); + } + annotationSchema.setSbgnFormat(sbgnFormat); + annotationSchema.setNetworkLayoutAsDefault(networkLayoutAsDefault); + userService.updateUser(dbUser); + user.setAnnotationSchema(annotationSchema); + } + + @Override + public void updateProject(Project project) { + projectDao.update(project); + } + + /** + * Retrieves (or creates) annotation schema for a given user. + * + * @param user + * for this users {@link UserAnnotationSchema} will be prepared + * @return {@link UserAnnotationSchema} for {@link User} + */ + public UserAnnotationSchema prepareUserAnnotationSchema(User user) { + UserAnnotationSchema annotationSchema = null; + if (user != null) { + annotationSchema = userDao.getById(user.getId()).getAnnotationSchema(); + if (annotationSchema != null && annotationSchema.getClassAnnotators().size() == 0) { + for (UserClassAnnotators uca : modelAnnotator.createDefaultAnnotatorSchema().getClassAnnotators()) { + annotationSchema.addClassAnnotator(uca); + } + } + } + if (annotationSchema == null) { + annotationSchema = modelAnnotator.createDefaultAnnotatorSchema(); + + ElementUtils elementUtils = new ElementUtils(); + + ClassTreeNode top = elementUtils.getAnnotatedElementClassTree(); + + Map<Class<? extends BioEntity>, Set<MiriamType>> validMiriam = modelAnnotator.getDefaultValidClasses(); + Map<Class<? extends BioEntity>, Set<MiriamType>> requiredMiriam = modelAnnotator.getDefaultRequiredClasses(); + + Queue<ClassTreeNode> nodes = new LinkedList<ClassTreeNode>(); + nodes.add(top); + + while (!nodes.isEmpty()) { + ClassTreeNode element = nodes.poll(); + annotationSchema.addClassAnnotator(new UserClassAnnotators(element.getClazz(), + modelAnnotator.getDefaultAnnotators(element.getClazz()))); + annotationSchema.addClassValidAnnotations( + new UserClassValidAnnotations(element.getClazz(), validMiriam.get(element.getClazz()))); + annotationSchema.addClassRequiredAnnotations( + new UserClassRequiredAnnotations(element.getClazz(), requiredMiriam.get(element.getClazz()))); + nodes.addAll(element.getChildren()); + } + if (user != null) { + User dbUser = userDao.getById(user.getId()); + dbUser.setAnnotationSchema(annotationSchema); + userDao.update(dbUser); + } + } + return annotationSchema; + } + /** * When we encountered hibernate exception we need to handle error reporting * differently (hibernate session is broken). This method handles such case when * hibernate exception occurred when removing project. - * @param originalProject + * + * @param originalProject * project that was being removed * @param exception */ @@ -343,15 +605,9 @@ public class ProjectService implements IProjectService { reportInSeparateThread.start(); } - @Override - public void addProject(Project project) { - projectDao.add(project); - - } - /** * This method creates set of images for the model layouts. - * + * * @param project * project for which we create layout images * @param params @@ -607,120 +863,6 @@ public class ProjectService implements IProjectService { } } - @Override - public void createProject(final CreateProjectParams params) throws SecurityException { - // this count down is used to wait for asynchronous thread to initialize - // data in the db (probably it would be better to move the initialization to - // main thread) - final CountDownLatch waitForInitialData = new CountDownLatch(1); - - Thread computations = new Thread(new Runnable() { - - @Override - public void run() { - if (params.isAsync()) { - // because we are running this in separate thread we need to open a - // new session for db connection - dbUtils.createSessionForCurrentThread(); - } - - Project project = createProjectFromParams(params); - projectDao.add(project); - if (params.isAsync()) { - projectDao.commit(); - } - waitForInitialData.countDown(); - double[] outOfMemoryBuffer; - MinervaLoggerAppender appender = MinervaLoggerAppender.createAppender(); - try { - logger.debug("Running: " + params.getProjectId() + "; " + params.getProjectFile()); - outOfMemoryBuffer = new double[OUT_OF_MEMORY_BACKUP_BUFFER_SIZE]; - for (int i = 0; i < OUT_OF_MEMORY_BACKUP_BUFFER_SIZE; i++) { - outOfMemoryBuffer[i] = Math.random() * OUT_OF_MEMORY_BACKUP_BUFFER_SIZE; - } - - UploadedFileEntry file = params.getProjectFile(); - project.setInputData(file); - - createModel(params, project); - Model originalModel = project.getModels().iterator().next().getModel(); - new CreateHierarchyCommand(originalModel, generator.computeZoomLevels(originalModel), - generator.computeZoomFactor(originalModel)).execute(); - for (Model model : originalModel.getSubmodels()) { - new CreateHierarchyCommand(model, generator.computeZoomLevels(model), generator.computeZoomFactor(model)) - .execute(); - } - - createImages(project, params); - - for (Layout layout : project.getLayouts()) { - for (DataOverlayImageLayer imageLayer : layout.getDataOverlayImageLayers()) { - String[] tmp = imageLayer.getDirectory().split("[\\\\/]"); - imageLayer.setDirectory(tmp[tmp.length - 1]); - } - } - - projectDao.update(project); - - if (params.isAnalyzeAnnotations()) { - analyzeAnnotations(originalModel, params); - } - MinervaLoggerAppender.unregisterLogEventStorage(appender); - project.addLoggingInfo(appender); - - if (params.isCacheModel()) { - cacheData(originalModel, params); - } - - updateProjectStatus(project, ProjectStatus.DONE, IProgressUpdater.MAX_PROGRESS, params); - if (project.getNotifyEmail() != null && !project.getNotifyEmail().equals("")) { - try { - sendSuccesfullEmail(originalModel); - } catch (MessagingException e) { - logger.error(e, e); - } - } - - logger.info("Project " + project.getProjectId() + " created successfully."); - } catch (HibernateException e) { - outOfMemoryBuffer = null; - logger.error("Problem with database", e); - handleHibernateExceptionReporting(params, e); - } catch (Exception e) { - outOfMemoryBuffer = null; - handleCreateProjectException(params, e); - } catch (OutOfMemoryError oome) { - // release some memory - outOfMemoryBuffer = null; - logger.error("Out of memory", oome); - if (project != null) { - project.setErrors("Out of memory: " + oome.getMessage()); - } - updateProjectStatus(project, ProjectStatus.FAIL, IProgressUpdater.MAX_PROGRESS, params); - } finally { - if (params.isAsync()) { - // close the transaction for this thread - dbUtils.closeSessionForCurrentThread(); - } - MinervaLoggerAppender.unregisterLogEventStorage(appender); - } - } - - }); - if (params.isAsync()) { - computations.start(); - } else { - computations.run(); - } - - try { - waitForInitialData.await(); - } catch (InterruptedException e1) { - logger.error(e1, e1); - } - - } - /** * Cache pubmed data for the model. * @@ -742,15 +884,16 @@ public class ProjectService implements IProjectService { updateProjectStatus(originalModel.getProject(), ProjectStatus.CACHING_MIRIAM, progress, params); } }); - + logger.warn("Cache of chemicals data is disabled"); -// chemicalService.cacheDataForModel(originalModel, new IProgressUpdater() { -// @Override -// public void setProgress(double progress) { -// updateProjectStatus(originalModel.getProject(), ProjectStatus.CACHING_CHEMICAL, progress, params); -// } -// }); + // chemicalService.cacheDataForModel(originalModel, new IProgressUpdater() { + // @Override + // public void setProgress(double progress) { + // updateProjectStatus(originalModel.getProject(), + // ProjectStatus.CACHING_CHEMICAL, progress, params); + // } + // }); drugService.cacheDataForModel(originalModel, new IProgressUpdater() { @Override @@ -835,142 +978,6 @@ public class ProjectService implements IProjectService { emailSender.sendEmail("MapViewer notification", "Map " + projectId + " was successfully removed.<br/>", email); } - @Override - public TreeNode createClassAnnotatorTree(User user) { - - UserAnnotationSchema annotationSchema = prepareUserAnnotationSchema(user); - - ElementUtils elementUtils = new ElementUtils(); - - ClassTreeNode top = elementUtils.getAnnotatedElementClassTree(); - - Class<?> clazz = top.getClazz(); - top.setData(annotationSchema.requiresAtLeastOneAnnotation(clazz)); - List<AnnotatorData> annotators = annotationSchema.getAnnotatorsForClass(clazz); - if (annotators == null) { - annotators = new ArrayList<>(); - } - TreeNode root = new DefaultTreeNode(new AnnotatedObjectTreeRow(top, modelAnnotator.getAvailableAnnotators(clazz), - modelAnnotator.getAnnotatorsFromCommonNames(annotators), - annotationSchema.getValidAnnotations(clazz), annotationSchema.getRequiredAnnotations(clazz)), null); - - root.setExpanded(true); - - Queue<Pair<ClassTreeNode, TreeNode>> nodes = new LinkedList<Pair<ClassTreeNode, TreeNode>>(); - nodes.add(new Pair<ClassTreeNode, TreeNode>(top, root)); - // create children - - Queue<TreeNode> expandParents = new LinkedList<TreeNode>(); - - while (!nodes.isEmpty()) { - Pair<ClassTreeNode, TreeNode> element = nodes.poll(); - - for (ClassTreeNode node : element.getLeft().getChildren()) { - - clazz = node.getClazz(); - node.setData(annotationSchema.requiresAtLeastOneAnnotation(clazz)); - annotators = annotationSchema.getAnnotatorsForClass(clazz); - if (annotators == null) { - annotators = new ArrayList<>(); - } - AnnotatedObjectTreeRow data = new AnnotatedObjectTreeRow(node, modelAnnotator.getAvailableAnnotators(clazz), - modelAnnotator.getAnnotatorsFromCommonNames(annotators), - annotationSchema.getValidAnnotations(clazz), annotationSchema.getRequiredAnnotations(clazz)); - TreeNode treeNode = new DefaultTreeNode(data, element.getRight()); - nodes.add(new Pair<ClassTreeNode, TreeNode>(node, treeNode)); - if (data.getUsedAnnotators().size() > 0 || data.getValidAnnotators().size() > 0) { - expandParents.add(treeNode); - } - } - } - while (!expandParents.isEmpty()) { - TreeNode node = expandParents.poll(); - if (node.getParent() != null && !node.getParent().isExpanded()) { - node.getParent().setExpanded(true); - expandParents.add(node.getParent()); - } - } - - return root; - - } - - /** - * Retrieves (or creates) annotation schema for a given user. - * - * @param user - * for this users {@link UserAnnotationSchema} will be prepared - * @return {@link UserAnnotationSchema} for {@link User} - */ - public UserAnnotationSchema prepareUserAnnotationSchema(User user) { - UserAnnotationSchema annotationSchema = null; - if (user != null) { - annotationSchema = userDao.getById(user.getId()).getAnnotationSchema(); - if (annotationSchema != null && annotationSchema.getClassAnnotators().size() == 0) { - for (UserClassAnnotators uca : modelAnnotator.createDefaultAnnotatorSchema().getClassAnnotators()) { - annotationSchema.addClassAnnotator(uca); - } - } - } - if (annotationSchema == null) { - annotationSchema = modelAnnotator.createDefaultAnnotatorSchema(); - - ElementUtils elementUtils = new ElementUtils(); - - ClassTreeNode top = elementUtils.getAnnotatedElementClassTree(); - - Map<Class<? extends BioEntity>, Set<MiriamType>> validMiriam = modelAnnotator.getDefaultValidClasses(); - Map<Class<? extends BioEntity>, Set<MiriamType>> requiredMiriam = modelAnnotator.getDefaultRequiredClasses(); - - Queue<ClassTreeNode> nodes = new LinkedList<ClassTreeNode>(); - nodes.add(top); - - while (!nodes.isEmpty()) { - ClassTreeNode element = nodes.poll(); - annotationSchema.addClassAnnotator(new UserClassAnnotators(element.getClazz(), - modelAnnotator.getDefaultAnnotators(element.getClazz()))); - annotationSchema.addClassValidAnnotations( - new UserClassValidAnnotations(element.getClazz(), validMiriam.get(element.getClazz()))); - annotationSchema.addClassRequiredAnnotations( - new UserClassRequiredAnnotations(element.getClazz(), requiredMiriam.get(element.getClazz()))); - nodes.addAll(element.getChildren()); - } - if (user != null) { - User dbUser = userDao.getById(user.getId()); - dbUser.setAnnotationSchema(annotationSchema); - userDao.update(dbUser); - } - } - return annotationSchema; - } - - @Override - public void updateClassAnnotatorTreeForUser(User user, TreeNode annotatorsTree, boolean sbgnFormat, - boolean networkLayoutAsDefault) { - User dbUser = userDao.getById(user.getId()); - if (dbUser.getAnnotationSchema() == null) { - dbUser.setAnnotationSchema(new UserAnnotationSchema()); - } - UserAnnotationSchema annotationSchema = dbUser.getAnnotationSchema(); - - Queue<TreeNode> queue = new LinkedList<TreeNode>(); - queue.add(annotatorsTree); - while (!queue.isEmpty()) { - TreeNode node = queue.poll(); - queue.addAll(node.getChildren()); - AnnotatedObjectTreeRow data = (AnnotatedObjectTreeRow) node.getData(); - annotationSchema.addClassAnnotator(new UserClassAnnotators(data.getClazz(), data.getUsedAnnotators())); - annotationSchema.addClassRequiredAnnotations( - new UserClassRequiredAnnotations(data.getClazz(), data.getRequiredAnnotations())); - annotationSchema - .addClassValidAnnotations(new UserClassValidAnnotations(data.getClazz(), data.getValidAnnotations())); - } - annotationSchema.setSbgnFormat(sbgnFormat); - annotationSchema.setNetworkLayoutAsDefault(networkLayoutAsDefault); - userService.updateUser(dbUser); - user.setAnnotationSchema(annotationSchema); - } - /** * Sends email about unsuccessful project creation. * @@ -1007,11 +1014,6 @@ public class ProjectService implements IProjectService { originalModel.getProject().getNotifyEmail()); } - @Override - public void updateProject(Project project) { - projectDao.update(project); - } - /** * This method handles situation when sever db error appeared during uploading * of the project into database. diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java index ae6e57598d..681630525a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java @@ -4,21 +4,17 @@ import java.io.IOException; import java.net.URISyntaxException; import java.util.List; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import lcsb.mapviewer.annotation.services.genome.FileNotAvailableException; -import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnector; -import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnectorException; -import lcsb.mapviewer.annotation.services.genome.UcscReferenceGenomeConnector; +import lcsb.mapviewer.annotation.services.genome.*; import lcsb.mapviewer.common.IProgressUpdater; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.persist.dao.map.layout.ReferenceGenomeDao; import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; import lcsb.mapviewer.services.utils.ReferenceGenomeExistsException; @@ -52,7 +48,7 @@ public class ReferenceGenomeService implements IReferenceGenomeService { @Autowired public ReferenceGenomeService(UcscReferenceGenomeConnector ucscReferenceGenomeConnector, - ReferenceGenomeDao referenceGenomeDao) { + ReferenceGenomeDao referenceGenomeDao) { this.ucscReferenceGenomeConnector = ucscReferenceGenomeConnector; this.referenceGenomeDao = referenceGenomeDao; } @@ -73,23 +69,6 @@ public class ReferenceGenomeService implements IReferenceGenomeService { }, true, customUrl); } - /** - * Return {@link ReferenceGenomeConnector} implementation for given reference - * genome type. - * - * @param type - * type of reference genome - * @return {@link ReferenceGenomeConnector} implementation for given reference - * genome type - */ - private ReferenceGenomeConnector getReferenceGenomeConnector(ReferenceGenomeType type) { - if (type == ReferenceGenomeType.UCSC) { - return ucscReferenceGenomeConnector; - } else { - throw new InvalidArgumentException("Unknown reference genome type: " + type); - } - } - @Override public List<MiriamData> getOrganismsByReferenceGenomeType(ReferenceGenomeType type) throws ReferenceGenomeConnectorException { @@ -155,4 +134,21 @@ public class ReferenceGenomeService implements IReferenceGenomeService { return referenceGenomeDao.getById(id); } + /** + * Return {@link ReferenceGenomeConnector} implementation for given reference + * genome type. + * + * @param type + * type of reference genome + * @return {@link ReferenceGenomeConnector} implementation for given reference + * genome type + */ + private ReferenceGenomeConnector getReferenceGenomeConnector(ReferenceGenomeType type) { + if (type == ReferenceGenomeType.UCSC) { + return ucscReferenceGenomeConnector; + } else { + throw new InvalidArgumentException("Unknown reference genome type: " + type); + } + } + } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/SearchHistoryService.java b/service/src/main/java/lcsb/mapviewer/services/impl/SearchHistoryService.java index 044b165d4d..01b683784a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/SearchHistoryService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/SearchHistoryService.java @@ -1,14 +1,14 @@ package lcsb.mapviewer.services.impl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + import lcsb.mapviewer.model.map.statistics.SearchHistory; import lcsb.mapviewer.model.map.statistics.SearchType; import lcsb.mapviewer.persist.dao.map.statistics.SearchHistoryDao; import lcsb.mapviewer.services.interfaces.ISearchHistoryService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - /** * Implementation of the service that manages search history. * @@ -19,39 +19,39 @@ import org.springframework.transaction.annotation.Transactional; @Service public class SearchHistoryService implements ISearchHistoryService { - /** - * Data access object for search history entries. - */ - private SearchHistoryDao searchHistoryDao; - - @Autowired - public SearchHistoryService(SearchHistoryDao searchHistoryDao) { - this.searchHistoryDao = searchHistoryDao; - } - - @Override - public void addQuery(String query, SearchType type, String ipAddress, String map) { - SearchHistory searchHistory = new SearchHistory(); - searchHistory.setIpAddress(ipAddress); - searchHistory.setQuery(query); - searchHistory.setType(type); - searchHistory.setMap(map); - searchHistoryDao.add(searchHistory); - } - - /** - * @return the searchHistoryDao - */ - public SearchHistoryDao getSearchHistoryDao() { - return searchHistoryDao; - } - - /** - * @param searchHistoryDao - * the searchHistoryDao to set - */ - public void setSearchHistoryDao(SearchHistoryDao searchHistoryDao) { - this.searchHistoryDao = searchHistoryDao; - } + /** + * Data access object for search history entries. + */ + private SearchHistoryDao searchHistoryDao; + + @Autowired + public SearchHistoryService(SearchHistoryDao searchHistoryDao) { + this.searchHistoryDao = searchHistoryDao; + } + + @Override + public void addQuery(String query, SearchType type, String ipAddress, String map) { + SearchHistory searchHistory = new SearchHistory(); + searchHistory.setIpAddress(ipAddress); + searchHistory.setQuery(query); + searchHistory.setType(type); + searchHistory.setMap(map); + searchHistoryDao.add(searchHistory); + } + + /** + * @return the searchHistoryDao + */ + public SearchHistoryDao getSearchHistoryDao() { + return searchHistoryDao; + } + + /** + * @param searchHistoryDao + * the searchHistoryDao to set + */ + public void setSearchHistoryDao(SearchHistoryDao searchHistoryDao) { + this.searchHistoryDao = searchHistoryDao; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java b/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java index 9a215f67bf..28efbadb1c 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/SearchService.java @@ -1,44 +1,21 @@ package lcsb.mapviewer.services.impl; import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.logging.log4j.*; +import java.util.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidClassException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.SearchIndex; +import lcsb.mapviewer.common.exception.*; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.model.map.statistics.SearchType; import lcsb.mapviewer.persist.dao.map.ModelDao; import lcsb.mapviewer.services.interfaces.ISearchHistoryService; @@ -109,6 +86,12 @@ public class SearchService implements ISearchService { * subcomplex". */ private Map<String, Class<? extends Element>> speciesSearchReversePrefix = new HashMap<>(); + /** + * Object containing autocomplete lists for models. For every model the map + * between String and List is stored. The key in this map is incomplete typed + * word, and value list contains suggestions that should appear for this word. + */ + private Map<Model, Map<String, List<String>>> autoCompleteLists = new HashMap<Model, Map<String, List<String>>>(); /** * Default constructor that set list of prefixes used in the search queries. @@ -128,7 +111,7 @@ public class SearchService implements ISearchService { addSearchPrefix("unknown", Unknown.class); } - /** + /** * Adds search prefix for an element class. * * @param prefix @@ -139,66 +122,6 @@ public class SearchService implements ISearchService { private void addSearchPrefix(String prefix, Class<? extends Element> clazz) { speciesSearchPrefix.put(clazz, prefix); speciesSearchReversePrefix.put(prefix, clazz); - } - - /** - * Private class that defines internal search result element. Contains reference - * to original result and match score of the result. - * - * @author Piotr Gawron - * - */ - private class SearchResult implements Comparable<SearchResult> { - /** - * Reference to the original object. - */ - private BioEntity obj; - - /** - * Score of the result. - */ - private double score; - - @Override - public int compareTo(SearchResult o) { - if (score == o.getScore()) { - return obj.getId() - o.getObj().getId(); - } else if (score < o.getScore()) { - return 1; - } else { - return -1; - } - } - - /** - * @return the obj - */ - public BioEntity getObj() { - return obj; - } - - /** - * @param obj - * the obj to set - */ - public void setObj(BioEntity obj) { - this.obj = obj; - } - - /** - * @return the score - */ - public double getScore() { - return score; - } - - /** - * @param score - * the score to set - */ - public void setScore(double score) { - this.score = score; - } }; /** @@ -389,6 +312,80 @@ public class SearchService implements ISearchService { return result; } + @Override + public List<BioEntity> searchByQuery(Model model, String query, int limit, Boolean perfectMatch) { + return searchByQuery(model, query, limit, perfectMatch, null); + } + + @Override + public List<BioEntity> getClosestElements(Model model, Point2D point, int numberOfElements, boolean perfectHit, + Collection<String> types) { + List<BioEntity> result = new ArrayList<>(); + + // probably this could be improved algorithmitically, right now all objects + // are sorted by distance, and numberOfElements closest are chosen as a list + // of results + List<DistanceToObject> tmpList = new ArrayList<>(); + for (Reaction reaction : model.getReactions()) { + if (types.size() == 0 || types.contains(reaction.getStringType().toLowerCase())) { + tmpList.add(new DistanceToObject(reaction, point)); + } + } + for (Element element : model.getElements()) { + if ((element instanceof Species && types.size() == 0) || types.contains(element.getStringType().toLowerCase())) { + tmpList.add(new DistanceToObject(element, point)); + } + } + Collections.sort(tmpList); + int size = Math.min(tmpList.size(), numberOfElements); + for (int i = 0; i < size; i++) { + if (!perfectHit) { + result.add(tmpList.get(i).getReference()); + } else if (tmpList.get(i).getDistance() < Configuration.EPSILON) { + result.add(tmpList.get(i).getReference()); + } + } + return result; + } + + @Override + public List<String> getAutocompleteList(Model model, String query) { + Map<String, List<String>> autoCompleteMap = autoCompleteLists.get(model); + if (autoCompleteMap == null) { + autoCompleteMap = createAutocompleteMap(model); + autoCompleteLists.put(model, autoCompleteMap); + } + List<String> result = autoCompleteMap.get(query.toLowerCase().trim()); + if (result == null) { + result = new ArrayList<String>(); + } + return result; + } + + @Override + public String[] getSuggestedQueryList(Model model) { + Set<String> possibilities = new HashSet<String>(); + for (Element alias : model.getElements()) { + if (alias instanceof Species) { + possibilities.addAll(getSearchPossibilitiesForAlias(alias)); + } + } + for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { + for (Element alias : connection.getSubmodel().getModel().getElements()) { + if (alias instanceof Species) { + possibilities.addAll(getSearchPossibilitiesForAlias(alias)); + } + } + } + String[] sortedPossibilites = new String[possibilities.size()]; + int index = 0; + for (String string : possibilities) { + sortedPossibilites[index++] = string; + } + Arrays.sort(sortedPossibilites); + return sortedPossibilites; + } + /** * Returns elements that are annotated with the given miriam data. * @@ -442,138 +439,6 @@ public class SearchService implements ISearchService { return null; } - @Override - public List<BioEntity> getClosestElements(Model model, Point2D point, int numberOfElements, boolean perfectHit, - Collection<String> types) { - List<BioEntity> result = new ArrayList<>(); - - // probably this could be improved algorithmitically, right now all objects - // are sorted by distance, and numberOfElements closest are chosen as a list - // of results - List<DistanceToObject> tmpList = new ArrayList<>(); - for (Reaction reaction : model.getReactions()) { - if (types.size() == 0 || types.contains(reaction.getStringType().toLowerCase())) { - tmpList.add(new DistanceToObject(reaction, point)); - } - } - for (Element element : model.getElements()) { - if ((element instanceof Species && types.size() == 0) || types.contains(element.getStringType().toLowerCase())) { - tmpList.add(new DistanceToObject(element, point)); - } - } - Collections.sort(tmpList); - int size = Math.min(tmpList.size(), numberOfElements); - for (int i = 0; i < size; i++) { - if (!perfectHit) { - result.add(tmpList.get(i).getReference()); - } else if (tmpList.get(i).getDistance() < Configuration.EPSILON) { - result.add(tmpList.get(i).getReference()); - } - } - return result; - } - - /** - * This class represents distance between object and some point. It's designed - * to help sort objects by their distance to some point. It It contains two - * fields: object reference and distance. - * - * @author Piotr Gawron - * - */ - private class DistanceToObject implements Comparable<DistanceToObject> { - /** - * Reference to the object. - */ - private BioEntity reference; - - /** - * Distance between the object and some point. - */ - private double distance; - - /** - * Constructor for reaction objects. - * - * @param reaction - * reaction reference to store - * @param point - * point from which the distance will be computed - */ - DistanceToObject(Reaction reaction, Point2D point) { - reference = reaction; - distance = reaction.getDistanceFromPoint(point); - } - - /** - * Constructor for alias objects. - * - * @param alias - * alias reference to store - * @param point - * point from which the distance will be computed - */ - DistanceToObject(Element alias, Point2D point) { - reference = alias; - distance = alias.getDistanceFromPoint(point); - } - - @Override - public int compareTo(DistanceToObject arg0) { - if (arg0.getDistance() < getDistance()) { - return 1; - } else if (arg0.getDistance() > getDistance()) { - return -1; - } else { - if (arg0.getReference().getZ() > getReference().getZ()) { - return 1; - } else if (arg0.getReference().getZ() < getReference().getZ()) { - return -1; - } else { - return 0; - } - } - } - - /** - * @return the reference - * @see #reference - */ - public BioEntity getReference() { - return reference; - } - - /** - * @return the distance - * @see #distance - */ - public double getDistance() { - return distance; - } - - } - - /** - * Object containing autocomplete lists for models. For every model the map - * between String and List is stored. The key in this map is incomplete typed - * word, and value list contains suggestions that should appear for this word. - */ - private Map<Model, Map<String, List<String>>> autoCompleteLists = new HashMap<Model, Map<String, List<String>>>(); - - @Override - public List<String> getAutocompleteList(Model model, String query) { - Map<String, List<String>> autoCompleteMap = autoCompleteLists.get(model); - if (autoCompleteMap == null) { - autoCompleteMap = createAutocompleteMap(model); - autoCompleteLists.put(model, autoCompleteMap); - } - List<String> result = autoCompleteMap.get(query.toLowerCase().trim()); - if (result == null) { - result = new ArrayList<String>(); - } - return result; - } - /** * Creates autocomplete map for a model. The key in this map is incomplete typed * word, and value list contains suggestions that should appear for this word. @@ -618,30 +483,6 @@ public class SearchService implements ISearchService { return result; } - @Override - public String[] getSuggestedQueryList(Model model) { - Set<String> possibilities = new HashSet<String>(); - for (Element alias : model.getElements()) { - if (alias instanceof Species) { - possibilities.addAll(getSearchPossibilitiesForAlias(alias)); - } - } - for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { - for (Element alias : connection.getSubmodel().getModel().getElements()) { - if (alias instanceof Species) { - possibilities.addAll(getSearchPossibilitiesForAlias(alias)); - } - } - } - String[] sortedPossibilites = new String[possibilities.size()]; - int index = 0; - for (String string : possibilities) { - sortedPossibilites[index++] = string; - } - Arrays.sort(sortedPossibilites); - return sortedPossibilites; - } - /** * Returns the list of all human readable search possibilities for alias. * @@ -695,9 +536,144 @@ public class SearchService implements ISearchService { this.searchHistoryService = searchHistoryService; } - @Override - public List<BioEntity> searchByQuery(Model model, String query, int limit, Boolean perfectMatch) { - return searchByQuery(model, query, limit, perfectMatch, null); +/** + * Private class that defines internal search result element. Contains reference + * to original result and match score of the result. + * + * @author Piotr Gawron + * + */ + private class SearchResult implements Comparable<SearchResult> { + /** + * Reference to the original object. + */ + private BioEntity obj; + + /** + * Score of the result. + */ + private double score; + + @Override + public int compareTo(SearchResult o) { + if (score == o.getScore()) { + return obj.getId() - o.getObj().getId(); + } else if (score < o.getScore()) { + return 1; + } else { + return -1; + } + } + + /** + * @return the obj + */ + public BioEntity getObj() { + return obj; + } + + /** + * @param obj + * the obj to set + */ + public void setObj(BioEntity obj) { + this.obj = obj; + } + + /** + * @return the score + */ + public double getScore() { + return score; + } + + /** + * @param score + * the score to set + */ + public void setScore(double score) { + this.score = score; + } + } + + /** + * This class represents distance between object and some point. It's designed + * to help sort objects by their distance to some point. It It contains two + * fields: object reference and distance. + * + * @author Piotr Gawron + * + */ + private class DistanceToObject implements Comparable<DistanceToObject> { + /** + * Reference to the object. + */ + private BioEntity reference; + + /** + * Distance between the object and some point. + */ + private double distance; + + /** + * Constructor for reaction objects. + * + * @param reaction + * reaction reference to store + * @param point + * point from which the distance will be computed + */ + DistanceToObject(Reaction reaction, Point2D point) { + reference = reaction; + distance = reaction.getDistanceFromPoint(point); + } + + /** + * Constructor for alias objects. + * + * @param alias + * alias reference to store + * @param point + * point from which the distance will be computed + */ + DistanceToObject(Element alias, Point2D point) { + reference = alias; + distance = alias.getDistanceFromPoint(point); + } + + @Override + public int compareTo(DistanceToObject arg0) { + if (arg0.getDistance() < getDistance()) { + return 1; + } else if (arg0.getDistance() > getDistance()) { + return -1; + } else { + if (arg0.getReference().getZ() > getReference().getZ()) { + return 1; + } else if (arg0.getReference().getZ() < getReference().getZ()) { + return -1; + } else { + return 0; + } + } + } + + /** + * @return the reference + * @see #reference + */ + public BioEntity getReference() { + return reference; + } + + /** + * @return the distance + * @see #distance + */ + public double getDistance() { + return distance; + } + } } \ No newline at end of file diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java index 793e35eb32..6d060e5578 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.services.impl; -import java.awt.Color; +import java.awt.*; import java.util.*; +import java.util.List; -import lcsb.mapviewer.model.security.*; -import lcsb.mapviewer.model.user.ConfigurationElementTypeGroup; -import lcsb.mapviewer.persist.dao.ProjectDao; -import lcsb.mapviewer.services.interfaces.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -16,9 +14,12 @@ import com.unboundid.ldap.sdk.LDAPException; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.geometry.ColorParser; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.model.security.Privilege; +import lcsb.mapviewer.model.security.PrivilegeType; +import lcsb.mapviewer.model.user.*; +import lcsb.mapviewer.persist.dao.ProjectDao; import lcsb.mapviewer.persist.dao.user.UserDao; +import lcsb.mapviewer.services.interfaces.*; @Transactional @Service @@ -33,10 +34,10 @@ public class UserService implements IUserService { @Autowired public UserService(UserDao userDao, - ILdapService ldapService, - IConfigurationService configurationService, - IPrivilegeService privilegeService, - ProjectDao projectDao) { + ILdapService ldapService, + IConfigurationService configurationService, + IPrivilegeService privilegeService, + ProjectDao projectDao) { this.userDao = userDao; this.ldapService = ldapService; this.configurationService = configurationService; @@ -54,6 +55,7 @@ public class UserService implements IUserService { public void updateUser(User user) { userDao.update(user); } + @Override public void deleteUser(User user) { String login = user.getLogin(); @@ -62,13 +64,13 @@ public class UserService implements IUserService { } @Override - public List<User> getUsers() { - return userDao.getAll(); + public User getUserByLogin(String login) { + return userDao.getUserByLogin(login); } @Override - public User getUserByLogin(String login) { - return userDao.getUserByLogin(login); + public List<User> getUsers() { + return userDao.getAll(); } @Override @@ -167,21 +169,21 @@ public class UserService implements IUserService { private void grantPrivilegesForDefaultConfigurationElementType(User user, ConfigurationElementType type) { switch (type) { - case DEFAULT_CAN_CREATE_OVERLAYS: - grantUserPrivilege(user, PrivilegeType.CAN_CREATE_OVERLAYS); - break; - case DEFAULT_READ_PROJECT: - grantUserPrivilege(user, PrivilegeType.READ_PROJECT, "*"); - projectDao.getAll() - .forEach(project -> grantUserPrivilege(user, PrivilegeType.READ_PROJECT, project.getProjectId())); - break; - case DEFAULT_WRITE_PROJECT: - grantUserPrivilege(user, PrivilegeType.WRITE_PROJECT, "*"); - projectDao.getAll() - .forEach(project -> grantUserPrivilege(user, PrivilegeType.WRITE_PROJECT, project.getProjectId())); - break; - default: - throw new IllegalArgumentException("The configuration element type '+" + type + "' is not handled."); + case DEFAULT_CAN_CREATE_OVERLAYS: + grantUserPrivilege(user, PrivilegeType.CAN_CREATE_OVERLAYS); + break; + case DEFAULT_READ_PROJECT: + grantUserPrivilege(user, PrivilegeType.READ_PROJECT, "*"); + projectDao.getAll() + .forEach(project -> grantUserPrivilege(user, PrivilegeType.READ_PROJECT, project.getProjectId())); + break; + case DEFAULT_WRITE_PROJECT: + grantUserPrivilege(user, PrivilegeType.WRITE_PROJECT, "*"); + projectDao.getAll() + .forEach(project -> grantUserPrivilege(user, PrivilegeType.WRITE_PROJECT, project.getProjectId())); + break; + default: + throw new IllegalArgumentException("The configuration element type '+" + type + "' is not handled."); } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/package-info.java b/service/src/main/java/lcsb/mapviewer/services/impl/package-info.java index 8579684cb4..4e24366aa9 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/package-info.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/package-info.java @@ -3,4 +3,3 @@ * layer. */ package lcsb.mapviewer.services.impl; - diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java index 4aaea5fcfc..0e97cb5383 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java @@ -1,19 +1,13 @@ package lcsb.mapviewer.services.interfaces; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.util.List; import java.util.Map; import lcsb.mapviewer.commands.CommandExecutionException; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.ColorSchemaType; -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -import lcsb.mapviewer.model.map.layout.Layout; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; @@ -29,6 +23,129 @@ import lcsb.mapviewer.services.utils.EmailSender; */ public interface ILayoutService { + /** + * Removes layout from the system. + * + * @param layout + * layout to remove + * @param homeDir + * directory where the system is deployed + * @throws IOException + * thrown when there are problems with removing layout files + */ + void removeLayout(Layout layout, String homeDir) throws IOException; + + /** + * Updates data about the layout. + * + * @param layout + * layout to update + */ + void updateLayout(Layout layout); + + /** + * Create layout based on the data in the parameter. + * + * @param params + * list of {@link CreateLayoutParams params} necessary to create layout + * @return object that refers to created layout + * @throws IOException + * thrown when there are problems with files + * @throws InvalidColorSchemaException + * if the coloring source is invalid + */ + Layout createLayout(CreateLayoutParams params) throws IOException, InvalidColorSchemaException; + + /** + * Create layout based on the data in the parameter. Layout will contain set of + * images that can be further visualized in goolge maps api. + * + * @param params + * list of {@link CreateLayoutParams params} necessary to create layout + * @return object that refers to created layout + * @throws IOException + * thrown when there are problems with files + * @throws CommandExecutionException + * if the coloring source is invalid + * @throws InvalidColorSchemaException + * if the coloring source is invalid + */ + Layout createLayoutWithImages(CreateLayoutParams params) + throws IOException, CommandExecutionException, InvalidColorSchemaException; + + /** + * Returns a list of pairs {@link Element} - {@link ColorSchema} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout}. + * + * @param model + * model where data is located + * @param layoutId + * identifier of the layout + * @return a list of pairs {@link Element} - {@link ColorSchema} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} + */ + List<Pair<Element, ColorSchema>> getAliasesForLayout(Model model, int layoutId); + + /** + * Returns a list of pairs {@link Reaction} - {@link ColorSchema}} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout}. + * + * @param model + * model where data is located + * @param layoutId + * identifier of the layout + * @return a list of pairs {@link Reaction} - {@link ColorSchema} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} + */ + List<Pair<Reaction, ColorSchema>> getReactionsForLayout(Model model, int layoutId); + + /** + * Returns mapping between {@link lcsb.mapviewer.model.map.species.Element + * Alias}/ {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction} and + * {@link ColorSchema} used for coloring object in the layout given in the + * parameter. + * + * @param model + * model where data is located + * @param layoutId + * identifier of the layout + * @return a list of pairs {@link Element} - {@link ColorSchema} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} + */ + Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId); + + Pair<Element, ColorSchema> getFullAliasForLayout(Model model, Integer id, int layoutId); + + Pair<Reaction, ColorSchema> getFullReactionForLayout(Model model, Integer id, int layoutId); + + /** + * Returns {@link EmailSender} used by the service. + * + * @return {@link EmailSender} used by the service + */ + EmailSender getEmailSender(); + + /** + * Sets {@link EmailSender} used by the service. + * + * @param emailSender + * {@link EmailSender} used by the service + */ + void setEmailSender(EmailSender emailSender); + + /** + * Returns list of custom layouts. + * + * @param project + * project where the layouts lay on + * @return list of custom layouts + */ + List<Layout> getLayoutsByProject(Project project); + + Layout getLayoutById(int overlayId); + + void setLayoutDao(LayoutDao layoutDao); + /** * Parameters used for creation of the layout. * @@ -94,7 +211,7 @@ public interface ILayoutService { */ private boolean async = false; - private boolean googleLicenseConsent = false; + private boolean googleLicenseConsent = false; /** * Type of the uploaded file. @@ -233,7 +350,7 @@ public interface ILayoutService { * @see #googleLicenseConsent */ public boolean isGoogleLicenseConsent() { - return googleLicenseConsent; + return googleLicenseConsent; } /** @@ -243,8 +360,8 @@ public interface ILayoutService { * @return {@link CreateLayoutParams} object */ public CreateLayoutParams googleLicenseConsent(boolean googleLicenseConsent) { - this.googleLicenseConsent = googleLicenseConsent; - return this; + this.googleLicenseConsent = googleLicenseConsent; + return this; } /** @@ -305,131 +422,4 @@ public interface ILayoutService { } } - /** - * Removes layout from the system. - * - * @param layout - * layout to remove - * @param homeDir - * directory where the system is deployed - * @throws IOException - * thrown when there are problems with removing layout files - */ - void removeLayout(Layout layout, String homeDir) throws IOException; - - /** - * Updates data about the layout. - * - * @param layout - * layout to update - */ - void updateLayout(Layout layout); - - /** - * Create layout based on the data in the parameter. - * - * @param params - * list of {@link CreateLayoutParams params} necessary to create layout - * @return object that refers to created layout - * @throws IOException - * thrown when there are problems with files - * @throws InvalidColorSchemaException - * if the coloring source is invalid - */ - Layout createLayout(CreateLayoutParams params) throws IOException, InvalidColorSchemaException; - - /** - * Create layout based on the data in the parameter. Layout will contain set of - * images that can be further visualized in goolge maps api. - * - * @param params - * list of {@link CreateLayoutParams params} necessary to create layout - * @return object that refers to created layout - * @throws IOException - * thrown when there are problems with files - * @throws CommandExecutionException - * if the coloring source is invalid - * @throws InvalidColorSchemaException - * if the coloring source is invalid - */ - Layout createLayoutWithImages(CreateLayoutParams params) - throws IOException, CommandExecutionException, InvalidColorSchemaException; - - /** - * Returns a list of pairs {@link Element} - {@link ColorSchema} that are visualized in - * a {@link lcsb.mapviewer.model.map.layout.Layout}. - * - * @param model - * model where data is located - * @param layoutId - * identifier of the layout - * @return a list of pairs {@link Element} - {@link ColorSchema} that are visualized in - * a {@link lcsb.mapviewer.model.map.layout.Layout} - */ - List<Pair<Element, ColorSchema>> getAliasesForLayout(Model model, int layoutId) - ; - - /** - * Returns a list of pairs {@link Reaction} - {@link ColorSchema}} that are - * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout}. - * - * @param model - * model where data is located - * @param layoutId - * identifier of the layout - * @return a list of pairs {@link Reaction} - {@link ColorSchema} that are - * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} - */ - List<Pair<Reaction, ColorSchema>> getReactionsForLayout(Model model, int layoutId) - ; - - /** - * Returns mapping between {@link lcsb.mapviewer.model.map.species.Element - * Alias}/ {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction} and - * {@link ColorSchema} used for coloring object in the layout given in the - * parameter. - * - * @param model - * model where data is located - * @param layoutId - * identifier of the layout - * @return a list of pairs {@link Element} - {@link ColorSchema} that are - * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} - */ - Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId); - - Pair<Element, ColorSchema> getFullAliasForLayout(Model model, Integer id, int layoutId) - ; - - Pair<Reaction, ColorSchema> getFullReactionForLayout(Model model, Integer id, int layoutId) - ; - - /** - * Returns {@link EmailSender} used by the service. - * - * @return {@link EmailSender} used by the service - */ - EmailSender getEmailSender(); - - /** - * Sets {@link EmailSender} used by the service. - * - * @param emailSender - * {@link EmailSender} used by the service - */ - void setEmailSender(EmailSender emailSender); - - /** - * Returns list of custom layouts. - * - * @param project - * project where the layouts lay on - * @return list of custom layouts - */ - List<Layout> getLayoutsByProject(Project project); - - Layout getLayoutById(int overlayId); - - void setLayoutDao(LayoutDao layoutDao); - } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IMiriamService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IMiriamService.java index b0fca3a3e3..0226315db0 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IMiriamService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IMiriamService.java @@ -11,22 +11,22 @@ import lcsb.mapviewer.model.map.MiriamType; */ public interface IMiriamService { - /** - * Returns url for data represented by {@link MiriamData}. - * - * @param md - * object to which link will be returned - * @return url to miriam data - */ - String getUrlForMiriamData(MiriamData md); + /** + * Returns url for data represented by {@link MiriamData}. + * + * @param md + * object to which link will be returned + * @return url to miriam data + */ + String getUrlForMiriamData(MiriamData md); - /** - * Returns {@link MiriamType} associated with parameter uri address. - * - * @param uri - * uri to check - * @return {@link MiriamType} for given uri - */ - MiriamType getTypeForUri(String uri); + /** + * Returns {@link MiriamType} associated with parameter uri address. + * + * @param uri + * uri to check + * @return {@link MiriamType} for given uri + */ + MiriamType getTypeForUri(String uri); } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java index 8fa4c19294..645259bc3d 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java @@ -6,9 +6,7 @@ import java.util.List; import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnectorException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; /** * Service used to maintain reference genome data. diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchHistoryService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchHistoryService.java index 2770c7a866..1293790e22 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchHistoryService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchHistoryService.java @@ -9,17 +9,17 @@ import lcsb.mapviewer.model.map.statistics.SearchType; * */ public interface ISearchHistoryService { - /** - * Adds search query entry into database. - * - * @param query - * what has been searched for - * @param type - * type of the search - * @param ipAddress - * ip address that was searching - * @param projectId - * identifier of the project where search was performed - */ - void addQuery(String query, SearchType type, String ipAddress, String projectId); + /** + * Adds search query entry into database. + * + * @param query + * what has been searched for + * @param type + * type of the search + * @param ipAddress + * ip address that was searching + * @param projectId + * identifier of the project where search was performed + */ + void addQuery(String query, SearchType type, String ipAddress, String projectId); } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java index acc8f8a377..4c9d37fd6f 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java @@ -19,9 +19,11 @@ public interface IUserService { List<User> getUsers(); void grantUserPrivilege(User user, PrivilegeType type); + void grantUserPrivilege(User user, PrivilegeType type, String objectId); void revokeUserPrivilege(User user, PrivilegeType type); + void revokeUserPrivilege(User user, PrivilegeType type, String objectId); void grantDefaultPrivileges(User user); @@ -29,19 +31,26 @@ public interface IUserService { void grantPrivilegeToAllUsersWithDefaultAccess(PrivilegeType type, String objectId); /** - * When an object is deleted we have to manually remove the access rights to it for every user to avoid pollution. - * Hibernate delete cascading does not work here, because security is completely decoupled from the business logic. - * @param privilegeType The concerned privilege domain. - * @param objectId The objectId for which to remove all access rights. + * When an object is deleted we have to manually remove the access rights to it + * for every user to avoid pollution. Hibernate delete cascading does not work + * here, because security is completely decoupled from the business logic. + * + * @param privilegeType + * The concerned privilege domain. + * @param objectId + * The objectId for which to remove all access rights. * */ void revokeObjectDomainPrivilegesForAllUsers(PrivilegeType privilegeType, String objectId); /** - * Returns {@link ColorExtractor} that transform overlay values into colors for given user. + * Returns {@link ColorExtractor} that transform overlay values into colors for + * given user. * - * @param user {@link User} for which {@link ColorExtractor} will be obtained - * @return {@link ColorExtractor} that transform overlay values into colors for given user + * @param user + * {@link User} for which {@link ColorExtractor} will be obtained + * @return {@link ColorExtractor} that transform overlay values into colors for + * given user */ ColorExtractor getColorExtractorForUser(User user); diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/package-info.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/package-info.java index adb9ff9cd6..510e41349e 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/package-info.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/package-info.java @@ -3,4 +3,3 @@ * layer. */ package lcsb.mapviewer.services.interfaces; - diff --git a/service/src/main/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRow.java b/service/src/main/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRow.java index 684fee0850..a64a8b2a28 100644 --- a/service/src/main/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRow.java +++ b/service/src/main/java/lcsb/mapviewer/services/overlay/AnnotatedObjectTreeRow.java @@ -1,12 +1,10 @@ package lcsb.mapviewer.services.overlay; import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.annotation.services.annotators.ElementAnnotator; import lcsb.mapviewer.model.map.MiriamType; @@ -22,277 +20,278 @@ import lcsb.mapviewer.modelutils.map.ClassTreeNode; */ public class AnnotatedObjectTreeRow implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private final transient Logger logger = LogManager.getLogger(AnnotatedObjectTreeRow.class); - - /** - * Name of the class. - */ - private String name; - /** - * Class. - */ - private Class<?> clazz; - - /** - * List of annotators that could be used for annotating {@link #clazz}. - */ - private List<String> validAnnotators = new ArrayList<>(); - - /** - * List of annotators that will be used for annotating {@link #clazz}. - */ - private List<AnnotatorData> usedAnnotators = new ArrayList<>(); - - /** - * Should the type be checked to contain at least one of the - * {@link #requiredAnnotations required miriam}. - */ - private Boolean require = null; - - /** - * List of valid {@link MiriamType} for the class. <br/> - * SizeOf({@link #validAnnotations} + {@link #missingValidAnnotations}) == - * sizeOf( {@link MiriamType#values()}). - */ - private List<MiriamType> validAnnotations = new ArrayList<MiriamType>(); - - /** - * List of {@link MiriamType} that may be moved to {@link #validAnnotations}. - * - * <br/> - * SizeOf({@link #validAnnotations} + {@link #missingValidAnnotations}) == - * sizeOf( {@link MiriamType#values()}). - */ - private List<MiriamType> missingValidAnnotations = new ArrayList<MiriamType>(); - - /** - * List of required {@link MiriamType} for the class. <br/> - * SizeOf({@link #requiredAnnotations} + {@link #missingRequiredAnnotations}) - * == sizeOf( {@link MiriamType#values()}). - */ - private List<MiriamType> requiredAnnotations = new ArrayList<MiriamType>(); - - /** - * List of {@link MiriamType} that may be moved to - * {@link #requiredAnnotations}. - * - * <br/> - * SizeOf({@link #requiredAnnotations} + {@link #missingRequiredAnnotations}) - * == sizeOf( {@link MiriamType#values()}). - */ - private List<MiriamType> missingRequiredAnnotations = new ArrayList<MiriamType>(); - - /** - * Default constructor. - * - * @param node - * information about {@link #clazz} - */ - public AnnotatedObjectTreeRow(ClassTreeNode node) { - this(node, new ArrayList<ElementAnnotator>(), new ArrayList<ElementAnnotator>(), new HashSet<MiriamType>(), new HashSet<MiriamType>()); - } - - /** - * Default constructor. - * - * @param node - * information about {@link #clazz} - * @param validAnnonators - * set of annotators that are available for {@link #clazz} - * @param usedAnnonators - * set of annotators that should be used by default - * @param validMiriam - * set of {@link MiriamType} that are valid by default - * @param requiredMiriam - * set of {@link MiriamType} that are required by default - */ - public AnnotatedObjectTreeRow(ClassTreeNode node, Collection<ElementAnnotator> validAnnonators, Collection<ElementAnnotator> usedAnnonators, - Collection<MiriamType> validMiriam, Collection<MiriamType> requiredMiriam) { - this.name = node.getCommonName(); - this.clazz = node.getClazz(); - for (ElementAnnotator elementAnnotator : validAnnonators) { - if (usedAnnonators.contains(elementAnnotator)) { - AnnotatorData annotatorData = new AnnotatorData(elementAnnotator.getClass()); - this.usedAnnotators.add(annotatorData); - } else { - this.validAnnotators.add(elementAnnotator.getCommonName()); - } - } - for (MiriamType mt : MiriamType.values()) { - if (validMiriam != null && validMiriam.contains(mt)) { - validAnnotations.add(mt); - } else { - missingValidAnnotations.add(mt); - } - - if (requiredMiriam != null && requiredMiriam.contains(mt)) { - requiredAnnotations.add(mt); - } else { - missingRequiredAnnotations.add(mt); - } - } - this.require = (Boolean) node.getData(); - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the clazz - * @see #clazz - */ - public Class<?> getClazz() { - return clazz; - } - - /** - * @param clazz - * the clazz to set - * @see #clazz - */ - public void setClazz(Class<?> clazz) { - this.clazz = clazz; - } - - /** - * @return the validAnnotators - * @see #validAnnotators - */ - public List<String> getValidAnnotators() { - return validAnnotators; - } - - /** - * @param validAnnotators - * the validAnnotators to set - * @see #validAnnotators - */ - public void setValidAnnotators(List<String> validAnnotators) { - this.validAnnotators = validAnnotators; - } - - /** - * @return the usedAnnotators - * @see #usedAnnotators - */ - public List<AnnotatorData> getUsedAnnotators() { - return usedAnnotators; - } - - /** - * @param usedAnnotators - * the usedAnnotators to set - * @see #usedAnnotators - */ - public void setUsedAnnotators(List<AnnotatorData> usedAnnotators) { - this.usedAnnotators = usedAnnotators; - } - - /** - * @return the validAnnotations - * @see #validAnnotations - */ - public List<MiriamType> getValidAnnotations() { - return validAnnotations; - } - - /** - * @param validAnnotations - * the validAnnotations to set - * @see #validAnnotations - */ - public void setValidAnnotations(List<MiriamType> validAnnotations) { - this.validAnnotations = validAnnotations; - } - - /** - * @return the require - * @see #require - */ - public Boolean getRequire() { - return require; - } - - /** - * @param require - * the require to set - * @see #require - */ - public void setRequire(Boolean require) { - this.require = require; - } - - /** - * @return the missingRequiredAnnotations - * @see #missingRequiredAnnotations - */ - public List<MiriamType> getMissingRequiredAnnotations() { - return missingRequiredAnnotations; - } - - /** - * @param missingRequiredAnnotations - * the missingRequiredAnnotations to set - * @see #missingRequiredAnnotations - */ - public void setMissingRequiredAnnotations(List<MiriamType> missingRequiredAnnotations) { - this.missingRequiredAnnotations = missingRequiredAnnotations; - } - - /** - * @return the requiredAnnotations - * @see #requiredAnnotations - */ - public List<MiriamType> getRequiredAnnotations() { - return requiredAnnotations; - } - - /** - * @param requiredAnnotations - * the requiredAnnotations to set - * @see #requiredAnnotations - */ - public void setRequiredAnnotations(List<MiriamType> requiredAnnotations) { - this.requiredAnnotations = requiredAnnotations; - } - - /** - * @return the missingValidAnnotations - * @see #missingValidAnnotations - */ - public List<MiriamType> getMissingValidAnnotations() { - return missingValidAnnotations; - } - - /** - * @param missingValidAnnotations - * the missingValidAnnotations to set - * @see #missingValidAnnotations - */ - public void setMissingValidAnnotations(List<MiriamType> missingValidAnnotations) { - this.missingValidAnnotations = missingValidAnnotations; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private final transient Logger logger = LogManager.getLogger(AnnotatedObjectTreeRow.class); + + /** + * Name of the class. + */ + private String name; + /** + * Class. + */ + private Class<?> clazz; + + /** + * List of annotators that could be used for annotating {@link #clazz}. + */ + private List<String> validAnnotators = new ArrayList<>(); + + /** + * List of annotators that will be used for annotating {@link #clazz}. + */ + private List<AnnotatorData> usedAnnotators = new ArrayList<>(); + + /** + * Should the type be checked to contain at least one of the + * {@link #requiredAnnotations required miriam}. + */ + private Boolean require = null; + + /** + * List of valid {@link MiriamType} for the class. <br/> + * SizeOf({@link #validAnnotations} + {@link #missingValidAnnotations}) == + * sizeOf( {@link MiriamType#values()}). + */ + private List<MiriamType> validAnnotations = new ArrayList<MiriamType>(); + + /** + * List of {@link MiriamType} that may be moved to {@link #validAnnotations}. + * + * <br/> + * SizeOf({@link #validAnnotations} + {@link #missingValidAnnotations}) == + * sizeOf( {@link MiriamType#values()}). + */ + private List<MiriamType> missingValidAnnotations = new ArrayList<MiriamType>(); + + /** + * List of required {@link MiriamType} for the class. <br/> + * SizeOf({@link #requiredAnnotations} + {@link #missingRequiredAnnotations}) == + * sizeOf( {@link MiriamType#values()}). + */ + private List<MiriamType> requiredAnnotations = new ArrayList<MiriamType>(); + + /** + * List of {@link MiriamType} that may be moved to {@link #requiredAnnotations}. + * + * <br/> + * SizeOf({@link #requiredAnnotations} + {@link #missingRequiredAnnotations}) == + * sizeOf( {@link MiriamType#values()}). + */ + private List<MiriamType> missingRequiredAnnotations = new ArrayList<MiriamType>(); + + /** + * Default constructor. + * + * @param node + * information about {@link #clazz} + */ + public AnnotatedObjectTreeRow(ClassTreeNode node) { + this(node, new ArrayList<ElementAnnotator>(), new ArrayList<ElementAnnotator>(), new HashSet<MiriamType>(), + new HashSet<MiriamType>()); + } + + /** + * Default constructor. + * + * @param node + * information about {@link #clazz} + * @param validAnnonators + * set of annotators that are available for {@link #clazz} + * @param usedAnnonators + * set of annotators that should be used by default + * @param validMiriam + * set of {@link MiriamType} that are valid by default + * @param requiredMiriam + * set of {@link MiriamType} that are required by default + */ + public AnnotatedObjectTreeRow(ClassTreeNode node, Collection<ElementAnnotator> validAnnonators, + Collection<ElementAnnotator> usedAnnonators, + Collection<MiriamType> validMiriam, Collection<MiriamType> requiredMiriam) { + this.name = node.getCommonName(); + this.clazz = node.getClazz(); + for (ElementAnnotator elementAnnotator : validAnnonators) { + if (usedAnnonators.contains(elementAnnotator)) { + AnnotatorData annotatorData = new AnnotatorData(elementAnnotator.getClass()); + this.usedAnnotators.add(annotatorData); + } else { + this.validAnnotators.add(elementAnnotator.getCommonName()); + } + } + for (MiriamType mt : MiriamType.values()) { + if (validMiriam != null && validMiriam.contains(mt)) { + validAnnotations.add(mt); + } else { + missingValidAnnotations.add(mt); + } + + if (requiredMiriam != null && requiredMiriam.contains(mt)) { + requiredAnnotations.add(mt); + } else { + missingRequiredAnnotations.add(mt); + } + } + this.require = (Boolean) node.getData(); + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the clazz + * @see #clazz + */ + public Class<?> getClazz() { + return clazz; + } + + /** + * @param clazz + * the clazz to set + * @see #clazz + */ + public void setClazz(Class<?> clazz) { + this.clazz = clazz; + } + + /** + * @return the validAnnotators + * @see #validAnnotators + */ + public List<String> getValidAnnotators() { + return validAnnotators; + } + + /** + * @param validAnnotators + * the validAnnotators to set + * @see #validAnnotators + */ + public void setValidAnnotators(List<String> validAnnotators) { + this.validAnnotators = validAnnotators; + } + + /** + * @return the usedAnnotators + * @see #usedAnnotators + */ + public List<AnnotatorData> getUsedAnnotators() { + return usedAnnotators; + } + + /** + * @param usedAnnotators + * the usedAnnotators to set + * @see #usedAnnotators + */ + public void setUsedAnnotators(List<AnnotatorData> usedAnnotators) { + this.usedAnnotators = usedAnnotators; + } + + /** + * @return the validAnnotations + * @see #validAnnotations + */ + public List<MiriamType> getValidAnnotations() { + return validAnnotations; + } + + /** + * @param validAnnotations + * the validAnnotations to set + * @see #validAnnotations + */ + public void setValidAnnotations(List<MiriamType> validAnnotations) { + this.validAnnotations = validAnnotations; + } + + /** + * @return the require + * @see #require + */ + public Boolean getRequire() { + return require; + } + + /** + * @param require + * the require to set + * @see #require + */ + public void setRequire(Boolean require) { + this.require = require; + } + + /** + * @return the missingRequiredAnnotations + * @see #missingRequiredAnnotations + */ + public List<MiriamType> getMissingRequiredAnnotations() { + return missingRequiredAnnotations; + } + + /** + * @param missingRequiredAnnotations + * the missingRequiredAnnotations to set + * @see #missingRequiredAnnotations + */ + public void setMissingRequiredAnnotations(List<MiriamType> missingRequiredAnnotations) { + this.missingRequiredAnnotations = missingRequiredAnnotations; + } + + /** + * @return the requiredAnnotations + * @see #requiredAnnotations + */ + public List<MiriamType> getRequiredAnnotations() { + return requiredAnnotations; + } + + /** + * @param requiredAnnotations + * the requiredAnnotations to set + * @see #requiredAnnotations + */ + public void setRequiredAnnotations(List<MiriamType> requiredAnnotations) { + this.requiredAnnotations = requiredAnnotations; + } + + /** + * @return the missingValidAnnotations + * @see #missingValidAnnotations + */ + public List<MiriamType> getMissingValidAnnotations() { + return missingValidAnnotations; + } + + /** + * @param missingValidAnnotations + * the missingValidAnnotations to set + * @see #missingValidAnnotations + */ + public void setMissingValidAnnotations(List<MiriamType> missingValidAnnotations) { + this.missingValidAnnotations = missingValidAnnotations; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/overlay/package-info.java b/service/src/main/java/lcsb/mapviewer/services/overlay/package-info.java index e11e591303..eea494a6f6 100644 --- a/service/src/main/java/lcsb/mapviewer/services/overlay/package-info.java +++ b/service/src/main/java/lcsb/mapviewer/services/overlay/package-info.java @@ -4,4 +4,3 @@ * */ package lcsb.mapviewer.services.overlay; - diff --git a/service/src/main/java/lcsb/mapviewer/services/search/DbSearchService.java b/service/src/main/java/lcsb/mapviewer/services/search/DbSearchService.java index bf41828482..b0e73954d8 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/DbSearchService.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/DbSearchService.java @@ -17,31 +17,31 @@ import lcsb.mapviewer.model.map.MiriamType; @Transactional public abstract class DbSearchService { - /** - * Service accessing - * <a href="http://europepmc.org/RestfulWebService">pubmed</a>. - */ - @Autowired - private PubmedParser pubmedParser; - - protected void cacheMiriamData(TargettingStructure targettingStructure) throws AnnotatorException { - Set<MiriamData> result = new HashSet<>(); - result.addAll(targettingStructure.getSources()); - for (Target target : targettingStructure.getTargets()) { - result.addAll(target.getGenes()); - result.addAll(target.getReferences()); - - } - - for (MiriamData miriamData : result) { - if (MiriamType.PUBMED.equals(miriamData.getDataType())) { - try { - pubmedParser.getPubmedArticleById(Integer.valueOf(miriamData.getResource())); - } catch (NumberFormatException | PubmedSearchException e) { - throw new AnnotatorException(e); - } - } - } - - } + /** + * Service accessing + * <a href="http://europepmc.org/RestfulWebService">pubmed</a>. + */ + @Autowired + private PubmedParser pubmedParser; + + protected void cacheMiriamData(TargettingStructure targettingStructure) throws AnnotatorException { + Set<MiriamData> result = new HashSet<>(); + result.addAll(targettingStructure.getSources()); + for (Target target : targettingStructure.getTargets()) { + result.addAll(target.getGenes()); + result.addAll(target.getReferences()); + + } + + for (MiriamData miriamData : result) { + if (MiriamType.PUBMED.equals(miriamData.getDataType())) { + try { + pubmedParser.getPubmedArticleById(Integer.valueOf(miriamData.getResource())); + } catch (NumberFormatException | PubmedSearchException e) { + throw new AnnotatorException(e); + } + } + } + + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/search/ElementMatcher.java b/service/src/main/java/lcsb/mapviewer/services/search/ElementMatcher.java index 6754f40b15..ceabbcb8e5 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/ElementMatcher.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/ElementMatcher.java @@ -1,22 +1,14 @@ package lcsb.mapviewer.services.search; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.annotation.data.Target; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Element; -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.model.map.*; +import lcsb.mapviewer.model.map.species.*; public class ElementMatcher { diff --git a/service/src/main/java/lcsb/mapviewer/services/search/IDbSearchService.java b/service/src/main/java/lcsb/mapviewer/services/search/IDbSearchService.java index ff5f7e3562..31ad2b47e3 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/IDbSearchService.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/IDbSearchService.java @@ -18,39 +18,39 @@ import lcsb.mapviewer.model.map.species.Element; */ public interface IDbSearchService<T> { - /** - * Returns the drugs found by drug name. - * - * @param name - * name of the drug - * @param searchCriteria - * set of {@link DbSearchCriteria} used for searching (like: - * {@link lcsb.mapviewer.model.map.model.Model Model}) - * @return list of drugs for drug names - */ - T getByName(String name, DbSearchCriteria searchCriteria); + /** + * Returns the drugs found by drug name. + * + * @param name + * name of the drug + * @param searchCriteria + * set of {@link DbSearchCriteria} used for searching (like: + * {@link lcsb.mapviewer.model.map.model.Model Model}) + * @return list of drugs for drug names + */ + T getByName(String name, DbSearchCriteria searchCriteria); - /** - * Returns the list of drugs that target at least one of the element in the - * parameter. - * - * @param targetElements - * list of elements that should be targeted by drug - * @param searchCriteria - * set of {@link DbSearchCriteria} used for searching (like: - * {@link lcsb.mapviewer.model.map.model.Model Model}) - * @return list of drugs that targets something from the elements collection - */ - List<T> getForTargets(Collection<Element> targetElements, DbSearchCriteria searchCriteria); + /** + * Returns the list of drugs that target at least one of the element in the + * parameter. + * + * @param targetElements + * list of elements that should be targeted by drug + * @param searchCriteria + * set of {@link DbSearchCriteria} used for searching (like: + * {@link lcsb.mapviewer.model.map.model.Model Model}) + * @return list of drugs that targets something from the elements collection + */ + List<T> getForTargets(Collection<Element> targetElements, DbSearchCriteria searchCriteria); - /** - * This method will cache all queries that make sense for the model. - * - * @param originalModel - * model to be considered for database queries - * @param progressUpdater - * callback function updating information about cache progress - */ - void cacheDataForModel(Model originalModel, IProgressUpdater progressUpdater); + /** + * This method will cache all queries that make sense for the model. + * + * @param originalModel + * model to be considered for database queries + * @param progressUpdater + * callback function updating information about cache progress + */ + void cacheDataForModel(Model originalModel, IProgressUpdater progressUpdater); } diff --git a/service/src/main/java/lcsb/mapviewer/services/search/chemical/ChemicalService.java b/service/src/main/java/lcsb/mapviewer/services/search/chemical/ChemicalService.java index 89c40a2b70..47e2e5e881 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/chemical/ChemicalService.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/chemical/ChemicalService.java @@ -1,18 +1,10 @@ package lcsb.mapviewer.services.search.chemical; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Set; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -24,14 +16,9 @@ import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; import lcsb.mapviewer.common.IProgressUpdater; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.Element; -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.*; import lcsb.mapviewer.services.search.DbSearchCriteria; import lcsb.mapviewer.services.search.DbSearchService; @@ -234,22 +221,6 @@ public class ChemicalService extends DbSearchService implements IChemicalService return chemicalList; } - /** - * @param disease - * {@link MiriamType#MESH_2012 mesh term} describing disease - * - * @return chemicals related to the disease - * @see #diseases - * @throws ChemicalSearchException - * thrown when there is problem with accessing ctd database - */ - private Map<MiriamData, String> getChemicalsByDisease(MiriamData disease) throws ChemicalSearchException { - if (diseases.get(disease) == null) { - diseases.put(disease, chemicalParser.getChemicalsForDisease(disease)); - } - return diseases.get(disease); - } - @Override public void cacheDataForModel(Model originalModel, IProgressUpdater iProgressUpdater) { double progress = 0.0; @@ -291,4 +262,20 @@ public class ChemicalService extends DbSearchService implements IChemicalService } } + /** + * @param disease + * {@link MiriamType#MESH_2012 mesh term} describing disease + * + * @return chemicals related to the disease + * @see #diseases + * @throws ChemicalSearchException + * thrown when there is problem with accessing ctd database + */ + private Map<MiriamData, String> getChemicalsByDisease(MiriamData disease) throws ChemicalSearchException { + if (diseases.get(disease) == null) { + diseases.put(disease, chemicalParser.getChemicalsForDisease(disease)); + } + return diseases.get(disease); + } + } diff --git a/service/src/main/java/lcsb/mapviewer/services/search/drug/DrugService.java b/service/src/main/java/lcsb/mapviewer/services/search/drug/DrugService.java index 2f7d3146cd..9ea2461a03 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/drug/DrugService.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/drug/DrugService.java @@ -1,34 +1,23 @@ package lcsb.mapviewer.services.search.drug; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.Drug; import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.services.ChEMBLParser; -import lcsb.mapviewer.annotation.services.DrugSearchException; -import lcsb.mapviewer.annotation.services.DrugbankHTMLParser; +import lcsb.mapviewer.annotation.services.*; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; import lcsb.mapviewer.common.IProgressUpdater; import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.Element; -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.*; import lcsb.mapviewer.model.map.statistics.SearchType; import lcsb.mapviewer.services.interfaces.ISearchHistoryService; import lcsb.mapviewer.services.search.DbSearchCriteria; @@ -72,9 +61,9 @@ public class DrugService extends DbSearchService implements IDrugService { @Autowired public DrugService(DrugbankHTMLParser drugBankParser, - ChEMBLParser chEMBLParser, - HgncAnnotator hgncAnnotator, - ISearchHistoryService searchHistoryService) { + ChEMBLParser chEMBLParser, + HgncAnnotator hgncAnnotator, + ISearchHistoryService searchHistoryService) { this.drugBankParser = drugBankParser; this.chEMBLParser = chEMBLParser; this.hgncAnnotator = hgncAnnotator; @@ -275,51 +264,6 @@ public class DrugService extends DbSearchService implements IDrugService { return drugList; } - /** - * @return the drugBankParser - */ - public DrugbankHTMLParser getDrugBankParser() { - return drugBankParser; - } - - /** - * @param drugBankParser - * the drugBankParser to set - */ - public void setDrugBankParser(DrugbankHTMLParser drugBankParser) { - this.drugBankParser = drugBankParser; - } - - /** - * @return the chEMBLParser - */ - public ChEMBLParser getChEMBLParser() { - return chEMBLParser; - } - - /** - * @param chEMBLParser - * the chEMBLParser to set - */ - public void setChEMBLParser(ChEMBLParser chEMBLParser) { - this.chEMBLParser = chEMBLParser; - } - - /** - * @return the searchHistoryService - */ - public ISearchHistoryService getSearchHistoryService() { - return searchHistoryService; - } - - /** - * @param searchHistoryService - * the searchHistoryService to set - */ - public void setSearchHistoryService(ISearchHistoryService searchHistoryService) { - this.searchHistoryService = searchHistoryService; - } - @Override public void cacheDataForModel(Model originalModel, IProgressUpdater iProgressUpdater) { logger.debug("Caching drug queries..."); @@ -366,6 +310,51 @@ public class DrugService extends DbSearchService implements IDrugService { } } + /** + * @return the drugBankParser + */ + public DrugbankHTMLParser getDrugBankParser() { + return drugBankParser; + } + + /** + * @param drugBankParser + * the drugBankParser to set + */ + public void setDrugBankParser(DrugbankHTMLParser drugBankParser) { + this.drugBankParser = drugBankParser; + } + + /** + * @return the chEMBLParser + */ + public ChEMBLParser getChEMBLParser() { + return chEMBLParser; + } + + /** + * @param chEMBLParser + * the chEMBLParser to set + */ + public void setChEMBLParser(ChEMBLParser chEMBLParser) { + this.chEMBLParser = chEMBLParser; + } + + /** + * @return the searchHistoryService + */ + public ISearchHistoryService getSearchHistoryService() { + return searchHistoryService; + } + + /** + * @param searchHistoryService + * the searchHistoryService to set + */ + public void setSearchHistoryService(ISearchHistoryService searchHistoryService) { + this.searchHistoryService = searchHistoryService; + } + @Override public List<String> getSuggestedQueryList(Project project, MiriamData organism) throws DrugSearchException { Set<String> resultSet = new HashSet<>(); diff --git a/service/src/main/java/lcsb/mapviewer/services/search/mirna/MiRNAService.java b/service/src/main/java/lcsb/mapviewer/services/search/mirna/MiRNAService.java index 23fcc7bcc0..d01d469cb6 100644 --- a/service/src/main/java/lcsb/mapviewer/services/search/mirna/MiRNAService.java +++ b/service/src/main/java/lcsb/mapviewer/services/search/mirna/MiRNAService.java @@ -1,11 +1,6 @@ package lcsb.mapviewer.services.search.mirna; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -19,14 +14,9 @@ import lcsb.mapviewer.annotation.services.MiRNASearchException; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.HgncAnnotator; import lcsb.mapviewer.common.IProgressUpdater; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.map.*; import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.Element; -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.*; import lcsb.mapviewer.services.search.DbSearchCriteria; import lcsb.mapviewer.services.search.DbSearchService; @@ -127,36 +117,6 @@ public class MiRNAService extends DbSearchService implements IMiRNAService { return mirnaList; } - /** - * Removes targets for unknown organisms from the mirna. - * - * @param mirna - * mirna from which we want to remove targets - * @param organisms - * organisms that should be kept - */ - private void removeUnknownOrganisms(MiRNA mirna, List<MiriamData> organisms) { - if (organisms.size() > 0) { - List<Target> toRemove = new ArrayList<Target>(); - for (Target target : mirna.getTargets()) { - boolean remove = true; - for (MiriamData organism : organisms) { - if (target.getOrganism() == null) { - remove = false; - } else if (target.getOrganism().equals(organism)) { - remove = false; - } - } - if (remove) { - logger.debug("Target " + target.getName() + " removed from list because results are limited to organisms: " - + organisms); - toRemove.add(target); - } - } - mirna.getTargets().removeAll(toRemove); - } - } - @Override public void cacheDataForModel(Model originalModel, IProgressUpdater iProgressUpdater) { logger.debug("Caching mirna queries..."); @@ -200,4 +160,34 @@ public class MiRNAService extends DbSearchService implements IMiRNAService { } } + /** + * Removes targets for unknown organisms from the mirna. + * + * @param mirna + * mirna from which we want to remove targets + * @param organisms + * organisms that should be kept + */ + private void removeUnknownOrganisms(MiRNA mirna, List<MiriamData> organisms) { + if (organisms.size() > 0) { + List<Target> toRemove = new ArrayList<Target>(); + for (Target target : mirna.getTargets()) { + boolean remove = true; + for (MiriamData organism : organisms) { + if (target.getOrganism() == null) { + remove = false; + } else if (target.getOrganism().equals(organism)) { + remove = false; + } + } + if (remove) { + logger.debug("Target " + target.getName() + " removed from list because results are limited to organisms: " + + organisms); + toRemove.add(target); + } + } + mirna.getTargets().removeAll(toRemove); + } + } + } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java b/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java index a22f84b61d..72200ad594 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java @@ -1,28 +1,17 @@ package lcsb.mapviewer.services.utils; -import java.awt.Color; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; +import java.awt.*; +import java.io.*; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; +import java.util.*; import java.util.List; -import java.util.Map; -import java.util.Set; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.annotation.services.MiriamConnector; -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.TextFileUtils; +import lcsb.mapviewer.common.*; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.common.geometry.ColorParser; @@ -30,13 +19,7 @@ import lcsb.mapviewer.converter.model.celldesigner.species.SpeciesMapping; import lcsb.mapviewer.converter.zip.ZipEntryFileFactory; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.ColorSchemaType; -import lcsb.mapviewer.model.map.layout.GeneVariation; -import lcsb.mapviewer.model.map.layout.GeneVariationColorSchema; -import lcsb.mapviewer.model.map.layout.GenericColorSchema; -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.services.utils.data.ColorSchemaColumn; diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java b/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java index ff71b1b57e..fd1be2766a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java @@ -1,16 +1,8 @@ package lcsb.mapviewer.services.utils; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; +import java.util.*; -import lcsb.mapviewer.model.user.User; import org.primefaces.model.TreeNode; import lcsb.mapviewer.converter.Converter; @@ -19,6 +11,7 @@ import lcsb.mapviewer.model.cache.UploadedFileEntry; import lcsb.mapviewer.model.graphics.MapCanvasType; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamType; +import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.model.user.annotator.AnnotatorData; import lcsb.mapviewer.services.overlay.AnnotatedObjectTreeRow; @@ -457,7 +450,8 @@ public class CreateProjectParams { while (!queue.isEmpty()) { TreeNode node = queue.poll(); - map.put(((AnnotatedObjectTreeRow) node.getData()).getClazz(), ((AnnotatedObjectTreeRow) node.getData()).getUsedAnnotators()); + map.put(((AnnotatedObjectTreeRow) node.getData()).getClazz(), + ((AnnotatedObjectTreeRow) node.getData()).getUsedAnnotators()); for (TreeNode node2 : node.getChildren()) { queue.add(node2); @@ -653,15 +647,15 @@ public class CreateProjectParams { return this; } + public User getUser() { + return user; + } + public CreateProjectParams setUser(User user) { this.user = user; return this; } - public User getUser() { - return user; - } - public CreateProjectParams semanticZoomContainsMultipleLayouts(boolean semanticZoomContainsMultipleLayouts) { this.semanticZoomContainsMultipleLayouts = semanticZoomContainsMultipleLayouts; return this; diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/EmailSender.java b/service/src/main/java/lcsb/mapviewer/services/utils/EmailSender.java index 8d0b6f9d76..d23ee6dbbd 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/EmailSender.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/EmailSender.java @@ -1,30 +1,16 @@ package lcsb.mapviewer.services.utils; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Properties; +import java.io.*; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Session; -import javax.mail.Store; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; - -import org.apache.logging.log4j.*; +import javax.activation.*; +import javax.mail.*; +import javax.mail.internet.*; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import com.sun.mail.smtp.SMTPTransport; @@ -40,7 +26,7 @@ import lcsb.mapviewer.services.interfaces.IConfigurationService; * */ public class EmailSender { - + /** * Max size of the content that is allowed as plain text. For emails with longer * content the content will be compressed and added as an attachment file. @@ -171,9 +157,9 @@ public class EmailSender { Properties props = System.getProperties(); props.setProperty("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.port", smtpPort); -// props.setProperty("mail.smtp.user", login); -// props.setProperty("mail.smtp.password", password); -// props.setProperty("mail.smtp.auth", "true"); + // props.setProperty("mail.smtp.user", login); + // props.setProperty("mail.smtp.password", password); + // props.setProperty("mail.smtp.auth", "true"); props.put("mail.smtps.quitwait", "false"); diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/InvalidPrivilegeException.java b/service/src/main/java/lcsb/mapviewer/services/utils/InvalidPrivilegeException.java index 6a8506ada0..e4cff15a5f 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/InvalidPrivilegeException.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/InvalidPrivilegeException.java @@ -7,18 +7,18 @@ package lcsb.mapviewer.services.utils; * */ public class InvalidPrivilegeException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Public constructor with message that should be reported. - * - * @param string - * message - */ - public InvalidPrivilegeException(String string) { - super(string); - } + /** + * Public constructor with message that should be reported. + * + * @param string + * message + */ + public InvalidPrivilegeException(String string) { + super(string); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/ReferenceGenomeExistsException.java b/service/src/main/java/lcsb/mapviewer/services/utils/ReferenceGenomeExistsException.java index fe163d7dea..b19b6fdf2c 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/ReferenceGenomeExistsException.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/ReferenceGenomeExistsException.java @@ -9,18 +9,18 @@ import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnectorExcepti * */ public class ReferenceGenomeExistsException extends ReferenceGenomeConnectorException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Public constructor with message that should be reported. - * - * @param string - * message - */ - public ReferenceGenomeExistsException(String string) { - super(string); - } + /** + * Public constructor with message that should be reported. + * + * @param string + * message + */ + public ReferenceGenomeExistsException(String string) { + super(string); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/SearchIndexer.java b/service/src/main/java/lcsb/mapviewer/services/utils/SearchIndexer.java index b3224f71f4..832b390e4d 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/SearchIndexer.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/SearchIndexer.java @@ -1,12 +1,10 @@ package lcsb.mapviewer.services.utils; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.model.map.SearchIndex; import lcsb.mapviewer.model.map.species.Element; @@ -20,159 +18,159 @@ import lcsb.mapviewer.model.map.species.Element; */ public class SearchIndexer { - /** - * Base score of the index generated for alias id. It will be used as a shift - * for {@link SearchIndex#weight} value. - */ - private static final int SEARCH_SCORE_LEVEL_FOR_ALIAS_ID = 60; - - /** - * Base score of the index generated for {@link Element#formerSymbols}. It will - * be used as a shift for {@link SearchIndex#weight} value. - */ - private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_FORMER_SYMBOL = 75; - - /** - * Base score of the index generated for full name. It will be used as a shift - * for {@link SearchIndex#weight} value. - */ - private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_FULL_NAME = 80; - - /** - * Base score of the index generated for synonims. It will be used as a shift - * for {@link SearchIndex#weight} value. - */ - private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_SYNONIM = 90; - - /** - * Base score of the index generated for name. It will be used as a shift for - * {@link SearchIndex#weight} value. - */ - private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_NAME = 100; - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(SearchIndexer.class); - - /** - * This method create list of indexes for an alias. Right now every index is - * one of the following indexed strings (from most important to less - * important): <br/> - * <ul> - * <li>species name,</li> - * <li>synonyms (only for proteins annotated by vencata server),</li> - * <li>common names (only for proteins annotated by vencata server),</li> - * <li>former symbols,</li> - * <li>speciesID,</li> - * <li>aliasID,</li> - * </ul> - * - * @param species - * object to be indexed - * @return list of indexes for an alias - */ - public List<SearchIndex> createIndexForAlias(Element species) { - List<SearchIndex> result = new ArrayList<>(); - String id1 = species.getElementId(); - result.add(new SearchIndex(getIndexStringForString(id1), SEARCH_SCORE_LEVEL_FOR_ALIAS_ID)); - String id3 = species.getName(); - - result.add(new SearchIndex(getIndexStringForString(id3), SEARCH_SCORE_LEVEL_FOR_SPECIES_NAME)); - - for (String string : species.getSynonyms()) { - result.add(new SearchIndex(getIndexStringForString(string), SEARCH_SCORE_LEVEL_FOR_SPECIES_SYNONIM)); - } - for (String string : species.getFormerSymbols()) { - result.add(new SearchIndex(getIndexStringForString(string), SEARCH_SCORE_LEVEL_FOR_SPECIES_FORMER_SYMBOL)); - } - String name = species.getFullName(); - if (name != null && !name.equals("")) { - result.add(new SearchIndex(getIndexStringForString(name), SEARCH_SCORE_LEVEL_FOR_SPECIES_FULL_NAME)); - } - return result; - } - - /** - * This method transform a string into indexed string version. Right now the - * indexed version is a lowercase string which contains only alphanumerical - * characters. - * - * @param str - * string for conversion - * @return indexed version of the input string - */ - private String getIndexStringForString(String str) { - return str.toLowerCase().replaceAll("[^a-z0-9]", ""); - } - - /** - * This method transform a string into indexed query. AvailablePrefixes - * contains a collection of all possible prefixes for query string that should - * be ommitted. - * - * @param originalQuery - * query to be transformed - * @param availablePrefixes - * collection of valid prefixes in the query - * - * @return indexed string of the qoriginal query - */ - public String getQueryStringForIndex(String originalQuery, Collection<String> availablePrefixes) { - String result = originalQuery; - for (String string : availablePrefixes) { - if (result.startsWith(string + ":")) { - result = result.replaceFirst(string + ":", ""); - break; - } - } - - return getIndexStringForString(result); - } - - /** - * This method check if query match search index and return probability of the - * hit between <0,1> (0 - means query is not similar to index, 1 means perfect - * match) increased by the index weight if probability is higher than 0. - * - * @param query - * query to be checked (it should be already prepared in the same way - * as index is) - * @param index - * search index value to be checked - * @return probabily value (range <0,1>) of match between query and index - * increased by the index weight - */ - public double match(String query, SearchIndex index) { - double partialValue = 0; - if (index.getValue().contains(query)) { - partialValue = ((double) query.length()) / ((double) index.getValue().length()); - } - if (partialValue > 0) { - return index.getWeight() + partialValue; - } else { - return 0; - } - } - - /** - * Return type of elements that can be returned for the query. - * - * @param string - * query string. - * @param speciesSearchReversePrefix - * map containing information about possible prefixes used in the - * query - * @return class of the element that might exist in the result - */ - public Class<? extends Element> getTypeForQuery(String string, Map<String, Class<? extends Element>> speciesSearchReversePrefix) { - String result = string; - for (Entry<String, Class<? extends Element>> entry : speciesSearchReversePrefix.entrySet()) { - if (result.startsWith(entry.getKey() + ":")) { - return entry.getValue(); - } - } - return Element.class; - } + /** + * Base score of the index generated for alias id. It will be used as a shift + * for {@link SearchIndex#weight} value. + */ + private static final int SEARCH_SCORE_LEVEL_FOR_ALIAS_ID = 60; + + /** + * Base score of the index generated for {@link Element#formerSymbols}. It will + * be used as a shift for {@link SearchIndex#weight} value. + */ + private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_FORMER_SYMBOL = 75; + + /** + * Base score of the index generated for full name. It will be used as a shift + * for {@link SearchIndex#weight} value. + */ + private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_FULL_NAME = 80; + + /** + * Base score of the index generated for synonims. It will be used as a shift + * for {@link SearchIndex#weight} value. + */ + private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_SYNONIM = 90; + + /** + * Base score of the index generated for name. It will be used as a shift for + * {@link SearchIndex#weight} value. + */ + private static final int SEARCH_SCORE_LEVEL_FOR_SPECIES_NAME = 100; + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(SearchIndexer.class); + + /** + * This method create list of indexes for an alias. Right now every index is one + * of the following indexed strings (from most important to less important): + * <br/> + * <ul> + * <li>species name,</li> + * <li>synonyms (only for proteins annotated by vencata server),</li> + * <li>common names (only for proteins annotated by vencata server),</li> + * <li>former symbols,</li> + * <li>speciesID,</li> + * <li>aliasID,</li> + * </ul> + * + * @param species + * object to be indexed + * @return list of indexes for an alias + */ + public List<SearchIndex> createIndexForAlias(Element species) { + List<SearchIndex> result = new ArrayList<>(); + String id1 = species.getElementId(); + result.add(new SearchIndex(getIndexStringForString(id1), SEARCH_SCORE_LEVEL_FOR_ALIAS_ID)); + String id3 = species.getName(); + + result.add(new SearchIndex(getIndexStringForString(id3), SEARCH_SCORE_LEVEL_FOR_SPECIES_NAME)); + + for (String string : species.getSynonyms()) { + result.add(new SearchIndex(getIndexStringForString(string), SEARCH_SCORE_LEVEL_FOR_SPECIES_SYNONIM)); + } + for (String string : species.getFormerSymbols()) { + result.add(new SearchIndex(getIndexStringForString(string), SEARCH_SCORE_LEVEL_FOR_SPECIES_FORMER_SYMBOL)); + } + String name = species.getFullName(); + if (name != null && !name.equals("")) { + result.add(new SearchIndex(getIndexStringForString(name), SEARCH_SCORE_LEVEL_FOR_SPECIES_FULL_NAME)); + } + return result; + } + + /** + * This method transform a string into indexed string version. Right now the + * indexed version is a lowercase string which contains only alphanumerical + * characters. + * + * @param str + * string for conversion + * @return indexed version of the input string + */ + private String getIndexStringForString(String str) { + return str.toLowerCase().replaceAll("[^a-z0-9]", ""); + } + + /** + * This method transform a string into indexed query. AvailablePrefixes contains + * a collection of all possible prefixes for query string that should be + * ommitted. + * + * @param originalQuery + * query to be transformed + * @param availablePrefixes + * collection of valid prefixes in the query + * + * @return indexed string of the qoriginal query + */ + public String getQueryStringForIndex(String originalQuery, Collection<String> availablePrefixes) { + String result = originalQuery; + for (String string : availablePrefixes) { + if (result.startsWith(string + ":")) { + result = result.replaceFirst(string + ":", ""); + break; + } + } + + return getIndexStringForString(result); + } + + /** + * This method check if query match search index and return probability of the + * hit between <0,1> (0 - means query is not similar to index, 1 means perfect + * match) increased by the index weight if probability is higher than 0. + * + * @param query + * query to be checked (it should be already prepared in the same way + * as index is) + * @param index + * search index value to be checked + * @return probabily value (range <0,1>) of match between query and index + * increased by the index weight + */ + public double match(String query, SearchIndex index) { + double partialValue = 0; + if (index.getValue().contains(query)) { + partialValue = ((double) query.length()) / ((double) index.getValue().length()); + } + if (partialValue > 0) { + return index.getWeight() + partialValue; + } else { + return 0; + } + } + + /** + * Return type of elements that can be returned for the query. + * + * @param string + * query string. + * @param speciesSearchReversePrefix + * map containing information about possible prefixes used in the query + * @return class of the element that might exist in the result + */ + public Class<? extends Element> getTypeForQuery(String string, + Map<String, Class<? extends Element>> speciesSearchReversePrefix) { + String result = string; + for (Entry<String, Class<? extends Element>> entry : speciesSearchReversePrefix.entrySet()) { + if (result.startsWith(entry.getKey() + ":")) { + return entry.getValue(); + } + } + return Element.class; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/data/BuildInLayout.java b/service/src/main/java/lcsb/mapviewer/services/utils/data/BuildInLayout.java index 32dd39567f..60a14f170c 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/data/BuildInLayout.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/data/BuildInLayout.java @@ -8,104 +8,104 @@ package lcsb.mapviewer.services.utils.data; * */ public enum BuildInLayout { - /** - * Normal strainghtforward visualization. - */ - NORMAL("Network", "_normal", null, false), - // /** - // * Set of data containing Substantia Nigra data for Parkinson Disease (false - // * discovery ratio 0.01). - // */ - // FDR_001("PD Substantia Nigra FDR=0.01", "_001", "/enricoData/ge001.txt", - // false), - // /** - // * Set of data containing Substantia Nigra data for Parkinson Disease (false - // * discovery ratio 0.05). - // */ - // FDR_005("PD Substantia Nigra FDR=0.05", "_005", "/enricoData/ge005.txt", - // false), - // /** - // * Set of data containing aging data for Parkinson Disease . - // */ - // AGING("Aging", "_ageing", "/enricoData/ageing.txt", false), - /** - * Standard visualization with hierarchical view. - */ - NESTED("Pathways and compartments", "_nested", null, true), - /** - * Clean visualization (with colors reset to black and white). - */ - CLEAN("Empty", "_empty", null, false); + /** + * Normal strainghtforward visualization. + */ + NORMAL("Network", "_normal", null, false), + // /** + // * Set of data containing Substantia Nigra data for Parkinson Disease (false + // * discovery ratio 0.01). + // */ + // FDR_001("PD Substantia Nigra FDR=0.01", "_001", "/enricoData/ge001.txt", + // false), + // /** + // * Set of data containing Substantia Nigra data for Parkinson Disease (false + // * discovery ratio 0.05). + // */ + // FDR_005("PD Substantia Nigra FDR=0.05", "_005", "/enricoData/ge005.txt", + // false), + // /** + // * Set of data containing aging data for Parkinson Disease . + // */ + // AGING("Aging", "_ageing", "/enricoData/ageing.txt", false), + /** + * Standard visualization with hierarchical view. + */ + NESTED("Pathways and compartments", "_nested", null, true), + /** + * Clean visualization (with colors reset to black and white). + */ + CLEAN("Empty", "_empty", null, false); - /** - * Title of the layout. - */ - private String title; + /** + * Title of the layout. + */ + private String title; - /** - * Suffix used for the directory name during image generation. - */ - private String directorySuffix; + /** + * Suffix used for the directory name during image generation. + */ + private String directorySuffix; - /** - * File with the color values for the layout. - */ - private String coloringFile; + /** + * File with the color values for the layout. + */ + private String coloringFile; - /** - * Should visualization be hierarchical or simple. - */ - private boolean nested; + /** + * Should visualization be hierarchical or simple. + */ + private boolean nested; - /** - * Default constructor with all information needed by layout. - * - * @param title - * Title of the layout - * @param directorySuffix - * Suffix used for the directory name during image generation - * @param coloringFileName - * File with the color values for the layout - * @param nested - * Should visualization be hierarchical or simple - */ - BuildInLayout(String title, String directorySuffix, String coloringFileName, boolean nested) { - this.title = title; - this.directorySuffix = directorySuffix; - this.coloringFile = coloringFileName; - this.nested = nested; - } + /** + * Default constructor with all information needed by layout. + * + * @param title + * Title of the layout + * @param directorySuffix + * Suffix used for the directory name during image generation + * @param coloringFileName + * File with the color values for the layout + * @param nested + * Should visualization be hierarchical or simple + */ + BuildInLayout(String title, String directorySuffix, String coloringFileName, boolean nested) { + this.title = title; + this.directorySuffix = directorySuffix; + this.coloringFile = coloringFileName; + this.nested = nested; + } - /** - * @return the title - * @see #title - */ - public String getTitle() { - return title; - } + /** + * @return the title + * @see #title + */ + public String getTitle() { + return title; + } - /** - * @return the directorySuffix - * @see #directorySuffix - */ - public String getDirectorySuffix() { - return directorySuffix; - } + /** + * @return the directorySuffix + * @see #directorySuffix + */ + public String getDirectorySuffix() { + return directorySuffix; + } - /** - * @return the coloringFile - * @see #coloringFile - */ - public String getColoringFile() { - return coloringFile; - } + /** + * @return the coloringFile + * @see #coloringFile + */ + public String getColoringFile() { + return coloringFile; + } - /** - * @return the nested - * @see #nested - */ - public boolean isNested() { - return nested; - } + /** + * @return the nested + * @see #nested + */ + public boolean isNested() { + return nested; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/data/ColorSchemaColumn.java b/service/src/main/java/lcsb/mapviewer/services/utils/data/ColorSchemaColumn.java index 3d73e12531..f199d482eb 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/data/ColorSchemaColumn.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/data/ColorSchemaColumn.java @@ -3,9 +3,7 @@ package lcsb.mapviewer.services.utils.data; import java.util.HashSet; import java.util.Set; -import lcsb.mapviewer.model.map.layout.ColorSchemaType; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; +import lcsb.mapviewer.model.map.layout.*; /** * This enum defines which columns are available for defining @@ -19,14 +17,14 @@ public enum ColorSchemaColumn { /** * Name of the element. */ - NAME(new ColorSchemaType[] { ColorSchemaType.GENERIC}), + NAME(new ColorSchemaType[] { ColorSchemaType.GENERIC }), GENE_NAME("name", new ColorSchemaType[] { ColorSchemaType.GENETIC_VARIANT }), /** * Name of the map. */ - MAP_NAME("model_name",new ColorSchemaType[] { ColorSchemaType.GENERIC, ColorSchemaType.GENETIC_VARIANT }), + MAP_NAME("model_name", new ColorSchemaType[] { ColorSchemaType.GENERIC, ColorSchemaType.GENETIC_VARIANT }), /** * Value that will be transformed into new color. @@ -43,7 +41,7 @@ public enum ColorSchemaColumn { /** * Class type of the element. */ - TYPE(new ColorSchemaType[] { ColorSchemaType.GENERIC}), + TYPE(new ColorSchemaType[] { ColorSchemaType.GENERIC }), /** * New element/reaction color. @@ -53,7 +51,7 @@ public enum ColorSchemaColumn { /** * Identifier of the element. */ - IDENTIFIER("references",new ColorSchemaType[] { ColorSchemaType.GENERIC, ColorSchemaType.GENETIC_VARIANT }), + IDENTIFIER("references", new ColorSchemaType[] { ColorSchemaType.GENERIC, ColorSchemaType.GENETIC_VARIANT }), /** * Element identifier. @@ -124,14 +122,24 @@ public enum ColorSchemaColumn { */ AMINO_ACID_CHANGE(new ColorSchemaType[] { ColorSchemaType.GENETIC_VARIANT }); + /** + * Human readable title used in input file. + */ + private String deprecatedColumnName; + /** + * Set of types where column is allowed. + */ + private Set<ColorSchemaType> types = new HashSet<>(); + /** * Constructor that creates enum entry with deprecated column name. - * + * * @param deprecatedColumnName * {@link #deprecatedColumnName} * @param types * list of {@link ColorSchemaType types} where this column is allowed - * @deprecated As of release 12.3, replaced by {@link #ColorSchemaColumn(ColorSchemaType[])} + * @deprecated As of release 12.3, replaced by + * {@link #ColorSchemaColumn(ColorSchemaType[])} */ @Deprecated ColorSchemaColumn(String deprecatedColumnName, ColorSchemaType[] types) { @@ -143,7 +151,7 @@ public enum ColorSchemaColumn { /** * Default constructor that creates enum entry. - * + * * @param deprecatedColumnName * {@link #deprecatedColumnName} * @param types @@ -155,16 +163,6 @@ public enum ColorSchemaColumn { } } - /** - * Human readable title used in input file. - */ - private String deprecatedColumnName; - - /** - * Set of types where column is allowed. - */ - private Set<ColorSchemaType> types = new HashSet<>(); - /** * * @return {@link #deprecatedColumnName} diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportColumn.java b/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportColumn.java index a5e48ef710..6fe578558e 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportColumn.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportColumn.java @@ -11,104 +11,103 @@ import lcsb.mapviewer.model.map.species.Species; */ public enum ExportColumn { - /** - * Name of the species. - */ - NAME("Name", Species.class), - - /** - * Name of compartment. - */ - COMPARTMENT_NAME("Compartment", Species.class), - - /** - * Name of compartment. - */ - POSITION_TO_COMPARTMENT("Position to compartment", Species.class), - - /** - * Name of pathway. - */ - COMPONENT_NAME("Pathway", Species.class), - - /** - * Type of the species. - */ - TYPE("Type", Species.class), - - /** - * Identifier. - */ - ID("Id", Object.class), - - /** - * Complex in which element is localized. - */ - COMPLEX("Parent complex", Species.class), - - /** - * Complex in which element is localized. - */ - SUBMODEL("Submodel", Species.class), - - /** - * Reaction identifier. - */ - REACTION_ID("Reaction id", Reaction.class), - - /** - * Reaction type. - */ - REACTION_TYPE("Reaction type", Reaction.class), - - /** - * Information if reaction is reversible. - */ - REACTION_REVERSIBLE("Reversible", Reaction.class), - - /** - * Every reaction is split into two elements interactions. - */ - REACTION_TWO_ELEMENT("Split reaction to two element interaction", Reaction.class); - - /** - * Default constructor that creates enum entry. - * - * @param title - * {@link #title} - * @param clazz - * {@link #clazz} - */ - ExportColumn(String title, Class<?> clazz) { - this.title = title; - this.clazz = clazz; - } - - /** - * Human readable title. - */ - private String title; - - /** - * Class for which this column should be accessible. - */ - private Class<?> clazz; - - /** - * - * @return {@link #title} - */ - public String getTitle() { - return title; - } - - /** - * - * - * @return {@link #clazz} - */ - public Class<?> getClazz() { - return clazz; - } + /** + * Name of the species. + */ + NAME("Name", Species.class), + + /** + * Name of compartment. + */ + COMPARTMENT_NAME("Compartment", Species.class), + + /** + * Name of compartment. + */ + POSITION_TO_COMPARTMENT("Position to compartment", Species.class), + + /** + * Name of pathway. + */ + COMPONENT_NAME("Pathway", Species.class), + + /** + * Type of the species. + */ + TYPE("Type", Species.class), + + /** + * Identifier. + */ + ID("Id", Object.class), + + /** + * Complex in which element is localized. + */ + COMPLEX("Parent complex", Species.class), + + /** + * Complex in which element is localized. + */ + SUBMODEL("Submodel", Species.class), + + /** + * Reaction identifier. + */ + REACTION_ID("Reaction id", Reaction.class), + + /** + * Reaction type. + */ + REACTION_TYPE("Reaction type", Reaction.class), + + /** + * Information if reaction is reversible. + */ + REACTION_REVERSIBLE("Reversible", Reaction.class), + + /** + * Every reaction is split into two elements interactions. + */ + REACTION_TWO_ELEMENT("Split reaction to two element interaction", Reaction.class); + + /** + * Human readable title. + */ + private String title; + /** + * Class for which this column should be accessible. + */ + private Class<?> clazz; + + /** + * Default constructor that creates enum entry. + * + * @param title + * {@link #title} + * @param clazz + * {@link #clazz} + */ + ExportColumn(String title, Class<?> clazz) { + this.title = title; + this.clazz = clazz; + } + + /** + * + * @return {@link #title} + */ + public String getTitle() { + return title; + } + + /** + * + * + * @return {@link #clazz} + */ + public Class<?> getClazz() { + return clazz; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportFileType.java b/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportFileType.java index 1578fe18a2..46b5ef01c2 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportFileType.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/data/ExportFileType.java @@ -7,40 +7,40 @@ package lcsb.mapviewer.services.utils.data; * */ public enum ExportFileType { - - /** - * Tab separated file. - */ - TAB_SEPARATED("Tab separated"), - - /** - * Simnple interaction format used by <a - * href="http://wiki.cytoscape.org/Cytoscape_User_Manual/Network_Formats" - * >Cytoscape</a>. - */ - SIF("SIF"); + /** + * Tab separated file. + */ + TAB_SEPARATED("Tab separated"), - /** - * Default constructor. - * - * @param title - * {@link #title} - */ - ExportFileType(final String title) { - this.title = title; - } + /** + * Simnple interaction format used by + * <a href="http://wiki.cytoscape.org/Cytoscape_User_Manual/Network_Formats" + * >Cytoscape</a>. + */ - /** - * Human readable name of the format. - */ - private String title; + SIF("SIF"); - /** - * - * @return {@link #title} - */ - public String getTitle() { - return title; - } + /** + * Human readable name of the format. + */ + private String title; + + /** + * Default constructor. + * + * @param title + * {@link #title} + */ + ExportFileType(final String title) { + this.title = title; + } + + /** + * + * @return {@link #title} + */ + public String getTitle() { + return title; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/data/package-info.java b/service/src/main/java/lcsb/mapviewer/services/utils/data/package-info.java index 7f4ef6a31e..cf3e217301 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/data/package-info.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/data/package-info.java @@ -3,4 +3,3 @@ * {@link lcsb.mapviewer.services.utils} package. */ package lcsb.mapviewer.services.utils.data; - diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/package-info.java b/service/src/main/java/lcsb/mapviewer/services/utils/package-info.java index 7f289e56f9..07edbd0ffa 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/package-info.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/package-info.java @@ -2,4 +2,3 @@ * This package contains some util classes used in service package. */ package lcsb.mapviewer.services.utils; - diff --git a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java index 0696927d2e..2abcca3597 100644 --- a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java +++ b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java @@ -40,19 +40,14 @@ import lcsb.mapviewer.services.search.drug.IDrugService; @RunWith(SpringJUnit4ClassRunner.class) public abstract class ServiceTestFunctions { + private static Map<String, Model> models = new HashMap<String, Model>(); @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - - private Logger logger = LogManager.getLogger(ServiceTestFunctions.class); - + public double EPSILON = 1e-6; @Autowired protected DrugbankHTMLParser drugBankHTMLParser; - @Autowired protected ModelAnnotator modelAnnotator; - - public double EPSILON = 1e-6; - @Autowired protected IConfigurationService configurationService; @@ -100,7 +95,7 @@ public abstract class ServiceTestFunctions { @Autowired protected DbUtils dbUtils; - + private Logger logger = LogManager.getLogger(ServiceTestFunctions.class); private MinervaLoggerAppender appender; @Before @@ -148,8 +143,6 @@ public abstract class ServiceTestFunctions { return user; } - private static Map<String, Model> models = new HashMap<String, Model>(); - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { if (!fromCache) { logger.debug("File without cache: " + fileName); diff --git a/service/src/test/java/lcsb/mapviewer/services/SpringServiceTestConfig.java b/service/src/test/java/lcsb/mapviewer/services/SpringServiceTestConfig.java index d0d08b0389..5cfc7f9519 100644 --- a/service/src/test/java/lcsb/mapviewer/services/SpringServiceTestConfig.java +++ b/service/src/test/java/lcsb/mapviewer/services/SpringServiceTestConfig.java @@ -1,14 +1,13 @@ package lcsb.mapviewer.services; +import org.springframework.context.annotation.*; +import org.springframework.security.core.session.SessionRegistryImpl; + import lcsb.mapviewer.annotation.SpringAnnotationConfig; import lcsb.mapviewer.persist.SpringPersistConfig; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.core.session.SessionRegistryImpl; @Configuration -@Import({SpringServiceConfig.class, SpringPersistConfig.class, SpringAnnotationConfig.class}) +@Import({ SpringServiceConfig.class, SpringPersistConfig.class, SpringAnnotationConfig.class }) public class SpringServiceTestConfig { @Bean diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java index 427d3ccbf1..9043fd0825 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/CustomMd5PasswordEncoderTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.services.impl; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.junit.*; diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/FailServiceMock.java b/service/src/test/java/lcsb/mapviewer/services/impl/FailServiceMock.java index c7a4866c06..bf15027fdc 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/FailServiceMock.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/FailServiceMock.java @@ -1,16 +1,14 @@ package lcsb.mapviewer.services.impl; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; +import lcsb.mapviewer.annotation.services.*; public class FailServiceMock implements IExternalService { - @Override - public ExternalServiceStatus getServiceStatus() { - ExternalServiceStatus status = new ExternalServiceStatus("Test service", "unknown"); - status.setStatus(ExternalServiceStatusType.DOWN); - return status; - } + @Override + public ExternalServiceStatus getServiceStatus() { + ExternalServiceStatus status = new ExternalServiceStatus("Test service", "unknown"); + status.setStatus(ExternalServiceStatusType.DOWN); + return status; + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java index 731e4ad090..91b413664d 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java @@ -2,10 +2,11 @@ package lcsb.mapviewer.services.impl; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.List; import org.apache.commons.io.IOUtils; import org.apache.logging.log4j.LogManager; @@ -47,10 +48,8 @@ public class LayoutServiceTest extends ServiceTestFunctions { @Autowired ILayoutService layoutService; - - private User user, user2; - ColorExtractor colorExtractor = new ColorExtractor(Color.RED, Color.GREEN, Color.BLUE); + private User user, user2; @Before public void setUp() throws Exception { diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/OkServiceMock.java b/service/src/test/java/lcsb/mapviewer/services/impl/OkServiceMock.java index e26c4c69e1..d7db97d58f 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/OkServiceMock.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/OkServiceMock.java @@ -1,16 +1,14 @@ package lcsb.mapviewer.services.impl; -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.annotation.services.IExternalService; +import lcsb.mapviewer.annotation.services.*; public class OkServiceMock implements IExternalService { - @Override - public ExternalServiceStatus getServiceStatus() { - ExternalServiceStatus status = new ExternalServiceStatus("Test service", "unknown"); - status.setStatus(ExternalServiceStatusType.OK); - return status; - } + @Override + public ExternalServiceStatus getServiceStatus() { + ExternalServiceStatus status = new ExternalServiceStatus("Test service", "unknown"); + status.setStatus(ExternalServiceStatusType.OK); + return status; + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java index 6e87809a64..c35bee8b1a 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java @@ -44,16 +44,14 @@ import lcsb.mapviewer.services.utils.data.BuildInLayout; @Rollback(true) public class ProjectServiceTest extends ServiceTestFunctions { - private Logger logger = LogManager.getLogger(ProjectServiceTest.class); - private ZipEntryFileFactory zefFactory = new ZipEntryFileFactory(); private final String tmpResultDir = "tmp/"; - private String projectId = "Some_id"; - @Autowired ElementDao aliasDao; - @Autowired LayoutDao layoutDao; + private Logger logger = LogManager.getLogger(ProjectServiceTest.class); + private ZipEntryFileFactory zefFactory = new ZipEntryFileFactory(); + private String projectId = "Some_id"; @Before public void setUp() throws Exception { diff --git a/service/src/test/java/lcsb/mapviewer/services/search/DbSearchServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/search/DbSearchServiceTest.java index 018bf80c98..2a839d2f22 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/DbSearchServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/DbSearchServiceTest.java @@ -4,7 +4,6 @@ import org.junit.Test; import org.mockito.Mockito; import lcsb.mapviewer.annotation.data.Chemical; -import lcsb.mapviewer.services.search.DbSearchService; public class DbSearchServiceTest { diff --git a/service/src/test/java/lcsb/mapviewer/services/search/ElementMatcherTest.java b/service/src/test/java/lcsb/mapviewer/services/search/ElementMatcherTest.java index 1b31f49b77..a43c78fd3e 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/ElementMatcherTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/ElementMatcherTest.java @@ -3,20 +3,13 @@ package lcsb.mapviewer.services.search; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; +import lcsb.mapviewer.annotation.data.*; import lcsb.mapviewer.annotation.data.Chemical; -import lcsb.mapviewer.annotation.data.Target; -import lcsb.mapviewer.annotation.data.TargetType; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Rna; +import lcsb.mapviewer.model.map.species.*; import lcsb.mapviewer.services.ServiceTestFunctions; public class ElementMatcherTest extends ServiceTestFunctions { diff --git a/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java index 8a9f7a18f8..1bd6e92b05 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/mirna/MiRNAServiceTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.services.search.mirna; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -19,10 +20,9 @@ import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.search.DbSearchCriteria; public class MiRNAServiceTest extends ServiceTestFunctions { - Logger logger = LogManager.getLogger(MiRNAServiceTest.class); - @Autowired protected IMiRNAService miRNAService; + Logger logger = LogManager.getLogger(MiRNAServiceTest.class); @Before public void setUp() throws Exception { diff --git a/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java b/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java index 55fc71dbc6..4592e44bb3 100644 --- a/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java @@ -2,10 +2,11 @@ package lcsb.mapviewer.services.utils; import static org.junit.Assert.*; -import java.awt.Color; +import java.awt.*; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; +import java.util.List; import org.apache.commons.io.output.ByteArrayOutputStream; import org.apache.logging.log4j.LogManager; diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CORSFilter.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CORSFilter.java index 60f694b6ac..3a0341a4c0 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CORSFilter.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CORSFilter.java @@ -2,16 +2,12 @@ package lcsb.mapviewer.web.bean.utils; import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import lcsb.mapviewer.common.Configuration; diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CacheFilter.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CacheFilter.java index 72733addc6..5baef1dcef 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CacheFilter.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CacheFilter.java @@ -2,15 +2,11 @@ package lcsb.mapviewer.web.bean.utils; import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * This filter disables caching for API queries. @@ -33,7 +29,7 @@ public class CacheFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; - //caching on Safari + // caching on Safari response.addHeader("Vary", "*"); // generic cache prevent mechanism response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomFilter.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomFilter.java index 04d2957a90..7f2a4282a0 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomFilter.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomFilter.java @@ -2,16 +2,12 @@ package lcsb.mapviewer.web.bean.utils; import java.io.IOException; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * This class should be used only for debug purpose. It wrapps @@ -23,29 +19,30 @@ import org.apache.logging.log4j.*; * */ public class CustomFilter implements Filter { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(CustomFilter.class); - - @Override - public void init(FilterConfig config) throws ServletException { - } - - @Override - public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { - HttpServletRequest request = (HttpServletRequest) req; - HttpServletResponse response = (HttpServletResponse) res; - - logger.debug("URI: " + request.getRequestURI()); - logger.debug("URL: " + request.getRequestURL()); - logger.debug("val: " + response.getBufferSize()); - chain.doFilter(req, new CustomHttpServletResponseWrapper(response)); - logger.debug("Content after: " + response.getContentType()); - } - - @Override - public void destroy() { - } + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(CustomFilter.class); + + @Override + public void init(FilterConfig config) throws ServletException { + } + + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) req; + HttpServletResponse response = (HttpServletResponse) res; + + logger.debug("URI: " + request.getRequestURI()); + logger.debug("URL: " + request.getRequestURL()); + logger.debug("val: " + response.getBufferSize()); + chain.doFilter(req, new CustomHttpServletResponseWrapper(response)); + logger.debug("Content after: " + response.getContentType()); + } + + @Override + public void destroy() { + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomHttpServletResponseWrapper.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomHttpServletResponseWrapper.java index f3eef2d300..5cfabaf067 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomHttpServletResponseWrapper.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/CustomHttpServletResponseWrapper.java @@ -5,11 +5,10 @@ import java.io.PrintWriter; import java.util.Locale; import javax.servlet.ServletOutputStream; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; +import javax.servlet.http.*; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * This class should be used only for debugging. It's a wrapper to standard JSF @@ -24,225 +23,225 @@ import org.apache.logging.log4j.*; */ public class CustomHttpServletResponseWrapper extends HttpServletResponseWrapper { - /** - * Default class logger. - */ - private Logger logger = LogManager.getLogger(CustomHttpServletResponseWrapper.class); - - /** - * Default constructor. - * - * @param response - * {@link HttpServletResponse} that should be encapsluated - */ - public CustomHttpServletResponseWrapper(HttpServletResponse response) { - super(response); - logger.debug("Constructor: " + response); - } - - @Override - public PrintWriter getWriter() throws IOException { - logger.debug("getWriter"); - return this.getWriter(); - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - logger.debug("getOutputStream"); - logger.debug(new Exception(), new Exception()); - return this.getOutputStream(); - } - - @Override - public String getCharacterEncoding() { - logger.debug("getCharacterEncoding"); - return this.getCharacterEncoding(); - } - - @Override - public String getContentType() { - logger.debug("getContentType"); - return this.getContentType(); - } - - @Override - public void setCharacterEncoding(String charset) { - logger.debug("setCharacterEncoding"); - this.setCharacterEncoding(charset); - } - - @Override - public void setContentLength(int len) { - logger.debug("setContentLength"); - this.setContentLength(len); - } - - @Override - public void setContentType(String type) { - logger.debug("setContentType: " + type); - logger.debug(new Exception(), new Exception()); - this.setContentType(type); - } - - @Override - public void setBufferSize(int size) { - logger.debug("setBufferSize"); - this.setBufferSize(size); - } - - @Override - public int getBufferSize() { - logger.debug("getBufferSize"); - return this.getBufferSize(); - } - - @Override - public void flushBuffer() throws IOException { - logger.debug("flushBuffer"); - this.flushBuffer(); - } - - @Override - public void resetBuffer() { - logger.debug("resetBuffer"); - this.resetBuffer(); - } - - @Override - public boolean isCommitted() { - logger.debug("isCommitted"); - return this.isCommitted(); - } - - @Override - public void reset() { - logger.debug("reset"); - this.reset(); - } - - @Override - public void setLocale(Locale loc) { - logger.debug("setLocale"); - this.setLocale(loc); - } - - @Override - public Locale getLocale() { - logger.debug("getLocale"); - return this.getLocale(); - } - - @Override - public void addCookie(Cookie cookie) { - logger.debug("addCookie"); - this.addCookie(cookie); - } - - @Override - public boolean containsHeader(String name) { - logger.debug("containsHeader"); - return this.containsHeader(name); - } - - @Override - public String encodeURL(String url) { - logger.debug("encodeURL"); - return this.encodeURL(url); - } - - @Override - public String encodeRedirectURL(String url) { - logger.debug("encodeRedirectURL"); - return this.encodeRedirectURL(url); - } - - @Override - public String encodeUrl(String url) { - logger.debug("encodeUrl"); - return this.encodeUrl(url); - } - - @Override - public String encodeRedirectUrl(String url) { - logger.debug("encodeRedirectUrl"); - return this.encodeRedirectUrl(url); - } - - @Override - public void sendError(int sc, String msg) throws IOException { - logger.debug("sendError"); - this.sendError(sc); - - } - - @Override - public void sendError(int sc) throws IOException { - logger.debug("sendError"); - this.sendError(sc); - - } - - @Override - public void sendRedirect(String location) throws IOException { - logger.debug("sendRedirect"); - this.sendRedirect(location); - - } - - @Override - public void setDateHeader(String name, long date) { - logger.debug("setDateHeader"); - this.setDateHeader(name, date); - - } - - @Override - public void addDateHeader(String name, long date) { - logger.debug("addDateHeader"); - this.addDateHeader(name, date); - - } - - @Override - public void setHeader(String name, String value) { - logger.debug("setHeader"); - this.setHeader(name, value); - - } - - @Override - public void addHeader(String name, String value) { - logger.debug("addHeader: " + name + " - " + value); - this.addHeader(name, value); - - } - - @Override - public void setIntHeader(String name, int value) { - logger.debug("setIntHeader"); - this.setIntHeader(name, value); - - } - - @Override - public void addIntHeader(String name, int value) { - logger.debug("addIntHeader"); - this.addIntHeader(name, value); - - } + /** + * Default class logger. + */ + private Logger logger = LogManager.getLogger(CustomHttpServletResponseWrapper.class); + + /** + * Default constructor. + * + * @param response + * {@link HttpServletResponse} that should be encapsluated + */ + public CustomHttpServletResponseWrapper(HttpServletResponse response) { + super(response); + logger.debug("Constructor: " + response); + } + + @Override + public void addCookie(Cookie cookie) { + logger.debug("addCookie"); + this.addCookie(cookie); + } @Override + public PrintWriter getWriter() throws IOException { + logger.debug("getWriter"); + return this.getWriter(); + } + + @Override + public boolean containsHeader(String name) { + logger.debug("containsHeader"); + return this.containsHeader(name); + } @Override + public ServletOutputStream getOutputStream() throws IOException { + logger.debug("getOutputStream"); + logger.debug(new Exception(), new Exception()); + return this.getOutputStream(); + } + + @Override + public String encodeURL(String url) { + logger.debug("encodeURL"); + return this.encodeURL(url); + } @Override + public String getCharacterEncoding() { + logger.debug("getCharacterEncoding"); + return this.getCharacterEncoding(); + } + + @Override + public String encodeRedirectURL(String url) { + logger.debug("encodeRedirectURL"); + return this.encodeRedirectURL(url); + } @Override + public String getContentType() { + logger.debug("getContentType"); + return this.getContentType(); + } + + @Override + public String encodeUrl(String url) { + logger.debug("encodeUrl"); + return this.encodeUrl(url); + } @Override + public void setCharacterEncoding(String charset) { + logger.debug("setCharacterEncoding"); + this.setCharacterEncoding(charset); + } + + @Override + public String encodeRedirectUrl(String url) { + logger.debug("encodeRedirectUrl"); + return this.encodeRedirectUrl(url); + } @Override + public void setContentLength(int len) { + logger.debug("setContentLength"); + this.setContentLength(len); + } + + @Override + public void sendError(int sc, String msg) throws IOException { + logger.debug("sendError"); + this.sendError(sc); + + } @Override + public void setContentType(String type) { + logger.debug("setContentType: " + type); + logger.debug(new Exception(), new Exception()); + this.setContentType(type); + } + + @Override + public void sendError(int sc) throws IOException { + logger.debug("sendError"); + this.sendError(sc); + + } @Override + public void setBufferSize(int size) { + logger.debug("setBufferSize"); + this.setBufferSize(size); + } + + @Override + public void sendRedirect(String location) throws IOException { + logger.debug("sendRedirect"); + this.sendRedirect(location); + + } @Override + public int getBufferSize() { + logger.debug("getBufferSize"); + return this.getBufferSize(); + } + + @Override + public void setDateHeader(String name, long date) { + logger.debug("setDateHeader"); + this.setDateHeader(name, date); + + } @Override + public void flushBuffer() throws IOException { + logger.debug("flushBuffer"); + this.flushBuffer(); + } + + @Override + public void addDateHeader(String name, long date) { + logger.debug("addDateHeader"); + this.addDateHeader(name, date); + + } @Override + public void resetBuffer() { + logger.debug("resetBuffer"); + this.resetBuffer(); + } + + @Override + public void setHeader(String name, String value) { + logger.debug("setHeader"); + this.setHeader(name, value); + + } @Override + public boolean isCommitted() { + logger.debug("isCommitted"); + return this.isCommitted(); + } + + @Override + public void addHeader(String name, String value) { + logger.debug("addHeader: " + name + " - " + value); + this.addHeader(name, value); + + } @Override + public void reset() { + logger.debug("reset"); + this.reset(); + } + + @Override + public void setIntHeader(String name, int value) { + logger.debug("setIntHeader"); + this.setIntHeader(name, value); + + } @Override + public void setLocale(Locale loc) { + logger.debug("setLocale"); + this.setLocale(loc); + } + + @Override + public void addIntHeader(String name, int value) { + logger.debug("addIntHeader"); + this.addIntHeader(name, value); + + } @Override + public Locale getLocale() { + logger.debug("getLocale"); + return this.getLocale(); + } + + @Override + public void setStatus(int sc) { + logger.debug("setStatus: " + sc); + this.setStatus(sc); + + } + + @Override + public void setStatus(int sc, String sm) { + logger.debug("setStatus"); + this.setStatus(sc, sm); + + } + + + + + + + + + + + + + + + + + + + + + + + + + + - @Override - public void setStatus(int sc) { - logger.debug("setStatus: " + sc); - this.setStatus(sc); - } - @Override - public void setStatus(int sc, String sm) { - logger.debug("setStatus"); - this.setStatus(sc, sm); - } } diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/StartupBean.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/StartupBean.java index da4d1a3e28..5bb3cdf4d3 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/StartupBean.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/StartupBean.java @@ -18,9 +18,7 @@ import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.ProjectStatus; import lcsb.mapviewer.model.map.layout.ReferenceGenome; import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IProjectService; -import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; +import lcsb.mapviewer.services.interfaces.*; /** * Bean where init script of the application is placed. The method in this bean @@ -38,9 +36,9 @@ public class StartupBean { @Autowired public StartupBean(IProjectService projectService, - IConfigurationService configurationService, - IReferenceGenomeService referenceGenomeService, - ServletContext servletContext) { + IConfigurationService configurationService, + IReferenceGenomeService referenceGenomeService, + ServletContext servletContext) { this.projectService = projectService; this.configurationService = configurationService; this.referenceGenomeService = referenceGenomeService; diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/VersionResourceHandler.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/VersionResourceHandler.java index e308a998f4..a647539a8e 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/VersionResourceHandler.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/VersionResourceHandler.java @@ -3,10 +3,7 @@ package lcsb.mapviewer.web.bean.utils; import java.io.File; import java.io.IOException; -import javax.faces.application.Resource; -import javax.faces.application.ResourceHandler; -import javax.faces.application.ResourceHandlerWrapper; -import javax.faces.application.ResourceWrapper; +import javax.faces.application.*; import javax.faces.context.FacesContext; import org.apache.logging.log4j.LogManager; @@ -23,16 +20,14 @@ import lcsb.mapviewer.services.impl.ConfigurationService; * */ public class VersionResourceHandler extends ResourceHandlerWrapper { - /** - * Default class logger. - */ - private final Logger logger = LogManager.getLogger(VersionResourceHandler.class); - /** * GIT version of the system. */ private static String version = null; - + /** + * Default class logger. + */ + private final Logger logger = LogManager.getLogger(VersionResourceHandler.class); /** * Resource for which we generate modified url. */ @@ -48,6 +43,11 @@ public class VersionResourceHandler extends ResourceHandlerWrapper { this.wrapped = wrapped; } + @Override + public ResourceHandler getWrapped() { + return wrapped; + } + @Override public Resource createResource(String resourceName) { return createResource(resourceName, null, null); @@ -69,13 +69,13 @@ public class VersionResourceHandler extends ResourceHandlerWrapper { return new ResourceWrapper() { @Override - public String getRequestPath() { - return super.getRequestPath() + "&m_version=" + getVersion(); + public Resource getWrapped() { + return resource; } @Override - public Resource getWrapped() { - return resource; + public String getRequestPath() { + return super.getRequestPath() + "&m_version=" + getVersion(); } @Override @@ -84,22 +84,17 @@ public class VersionResourceHandler extends ResourceHandlerWrapper { } @Override - public String getResourceName() { - return getWrapped().getResourceName(); + public String getLibraryName() { + return getWrapped().getLibraryName(); } @Override - public String getLibraryName() { - return getWrapped().getLibraryName(); + public String getResourceName() { + return getWrapped().getResourceName(); } }; } - @Override - public ResourceHandler getWrapped() { - return wrapped; - } - /** * This method returns git version of the framework. * diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/XFrameFilter.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/XFrameFilter.java index 7cafab8000..518b5ff2c8 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/XFrameFilter.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/XFrameFilter.java @@ -1,12 +1,14 @@ package lcsb.mapviewer.web.bean.utils; -import lcsb.mapviewer.common.Configuration; -import org.apache.commons.validator.routines.UrlValidator; +import java.io.IOException; +import java.util.List; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.List; + +import org.apache.commons.validator.routines.UrlValidator; + +import lcsb.mapviewer.common.Configuration; public class XFrameFilter implements Filter { diff --git a/web/src/main/java/lcsb/mapviewer/web/bean/utils/package-info.java b/web/src/main/java/lcsb/mapviewer/web/bean/utils/package-info.java index bcb4a4511e..45bcaea616 100644 --- a/web/src/main/java/lcsb/mapviewer/web/bean/utils/package-info.java +++ b/web/src/main/java/lcsb/mapviewer/web/bean/utils/package-info.java @@ -2,4 +2,3 @@ * Provides util classes used by the web interface. */ package lcsb.mapviewer.web.bean.utils; - diff --git a/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationFailureHandlerImpl.java b/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationFailureHandlerImpl.java index 704d2557c3..9bfe246f61 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationFailureHandlerImpl.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationFailureHandlerImpl.java @@ -1,14 +1,15 @@ package lcsb.mapviewer.web.config; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.authentication.AuthenticationFailureHandler; -import org.springframework.stereotype.Component; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; + +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; @Component public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler { diff --git a/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationSuccessHandlerImpl.java b/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationSuccessHandlerImpl.java index ec526d7ab6..d6935a0a1a 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationSuccessHandlerImpl.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/AuthenticationSuccessHandlerImpl.java @@ -8,15 +8,15 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; +import com.fasterxml.jackson.databind.ObjectMapper; + import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.services.interfaces.IUserService; @@ -60,7 +60,7 @@ public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHa result.put("login", user.getLogin()); String json = new ObjectMapper().writeValueAsString(result); - + response.setContentType("application/json"); response.getWriter().print(json); diff --git a/web/src/main/java/lcsb/mapviewer/web/config/LdapAuthenticationProvider.java b/web/src/main/java/lcsb/mapviewer/web/config/LdapAuthenticationProvider.java index bc96862d2a..a40ff673bb 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/LdapAuthenticationProvider.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/LdapAuthenticationProvider.java @@ -43,8 +43,8 @@ public class LdapAuthenticationProvider implements AuthenticationProvider { throw new BadCredentialsException("Invalid username."); } User existingUser = userService.getUserByLogin(username); - - if (existingUser!=null) { + + if (existingUser != null) { if (!existingUser.isConnectedToLdap()) { throw new BadCredentialsException("User cannot authenticate over LDAP"); } diff --git a/web/src/main/java/lcsb/mapviewer/web/config/LocalAuthenticationProvider.java b/web/src/main/java/lcsb/mapviewer/web/config/LocalAuthenticationProvider.java index 1b36d74097..746fd716b0 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/LocalAuthenticationProvider.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/LocalAuthenticationProvider.java @@ -1,12 +1,11 @@ package lcsb.mapviewer.web.config; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IUserService; +import javax.annotation.PostConstruct; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; -import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; @@ -15,7 +14,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; +import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.services.interfaces.IUserService; @Order(1) @Service @@ -29,8 +29,8 @@ public class LocalAuthenticationProvider implements AuthenticationProvider { @Autowired public LocalAuthenticationProvider(UserDetailsService userDetailsService, - PasswordEncoder passwordEncoder, - IUserService userService) { + PasswordEncoder passwordEncoder, + IUserService userService) { this.userDetailsService = userDetailsService; this.passwordEncoder = passwordEncoder; this.userService = userService; diff --git a/web/src/main/java/lcsb/mapviewer/web/config/LogoutSuccessHandlerImpl.java b/web/src/main/java/lcsb/mapviewer/web/config/LogoutSuccessHandlerImpl.java index 147cd68d16..f44111018b 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/LogoutSuccessHandlerImpl.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/LogoutSuccessHandlerImpl.java @@ -1,13 +1,14 @@ package lcsb.mapviewer.web.config; -import org.springframework.security.core.Authentication; -import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; -import org.springframework.stereotype.Service; +import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.IOException; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; +import org.springframework.stereotype.Service; @Service public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler { diff --git a/web/src/main/java/lcsb/mapviewer/web/config/RefreshAuthoritiesInterceptor.java b/web/src/main/java/lcsb/mapviewer/web/config/RefreshAuthoritiesInterceptor.java index 2d73217101..bdb0699e99 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/RefreshAuthoritiesInterceptor.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/RefreshAuthoritiesInterceptor.java @@ -1,5 +1,8 @@ package lcsb.mapviewer.web.config; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -9,17 +12,16 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.HandlerInterceptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** - * This class intercepts a request (before the authorization step) to refresh the current authentication object in case - * the authorities have been updated since the last request. + * This class intercepts a request (before the authorization step) to refresh + * the current authentication object in case the authorities have been updated + * since the last request. * - * Performance note: - * This code has an impact on performance due to the repeated DB requests, but is much simpler and therefor safer. - * If performance becomes an issue, user sessions must be updated manually when authorities change. This also requires - * being able to directly access and modify an arbitrary user session from the current request session. + * Performance note: This code has an impact on performance due to the repeated + * DB requests, but is much simpler and therefor safer. If performance becomes + * an issue, user sessions must be updated manually when authorities change. + * This also requires being able to directly access and modify an arbitrary user + * session from the current request session. */ @Transactional @Service @@ -41,8 +43,7 @@ public class RefreshAuthoritiesInterceptor implements HandlerInterceptor { Authentication newAuth = new UsernamePasswordAuthenticationToken( auth.getPrincipal(), auth.getCredentials(), - userDetailsService.loadUserByUsername(auth.getName()).getAuthorities() - ); + userDetailsService.loadUserByUsername(auth.getName()).getAuthorities()); SecurityContextHolder.getContext().setAuthentication(newAuth); return true; } diff --git a/web/src/main/java/lcsb/mapviewer/web/config/SpringSecurityConfig.java b/web/src/main/java/lcsb/mapviewer/web/config/SpringSecurityConfig.java index ff4a033e83..d269c94d9f 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/SpringSecurityConfig.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/SpringSecurityConfig.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.web.config; -import javax.transaction.Transactional; +import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.*; @@ -19,11 +19,9 @@ import lcsb.mapviewer.api.SpringRestApiConfig; import lcsb.mapviewer.services.SpringServiceConfig; import lcsb.mapviewer.web.bean.utils.*; -import java.util.List; - @Configuration @ComponentScan(basePackages = { "lcsb.mapviewer.web.config" }) -@Import({SpringRestApiConfig.class, SpringServiceConfig.class}) +@Import({ SpringRestApiConfig.class, SpringServiceConfig.class }) @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @@ -34,9 +32,9 @@ public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired SpringSecurityConfig(AuthenticationSuccessHandler successHandler, - AuthenticationFailureHandler failureHandler, - LogoutSuccessHandler logoutSuccessHandler, - List<AuthenticationProvider> authenticationProviders) { + AuthenticationFailureHandler failureHandler, + LogoutSuccessHandler logoutSuccessHandler, + List<AuthenticationProvider> authenticationProviders) { super(false); this.successHandler = successHandler; this.failureHandler = failureHandler; diff --git a/web/src/main/java/lcsb/mapviewer/web/config/SpringWebConfig.java b/web/src/main/java/lcsb/mapviewer/web/config/SpringWebConfig.java index 8a5e92ff18..139b2ad949 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/SpringWebConfig.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/SpringWebConfig.java @@ -1,22 +1,20 @@ package lcsb.mapviewer.web.config; -import lcsb.mapviewer.api.SpringRestApiConfig; +import java.util.List; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.*; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.InternalResourceViewResolver; -import java.util.List; +import lcsb.mapviewer.api.SpringRestApiConfig; @Configuration @EnableWebMvc @Import(SpringRestApiConfig.class) -@ComponentScan(basePackages = {"lcsb.mapviewer.web"}) +@ComponentScan(basePackages = { "lcsb.mapviewer.web" }) public class SpringWebConfig implements WebMvcConfigurer { private List<HandlerInterceptor> interceptors; @@ -35,10 +33,8 @@ public class SpringWebConfig implements WebMvcConfigurer { } @Override - public void addViewControllers(ViewControllerRegistry registry) { - registry - .addViewController("/") - .setViewName("index"); + public void addInterceptors(InterceptorRegistry registry) { + interceptors.forEach(registry::addInterceptor); } @Override @@ -54,8 +50,10 @@ public class SpringWebConfig implements WebMvcConfigurer { } @Override - public void addInterceptors(InterceptorRegistry registry) { - interceptors.forEach(registry::addInterceptor); + public void addViewControllers(ViewControllerRegistry registry) { + registry + .addViewController("/") + .setViewName("index"); } } diff --git a/web/src/main/java/lcsb/mapviewer/web/config/UserDetailsServiceImpl.java b/web/src/main/java/lcsb/mapviewer/web/config/UserDetailsServiceImpl.java index b5c1763048..1d5898de91 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/UserDetailsServiceImpl.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/UserDetailsServiceImpl.java @@ -5,13 +5,13 @@ import java.util.stream.Collectors; import javax.transaction.Transactional; -import lcsb.mapviewer.common.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.*; import org.springframework.stereotype.Service; +import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.user.UserDao; diff --git a/web/src/main/java/lcsb/mapviewer/web/config/WebAppInitializer.java b/web/src/main/java/lcsb/mapviewer/web/config/WebAppInitializer.java index 945ce43bb8..4833b9fa77 100644 --- a/web/src/main/java/lcsb/mapviewer/web/config/WebAppInitializer.java +++ b/web/src/main/java/lcsb/mapviewer/web/config/WebAppInitializer.java @@ -34,15 +34,6 @@ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServlet return new Class[] {}; } - @Override - protected String[] getServletMappings() { - return new String[] { "/", "/api/*" }; - } - - @Override - protected Filter[] getServletFilters() { - return new Filter[]{new XFrameFilter()}; - } @Override public void onStartup(ServletContext container) throws ServletException { assert container.setInitParameter("com.sun.faces.enableMissingResourceLibraryDetection", "true"); @@ -76,4 +67,14 @@ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServlet super.onStartup(container); } + + @Override + protected String[] getServletMappings() { + return new String[] { "/", "/api/*" }; + } + + @Override + protected Filter[] getServletFilters() { + return new Filter[] { new XFrameFilter() }; + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/converter/MiriamTypeConverter.java b/web/src/main/java/lcsb/mapviewer/web/converter/MiriamTypeConverter.java index 6e2ec9290c..a5bd60c1c5 100644 --- a/web/src/main/java/lcsb/mapviewer/web/converter/MiriamTypeConverter.java +++ b/web/src/main/java/lcsb/mapviewer/web/converter/MiriamTypeConverter.java @@ -1,16 +1,15 @@ package lcsb.mapviewer.web.converter; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.UUID; -import java.util.WeakHashMap; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.FacesConverter; -import org.apache.logging.log4j.*; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; /** * Converter used for {@link lcsb.mapviewer.model.map.MiriamType} in primefaces @@ -22,38 +21,37 @@ import org.apache.logging.log4j.*; @FacesConverter(value = "miriamTypeConverter") public class MiriamTypeConverter implements Converter { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = LogManager.getLogger(MiriamTypeConverter.class); - - /** - * Map between custom uuid and MiriamType object. - */ - private static Map<Object, String> entities = new WeakHashMap<Object, String>(); - - @Override - public String getAsString(FacesContext context, UIComponent component, Object entity) { - synchronized (entities) { - if (!entities.containsKey(entity)) { - String uuid = UUID.randomUUID().toString(); - entities.put(entity, uuid); - return uuid; - } else { - return entities.get(entity); - } - } - } - - @Override - public Object getAsObject(FacesContext context, UIComponent component, String uuid) { - for (Entry<Object, String> entry : entities.entrySet()) { - if (entry.getValue().equals(uuid)) { - return entry.getKey(); - } - } - return null; - } + /** + * Map between custom uuid and MiriamType object. + */ + private static Map<Object, String> entities = new WeakHashMap<Object, String>(); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = LogManager.getLogger(MiriamTypeConverter.class); + + @Override + public Object getAsObject(FacesContext context, UIComponent component, String uuid) { + for (Entry<Object, String> entry : entities.entrySet()) { + if (entry.getValue().equals(uuid)) { + return entry.getKey(); + } + } + return null; + } + + @Override + public String getAsString(FacesContext context, UIComponent component, Object entity) { + synchronized (entities) { + if (!entities.containsKey(entity)) { + String uuid = UUID.randomUUID().toString(); + entities.put(entity, uuid); + return uuid; + } else { + return entities.get(entity); + } + } + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/converter/package-info.java b/web/src/main/java/lcsb/mapviewer/web/converter/package-info.java index 9459987d0d..00e738795f 100644 --- a/web/src/main/java/lcsb/mapviewer/web/converter/package-info.java +++ b/web/src/main/java/lcsb/mapviewer/web/converter/package-info.java @@ -3,4 +3,3 @@ * by primefaces. */ package lcsb.mapviewer.web.converter; - diff --git a/web/src/main/java/lcsb/mapviewer/web/events/Event.java b/web/src/main/java/lcsb/mapviewer/web/events/Event.java index 3ad3a4efcf..84ca1302b6 100644 --- a/web/src/main/java/lcsb/mapviewer/web/events/Event.java +++ b/web/src/main/java/lcsb/mapviewer/web/events/Event.java @@ -1,6 +1,5 @@ package lcsb.mapviewer.web.events; - /** * Abstract event object that might be handled by {@link Listener} class. * diff --git a/web/src/main/java/lcsb/mapviewer/web/events/Listener.java b/web/src/main/java/lcsb/mapviewer/web/events/Listener.java index e80dec2722..56de800f0d 100644 --- a/web/src/main/java/lcsb/mapviewer/web/events/Listener.java +++ b/web/src/main/java/lcsb/mapviewer/web/events/Listener.java @@ -10,51 +10,51 @@ import java.io.Serializable; * @param <T> */ public abstract class Listener<T extends Event> implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Class of event handled by this listener. - */ - private Class<T> eventClass; - - /** - * Default constructor. - * - * @param clazz - * class of events handled by this listener - */ - public Listener(Class<T> clazz) { - this.eventClass = clazz; - } - - /** - * This method handle the event. - * - * @param event - * event to be handled - */ - protected abstract void handle(T event); - - /** - * Handle the event. - * - * @param event - * event to be handled - */ - @SuppressWarnings("unchecked") - public void handleEvent(Event event) { - this.handle((T) event); - } - - /** - * @return the eventClass - * @see #eventClass - */ - public Class<T> getEventClass() { - return eventClass; - } + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Class of event handled by this listener. + */ + private Class<T> eventClass; + + /** + * Default constructor. + * + * @param clazz + * class of events handled by this listener + */ + public Listener(Class<T> clazz) { + this.eventClass = clazz; + } + + /** + * This method handle the event. + * + * @param event + * event to be handled + */ + protected abstract void handle(T event); + + /** + * Handle the event. + * + * @param event + * event to be handled + */ + @SuppressWarnings("unchecked") + public void handleEvent(Event event) { + this.handle((T) event); + } + + /** + * @return the eventClass + * @see #eventClass + */ + public Class<T> getEventClass() { + return eventClass; + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/events/ObjectAddedEvent.java b/web/src/main/java/lcsb/mapviewer/web/events/ObjectAddedEvent.java index d1724d278c..57437881ce 100644 --- a/web/src/main/java/lcsb/mapviewer/web/events/ObjectAddedEvent.java +++ b/web/src/main/java/lcsb/mapviewer/web/events/ObjectAddedEvent.java @@ -9,32 +9,32 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; * */ public class ObjectAddedEvent extends Event { - - /** - * Object that was removed. - */ - private Object object; - /** - * Default constructor. - * - * @param object - * {@link #object} - */ - public ObjectAddedEvent(Object object) { - if (object == null) { - throw new InvalidArgumentException("object cannot be null"); - } + /** + * Object that was removed. + */ + private Object object; - this.object = object; - } + /** + * Default constructor. + * + * @param object + * {@link #object} + */ + public ObjectAddedEvent(Object object) { + if (object == null) { + throw new InvalidArgumentException("object cannot be null"); + } - /** - * @return the object - * @see #object - */ - public Object getObject() { - return object; - } + this.object = object; + } + + /** + * @return the object + * @see #object + */ + public Object getObject() { + return object; + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/events/ObjectModifiedEvent.java b/web/src/main/java/lcsb/mapviewer/web/events/ObjectModifiedEvent.java index 7738d88194..f35620dcb4 100644 --- a/web/src/main/java/lcsb/mapviewer/web/events/ObjectModifiedEvent.java +++ b/web/src/main/java/lcsb/mapviewer/web/events/ObjectModifiedEvent.java @@ -9,31 +9,31 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; * */ public class ObjectModifiedEvent extends Event { - - /** - * Object that was modified. - */ - private Object object; - /** - * Default constructor. - * - * @param object - * {@link #object} - */ - public ObjectModifiedEvent(Object object) { - if (object == null) { - throw new InvalidArgumentException("object cannot be null"); - } - this.object = object; - } + /** + * Object that was modified. + */ + private Object object; - /** - * @return the object - * @see #object - */ - public Object getObject() { - return object; - } + /** + * Default constructor. + * + * @param object + * {@link #object} + */ + public ObjectModifiedEvent(Object object) { + if (object == null) { + throw new InvalidArgumentException("object cannot be null"); + } + this.object = object; + } + + /** + * @return the object + * @see #object + */ + public Object getObject() { + return object; + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/events/ObjectRemovedEvent.java b/web/src/main/java/lcsb/mapviewer/web/events/ObjectRemovedEvent.java index 5e88eddac7..34abd352a6 100644 --- a/web/src/main/java/lcsb/mapviewer/web/events/ObjectRemovedEvent.java +++ b/web/src/main/java/lcsb/mapviewer/web/events/ObjectRemovedEvent.java @@ -9,32 +9,32 @@ import lcsb.mapviewer.common.exception.InvalidArgumentException; * */ public class ObjectRemovedEvent extends Event { - - /** - * Object that was removed. - */ - private Object object; - /** - * Default constructor. - * - * @param object - * {@link #object} - */ - public ObjectRemovedEvent(Object object) { - if (object == null) { - throw new InvalidArgumentException("object cannot be null"); - } + /** + * Object that was removed. + */ + private Object object; - this.object = object; - } + /** + * Default constructor. + * + * @param object + * {@link #object} + */ + public ObjectRemovedEvent(Object object) { + if (object == null) { + throw new InvalidArgumentException("object cannot be null"); + } - /** - * @return the object - * @see #object - */ - public Object getObject() { - return object; - } + this.object = object; + } + + /** + * @return the object + * @see #object + */ + public Object getObject() { + return object; + } } diff --git a/web/src/main/java/lcsb/mapviewer/web/events/package-info.java b/web/src/main/java/lcsb/mapviewer/web/events/package-info.java index 9060b696b6..58b4c326f8 100644 --- a/web/src/main/java/lcsb/mapviewer/web/events/package-info.java +++ b/web/src/main/java/lcsb/mapviewer/web/events/package-info.java @@ -2,4 +2,3 @@ * Provides events and listeners functionality. */ package lcsb.mapviewer.web.events; - diff --git a/web/src/test/java/lcsb/mapviewer/web/ChemicalControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/ChemicalControllerIntegrationTest.java index d01180bf97..959d2fee3b 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ChemicalControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/ChemicalControllerIntegrationTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -24,11 +24,9 @@ import lcsb.mapviewer.services.interfaces.IConfigurationService; @Rollback public class ChemicalControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; - + Logger logger = LogManager.getLogger(); @Autowired IConfigurationService configurationService; diff --git a/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTest.java index 824e80cae2..1fb757ca94 100644 --- a/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.web; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.awt.geom.Point2D; import java.util.Arrays; @@ -40,19 +40,14 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Rollback public class CommentControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_PROJECT = "test_project"; - private static final String TEST_USER_PASSWORD = "test_user_pass"; private static final String TEST_USER_LOGIN = "test_user"; - private static final String TEST_CURATOR_PASSWORD = "test_curator_pass"; private static final String TEST_CURATOR_LOGIN = "test_curator"; - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; - + Logger logger = LogManager.getLogger(); private ModelData map; private Reaction reaction; private Element element; diff --git a/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTestWithoutTransaction.java b/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTestWithoutTransaction.java index ab5abd5463..5a3005d701 100644 --- a/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTestWithoutTransaction.java +++ b/web/src/test/java/lcsb/mapviewer/web/CommentControllerIntegrationTestWithoutTransaction.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -16,10 +16,9 @@ import org.springframework.test.web.servlet.RequestBuilder; @Rollback public class CommentControllerIntegrationTestWithoutTransaction extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String BUILT_IN_TEST_ADMIN_PASSWORD = "admin"; private static final String BUILT_IN_TEST_ADMIN_LOGIN = "admin"; + Logger logger = LogManager.getLogger(); @Before public void setup() { diff --git a/web/src/test/java/lcsb/mapviewer/web/ConfigurationControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/ConfigurationControllerIntegrationTest.java index a8dac431a5..66afc4bc0c 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ConfigurationControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/ConfigurationControllerIntegrationTest.java @@ -1,8 +1,10 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.HashMap; import java.util.Map; @@ -31,16 +33,11 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Transactional @Rollback public class ConfigurationControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_USER_PASSWORD = "test_pass"; - private static final String TEST_USER_LOGIN = "test_user"; - private static final String TEST_ADMIN_PASSWORD = "test_admin_pass"; - private static final String TEST_ADMIN_LOGIN = "test_admin"; - + Logger logger = LogManager.getLogger(); @Autowired private IUserService userService; diff --git a/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java index 4044855a7d..df0d467a51 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/ControllerIntegrationTest.java @@ -1,6 +1,6 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import java.awt.geom.Point2D; import java.util.Arrays; @@ -49,33 +49,23 @@ abstract public class ControllerIntegrationTest { @Rule public UnitTestFailedWatcher unitTestFailedWatcher = new UnitTestFailedWatcher(); - + protected MockMvc mockMvc; @Autowired private WebApplicationContext context; - @Autowired private Filter springSecurityFilterChain; - @Autowired private IUserService userService; - @Autowired private ProjectDao projectDao; - @Autowired private UserDao userDao; - @Autowired private PasswordEncoder passwordEncoder; - @Autowired private UploadedFileEntryDao fileDao; - @Autowired private DbUtils dbUtils; - - protected MockMvc mockMvc; - private MinervaLoggerAppender appender; private ExecutorService executorService; diff --git a/web/src/test/java/lcsb/mapviewer/web/DrugControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/DrugControllerIntegrationTest.java index eaf02a4fc2..c4ed2e324c 100644 --- a/web/src/test/java/lcsb/mapviewer/web/DrugControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/DrugControllerIntegrationTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -24,11 +24,9 @@ import lcsb.mapviewer.services.interfaces.IConfigurationService; @Rollback public class DrugControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; - + Logger logger = LogManager.getLogger(); @Autowired IConfigurationService configurationService; diff --git a/web/src/test/java/lcsb/mapviewer/web/EndPointsInputValidationTests.java b/web/src/test/java/lcsb/mapviewer/web/EndPointsInputValidationTests.java index 36bcefe396..440278e5ac 100644 --- a/web/src/test/java/lcsb/mapviewer/web/EndPointsInputValidationTests.java +++ b/web/src/test/java/lcsb/mapviewer/web/EndPointsInputValidationTests.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import java.net.URI; @@ -25,15 +26,12 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandl @RunWith(SpringJUnit4ClassRunner.class) public class EndPointsInputValidationTests extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static String[] testValues = { " ", "-1", "0", "empty", "admin", "1.00,2.00", "17.00", "1" }; private static List<HttpStatus> validResponses = Arrays.asList(HttpStatus.OK, HttpStatus.BAD_REQUEST, HttpStatus.NOT_FOUND, HttpStatus.FORBIDDEN); - @Autowired public RequestMappingHandlerMapping requestMappingHandlerMapping; - + Logger logger = LogManager.getLogger(); @Autowired ServletContext container; diff --git a/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTest.java index 63fe2306d3..9259b5ba64 100644 --- a/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.junit.Assert.assertNotNull; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; diff --git a/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTestWithoutTransaction.java b/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTestWithoutTransaction.java index a90953356c..9d32a6cf18 100644 --- a/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTestWithoutTransaction.java +++ b/web/src/test/java/lcsb/mapviewer/web/FileControllerIntegrationTestWithoutTransaction.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; diff --git a/web/src/test/java/lcsb/mapviewer/web/LdapServiceTestConfiguration.java b/web/src/test/java/lcsb/mapviewer/web/LdapServiceTestConfiguration.java index b111ecbd63..71dbe40e6a 100644 --- a/web/src/test/java/lcsb/mapviewer/web/LdapServiceTestConfiguration.java +++ b/web/src/test/java/lcsb/mapviewer/web/LdapServiceTestConfiguration.java @@ -21,15 +21,13 @@ import lcsb.mapviewer.services.interfaces.ILdapService; @Profile("ldapTest") @Configuration public class LdapServiceTestConfiguration { - @Autowired - IConfigurationService configurationService; - - Logger logger = LogManager.getLogger(); - static String TEST_LOGIN = "john.doe.test"; static String TEST_PASSWD = "test_passwd"; static String LDAP_FILE_CONTENT = "./src/test/resources/ldap/john-doe-test-example.ldif"; static String TEST_INVALID_PASSWD = "incorrect password"; + @Autowired + IConfigurationService configurationService; + Logger logger = LogManager.getLogger(); @Bean @Primary diff --git a/web/src/test/java/lcsb/mapviewer/web/MapControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/MapControllerIntegrationTest.java index f61eb579ee..a3aef6a207 100644 --- a/web/src/test/java/lcsb/mapviewer/web/MapControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/MapControllerIntegrationTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/web/src/test/java/lcsb/mapviewer/web/MiRnaControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/MiRnaControllerIntegrationTest.java index c71986efe6..92b63aad17 100644 --- a/web/src/test/java/lcsb/mapviewer/web/MiRnaControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/MiRnaControllerIntegrationTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -24,11 +24,9 @@ import lcsb.mapviewer.services.interfaces.IConfigurationService; @Rollback public class MiRnaControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; - + Logger logger = LogManager.getLogger(); @Autowired IConfigurationService configurationService; diff --git a/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTest.java index 5c8360d268..f0dfd1ee1f 100644 --- a/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; @@ -40,19 +40,14 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Rollback public class OverlayControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_PROJECT = "test_project"; - private static final String TEST_USER_PASSWORD = "test_user_pass"; private static final String TEST_USER_LOGIN = "test_user"; - private static final String TEST_CURATOR_PASSWORD = "test_curator_pass"; private static final String TEST_CURATOR_LOGIN = "test_curator"; - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; - + Logger logger = LogManager.getLogger(); @Autowired private LayoutDao layoutDao; @@ -147,9 +142,10 @@ public class OverlayControllerIntegrationTest extends ControllerIntegrationTest MockHttpSession session = createSession(TEST_ADMIN_LOGIN, TEST_ADMIN_PASSWORD); - RequestBuilder request = get("/projects/" + TEST_PROJECT + "/overlays/?publicOverlay=false&creator="+TEST_ADMIN_LOGIN) - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .session(session); + RequestBuilder request = get( + "/projects/" + TEST_PROJECT + "/overlays/?publicOverlay=false&creator=" + TEST_ADMIN_LOGIN) + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .session(session); String response = mockMvc.perform(request) .andExpect(status().is2xxSuccessful()) @@ -1025,8 +1021,8 @@ public class OverlayControllerIntegrationTest extends ControllerIntegrationTest RequestBuilder request = get( "/projects/" + TEST_PROJECT + "/overlays/" + overlay.getId() + ":downloadSource/") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .session(session); + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .session(session); mockMvc.perform(request) .andExpect(status().is2xxSuccessful()); diff --git a/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTestWithoutTransaction.java b/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTestWithoutTransaction.java index 2f27f12472..ace9df7f86 100644 --- a/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTestWithoutTransaction.java +++ b/web/src/test/java/lcsb/mapviewer/web/OverlayControllerIntegrationTestWithoutTransaction.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -21,15 +21,12 @@ import lcsb.mapviewer.services.interfaces.IConfigurationService; @Rollback public class OverlayControllerIntegrationTestWithoutTransaction extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String BUILD_IN_TEST_ADMIN_PASSWORD = "admin"; private static final String BUILD_IN_TEST_ADMIN_LOGIN = "admin"; - - private String defaultProjectId; - + Logger logger = LogManager.getLogger(); @Autowired IConfigurationService configurationService; + private String defaultProjectId; @Before public void setup() throws Exception { diff --git a/web/src/test/java/lcsb/mapviewer/web/PluginControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/PluginControllerIntegrationTest.java index e6c8580c56..83ec743993 100644 --- a/web/src/test/java/lcsb/mapviewer/web/PluginControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/PluginControllerIntegrationTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.junit.Assert.assertEquals; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.Arrays; @@ -11,9 +12,7 @@ import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.*; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; @@ -37,12 +36,9 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Rollback public class PluginControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_USER_PASSWORD = "test_pass"; - private static final String TEST_USER_LOGIN = "test_user"; - + Logger logger = LogManager.getLogger(); @Autowired private PluginDao pluginDao; @@ -192,9 +188,10 @@ public class PluginControllerIntegrationTest extends ControllerIntegrationTest { Plugin plugin = createPlugin(); - RequestBuilder request = post("/plugins/" + plugin.getHash() + "/data/users/" + Configuration.ANONYMOUS_LOGIN + "/key/") - .contentType(MediaType.APPLICATION_FORM_URLENCODED) - .content(body); + RequestBuilder request = post( + "/plugins/" + plugin.getHash() + "/data/users/" + Configuration.ANONYMOUS_LOGIN + "/key/") + .contentType(MediaType.APPLICATION_FORM_URLENCODED) + .content(body); mockMvc.perform(request) .andExpect(status().is2xxSuccessful()); diff --git a/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTest.java index 3909060911..04b24c6fe6 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.web; import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -32,15 +33,11 @@ import lcsb.mapviewer.services.interfaces.IUserService; public class ProjectControllerIntegrationTest extends ControllerIntegrationTest { private static final String TEST_PROJECT = "test_project"; - - Logger logger = LogManager.getLogger(); - private static final String CURATOR_PASSWORD = "test_pass"; private static final String CURATOR_LOGIN = "test_user"; - private static final String ADMIN_PASSWORD = "admin_pass"; private static final String ADMIN_LOGIN = "admin_user"; - + Logger logger = LogManager.getLogger(); @Autowired private IUserService userService; diff --git a/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java b/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java index 02dd41778a..607a27e11b 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java +++ b/web/src/test/java/lcsb/mapviewer/web/ProjectControllerIntegrationTestForAsyncCalls.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.web; import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.file.Files; import java.nio.file.Paths; @@ -37,18 +38,13 @@ import lcsb.mapviewer.services.interfaces.IUserService; public class ProjectControllerIntegrationTestForAsyncCalls extends ControllerIntegrationTest { private static final String TEST_PROJECT = "test_project"; - - Logger logger = LogManager.getLogger(); - private static final String CURATOR_PASSWORD = "curator_pass"; private static final String CURATOR_LOGIN = "test_curator"; - private static final String ADMIN_PASSWORD = "admin_pass"; private static final String ADMIN_LOGIN = "admin_user"; - private static final String USER_PASSWORD = "user_pass"; private static final String USER_LOGIN = "test_user"; - + Logger logger = LogManager.getLogger(); @Autowired private ProjectDao projectDao; diff --git a/web/src/test/java/lcsb/mapviewer/web/PublicationsControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/PublicationsControllerIntegrationTest.java index 9fdec3d038..5b8340d0d4 100644 --- a/web/src/test/java/lcsb/mapviewer/web/PublicationsControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/PublicationsControllerIntegrationTest.java @@ -1,7 +1,7 @@ package lcsb.mapviewer.web; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/web/src/test/java/lcsb/mapviewer/web/ReactionControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/ReactionControllerIntegrationTest.java index 3d79f671c6..d40c300b85 100644 --- a/web/src/test/java/lcsb/mapviewer/web/ReactionControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/ReactionControllerIntegrationTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; diff --git a/web/src/test/java/lcsb/mapviewer/web/SpringSecurityGeneralIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/SpringSecurityGeneralIntegrationTest.java index 42b7f776f4..744ba7ab53 100644 --- a/web/src/test/java/lcsb/mapviewer/web/SpringSecurityGeneralIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/SpringSecurityGeneralIntegrationTest.java @@ -1,8 +1,9 @@ package lcsb.mapviewer.web; import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import javax.servlet.http.HttpSession; @@ -39,7 +40,7 @@ public class SpringSecurityGeneralIntegrationTest extends ControllerIntegrationT @Autowired IConfigurationService configurationService; - + @Before public void setup() { createUser(TEST_USER_LOGIN, TEST_USER_PASSWORD); diff --git a/web/src/test/java/lcsb/mapviewer/web/SpringSecurityLdapIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/SpringSecurityLdapIntegrationTest.java index 81a009f6f3..61303def63 100644 --- a/web/src/test/java/lcsb/mapviewer/web/SpringSecurityLdapIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/SpringSecurityLdapIntegrationTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.web; import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -38,8 +38,6 @@ public class SpringSecurityLdapIntegrationTest extends ControllerIntegrationTest @Autowired private IUserService userService; - - @Before public void setUp() throws LDAPException { } @@ -48,7 +46,6 @@ public class SpringSecurityLdapIntegrationTest extends ControllerIntegrationTest public void tearDown() { } - @Test public void testInvalidLoginFromLdap() throws Exception { int count = userService.getUsers().size(); @@ -103,7 +100,7 @@ public class SpringSecurityLdapIntegrationTest extends ControllerIntegrationTest assertEquals("LDAP login is case insensitive and no new user should be added for different cases", count + 1, userService.getUsers().size()); } - + @Test public void testLocalAccountShouldntAuthenticateFromLdap() throws Exception { createUser(LdapServiceTestConfiguration.TEST_LOGIN, LOCAL_PASSWORD); diff --git a/web/src/test/java/lcsb/mapviewer/web/TaxonomiesControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/TaxonomiesControllerIntegrationTest.java index abc8b0655e..e1a58f0e02 100644 --- a/web/src/test/java/lcsb/mapviewer/web/TaxonomiesControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/TaxonomiesControllerIntegrationTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.junit.Assert.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -39,7 +39,7 @@ public class TaxonomiesControllerIntegrationTest extends ControllerIntegrationTe String response = mockMvc.perform(request) .andExpect(status().is2xxSuccessful()) .andReturn().getResponse().getContentAsString(); - + int taxonomies = new JsonParser() .parse(response) .getAsJsonArray().size(); diff --git a/web/src/test/java/lcsb/mapviewer/web/UserControllerAnonymousIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/UserControllerAnonymousIntegrationTest.java index 5748478576..b646785583 100644 --- a/web/src/test/java/lcsb/mapviewer/web/UserControllerAnonymousIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/UserControllerAnonymousIntegrationTest.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -19,17 +19,15 @@ import org.springframework.transaction.annotation.Transactional; import com.google.gson.JsonParser; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.model.user.User; @RunWith(SpringJUnit4ClassRunner.class) @Transactional @Rollback public class UserControllerAnonymousIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; + Logger logger = LogManager.getLogger(); @Before public void setup() { diff --git a/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTest.java b/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTest.java index aa8068f456..5ea6eb81ca 100644 --- a/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTest.java +++ b/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTest.java @@ -2,7 +2,7 @@ package lcsb.mapviewer.web; import static org.junit.Assert.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.*; @@ -38,16 +38,12 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Rollback public class UserControllerIntegrationTest extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_USER_PASSWORD = "test_pass"; private static final String TEST_USER_LOGIN = "test_user"; - private static final String TEST_ADMIN_PASSWORD = "test_admin"; private static final String TEST_ADMIN_LOGIN = "test_admin"; - private static final String TEST_PROJECT = "test_project"; - + Logger logger = LogManager.getLogger(); private User user; private User admin; @@ -301,8 +297,7 @@ public class UserControllerIntegrationTest extends ControllerIntegrationTest { String body = EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList( new BasicNameValuePair("name", "FirstName"), - new BasicNameValuePair("password", "FirstName") - ))); + new BasicNameValuePair("password", "FirstName")))); RequestBuilder grantRequest = post("/users/" + testLogin) .contentType(MediaType.APPLICATION_FORM_URLENCODED) @@ -321,8 +316,7 @@ public class UserControllerIntegrationTest extends ControllerIntegrationTest { MockHttpSession session = createSession(TEST_ADMIN_LOGIN, TEST_ADMIN_PASSWORD); String body = EntityUtils.toString(new UrlEncodedFormEntity(Arrays.asList( - new BasicNameValuePair("name", "FirstName") - ))); + new BasicNameValuePair("name", "FirstName")))); RequestBuilder grantRequest = post("/users/" + testLogin) .contentType(MediaType.APPLICATION_FORM_URLENCODED) diff --git a/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTestWithoutTransaction.java b/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTestWithoutTransaction.java index ba88a60563..2b70d963ed 100644 --- a/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTestWithoutTransaction.java +++ b/web/src/test/java/lcsb/mapviewer/web/UserControllerIntegrationTestWithoutTransaction.java @@ -1,10 +1,9 @@ package lcsb.mapviewer.web; -import static org.junit.Assert.*; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import java.util.*; +import java.util.Arrays; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.message.BasicNameValuePair; @@ -20,31 +19,18 @@ import org.springframework.mock.web.MockHttpSession; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.RequestBuilder; -import org.springframework.transaction.annotation.Transactional; -import com.google.gson.*; - -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.security.Privilege; -import lcsb.mapviewer.model.security.PrivilegeType; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.persist.dao.ProjectDao; -import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.IUserService; @RunWith(SpringJUnit4ClassRunner.class) @Rollback public class UserControllerIntegrationTestWithoutTransaction extends ControllerIntegrationTest { - Logger logger = LogManager.getLogger(); - private static final String TEST_USER_PASSWORD = "test_pass"; private static final String TEST_USER_LOGIN = "test_user"; - private static final String ADMIN_PASSWORD = "admin"; private static final String ADMIN_LOGIN = "admin"; - + Logger logger = LogManager.getLogger(); @Autowired private IUserService userService; -- GitLab