From 6029d25f5f3ad43fe02ffe1a4beb1eda0a6ae5e3 Mon Sep 17 00:00:00 2001 From: ramverma Date: Fri, 25 May 2018 11:55:45 +0100 Subject: Adding apex event-model module - Adding apex event-model module - Fixing namespaces Change-Id: If37a1773000ca99eb5d97703fdeb5788ce55365c Issue-ID: POLICY-856 Signed-off-by: ramverma --- .gitignore | 1 + model/basic-model/pom.xml | 10 +- .../basicmodel/concepts/ApexConceptException.java | 49 -- .../model/basicmodel/concepts/ApexException.java | 102 ---- .../basicmodel/concepts/ApexRuntimeException.java | 101 ---- .../model/basicmodel/concepts/AxArtifactKey.java | 376 ------------- .../apex/model/basicmodel/concepts/AxConcept.java | 137 ----- .../model/basicmodel/concepts/AxConceptGetter.java | 77 --- .../basicmodel/concepts/AxConceptGetterImpl.java | 156 ------ .../onap/apex/model/basicmodel/concepts/AxKey.java | 99 ---- .../apex/model/basicmodel/concepts/AxKeyInfo.java | 356 ------------- .../basicmodel/concepts/AxKeyInformation.java | 448 ---------------- .../apex/model/basicmodel/concepts/AxKeyUse.java | 245 --------- .../apex/model/basicmodel/concepts/AxModel.java | 471 ----------------- .../model/basicmodel/concepts/AxReferenceKey.java | 556 -------------------- .../basicmodel/concepts/AxValidationMessage.java | 103 ---- .../basicmodel/concepts/AxValidationResult.java | 145 ------ .../model/basicmodel/concepts/package-info.java | 34 -- .../onap/apex/model/basicmodel/dao/ApexDao.java | 207 -------- .../apex/model/basicmodel/dao/ApexDaoFactory.java | 66 --- .../apex/model/basicmodel/dao/DAOParameters.java | 124 ----- .../dao/converters/CDATAConditioner.java | 92 ---- .../basicmodel/dao/converters/UUID2String.java | 83 --- .../basicmodel/dao/converters/package-info.java | 27 - .../model/basicmodel/dao/impl/DefaultApexDao.java | 526 ------------------- .../model/basicmodel/dao/impl/package-info.java | 26 - .../apex/model/basicmodel/dao/package-info.java | 27 - .../basicmodel/handling/ApexModelCreator.java | 39 -- .../basicmodel/handling/ApexModelException.java | 51 -- .../basicmodel/handling/ApexModelFileWriter.java | 139 ----- .../model/basicmodel/handling/ApexModelReader.java | 279 ---------- .../model/basicmodel/handling/ApexModelSaver.java | 95 ---- .../basicmodel/handling/ApexModelStringWriter.java | 149 ------ .../model/basicmodel/handling/ApexModelWriter.java | 278 ---------- .../basicmodel/handling/ApexSchemaGenerator.java | 166 ------ .../model/basicmodel/handling/package-info.java | 37 -- .../onap/apex/model/basicmodel/package-info.java | 29 -- .../basicmodel/service/AbstractParameters.java | 85 --- .../model/basicmodel/service/ModelService.java | 106 ---- .../model/basicmodel/service/ParameterService.java | 116 ----- .../model/basicmodel/service/package-info.java | 26 - .../apex/model/basicmodel/test/TestApexModel.java | 332 ------------ .../basicmodel/test/TestApexModelCreator.java | 62 --- .../apex/model/basicmodel/test/package-info.java | 26 - .../basicmodel/xml/AxReferenceKeyAdapter.java | 61 --- .../apex/model/basicmodel/xml/package-info.java | 34 -- .../basicmodel/concepts/ApexConceptException.java | 49 ++ .../model/basicmodel/concepts/ApexException.java | 102 ++++ .../basicmodel/concepts/ApexRuntimeException.java | 101 ++++ .../model/basicmodel/concepts/AxArtifactKey.java | 384 ++++++++++++++ .../apex/model/basicmodel/concepts/AxConcept.java | 139 +++++ .../model/basicmodel/concepts/AxConceptGetter.java | 77 +++ .../basicmodel/concepts/AxConceptGetterImpl.java | 154 ++++++ .../apex/model/basicmodel/concepts/AxKey.java | 106 ++++ .../apex/model/basicmodel/concepts/AxKeyInfo.java | 365 +++++++++++++ .../basicmodel/concepts/AxKeyInformation.java | 460 ++++++++++++++++ .../apex/model/basicmodel/concepts/AxKeyUse.java | 252 +++++++++ .../apex/model/basicmodel/concepts/AxModel.java | 479 +++++++++++++++++ .../model/basicmodel/concepts/AxReferenceKey.java | 579 +++++++++++++++++++++ .../basicmodel/concepts/AxValidationMessage.java | 105 ++++ .../basicmodel/concepts/AxValidationResult.java | 152 ++++++ .../model/basicmodel/concepts/package-info.java | 34 ++ .../policy/apex/model/basicmodel/dao/ApexDao.java | 207 ++++++++ .../apex/model/basicmodel/dao/ApexDaoFactory.java | 68 +++ .../apex/model/basicmodel/dao/DAOParameters.java | 125 +++++ .../dao/converters/CDATAConditioner.java | 91 ++++ .../basicmodel/dao/converters/UUID2String.java | 83 +++ .../basicmodel/dao/converters/package-info.java | 28 + .../model/basicmodel/dao/impl/DefaultApexDao.java | 520 ++++++++++++++++++ .../model/basicmodel/dao/impl/package-info.java | 26 + .../apex/model/basicmodel/dao/package-info.java | 29 ++ .../basicmodel/handling/ApexModelCreator.java | 39 ++ .../basicmodel/handling/ApexModelException.java | 51 ++ .../basicmodel/handling/ApexModelFileWriter.java | 139 +++++ .../model/basicmodel/handling/ApexModelReader.java | 279 ++++++++++ .../model/basicmodel/handling/ApexModelSaver.java | 95 ++++ .../basicmodel/handling/ApexModelStringWriter.java | 149 ++++++ .../model/basicmodel/handling/ApexModelWriter.java | 278 ++++++++++ .../basicmodel/handling/ApexSchemaGenerator.java | 166 ++++++ .../model/basicmodel/handling/package-info.java | 36 ++ .../policy/apex/model/basicmodel/package-info.java | 29 ++ .../basicmodel/service/AbstractParameters.java | 85 +++ .../model/basicmodel/service/ModelService.java | 106 ++++ .../model/basicmodel/service/ParameterService.java | 116 +++++ .../model/basicmodel/service/package-info.java | 26 + .../apex/model/basicmodel/test/TestApexModel.java | 332 ++++++++++++ .../basicmodel/test/TestApexModelCreator.java | 62 +++ .../apex/model/basicmodel/test/package-info.java | 26 + .../basicmodel/xml/AxReferenceKeyAdapter.java | 63 +++ .../apex/model/basicmodel/xml/package-info.java | 34 ++ .../basic-model/src/main/resources/xml/example.xsd | 2 +- .../apex/model/basicmodel/concepts/AxKeyTest.java | 119 ----- .../model/basicmodel/concepts/TestAxKeyInfo.java | 108 ---- .../basicmodel/concepts/TestAxReferenceKey.java | 112 ---- .../apex/model/basicmodel/concepts/TestEntity.java | 175 ------- .../model/basicmodel/concepts/TestExceptions.java | 70 --- .../model/basicmodel/concepts/TestValidation.java | 93 ---- .../apex/model/basicmodel/concepts/testKeyUse.java | 82 --- .../onap/apex/model/basicmodel/dao/EntityTest.java | 300 ----------- .../apex/model/basicmodel/dao/TestDaoMisc.java | 91 ---- .../basicmodel/handling/AxModelWithReferences.java | 69 --- .../basicmodel/handling/TestApexBasicModel.java | 137 ----- .../handling/TestApexBasicModelConcepts.java | 279 ---------- .../handling/TestApexBasicModelCreator.java | 126 ----- .../handling/TestApexTestModelCreator0.java | 63 --- .../handling/TestApexTestModelCreator1.java | 75 --- .../handling/TestApexTestModelCreator2.java | 63 --- .../basicmodel/handling/TestBasicModelTest.java | 156 ------ .../basicmodel/handling/TestConceptGetter.java | 171 ------ .../model/basicmodel/handling/TestExceptions.java | 44 -- .../basicmodel/handling/TestModelFileWriter.java | 131 ----- .../model/basicmodel/handling/TestModelReader.java | 155 ------ .../model/basicmodel/handling/TestModelSaver.java | 53 -- .../basicmodel/handling/TestModelStringWriter.java | 99 ---- .../model/basicmodel/handling/TestModelWriter.java | 98 ---- .../basicmodel/handling/TestSchemaGenerator.java | 93 ---- .../basicmodel/service/IllegalParameters.java | 32 -- .../model/basicmodel/service/LegalParameters.java | 32 -- .../basicmodel/service/TestAbstractParameters.java | 51 -- .../model/basicmodel/service/TestModelService.java | 78 --- .../basicmodel/service/TestParameterService.java | 77 --- .../basicmodel/xml/TestAxReferenceKeyAdapter.java | 46 -- .../apex/model/basicmodel/concepts/AxKeyTest.java | 119 +++++ .../model/basicmodel/concepts/TestAxKeyInfo.java | 108 ++++ .../basicmodel/concepts/TestAxReferenceKey.java | 112 ++++ .../apex/model/basicmodel/concepts/TestEntity.java | 175 +++++++ .../model/basicmodel/concepts/TestExceptions.java | 70 +++ .../model/basicmodel/concepts/TestValidation.java | 93 ++++ .../apex/model/basicmodel/concepts/testKeyUse.java | 82 +++ .../apex/model/basicmodel/dao/EntityTest.java | 296 +++++++++++ .../apex/model/basicmodel/dao/TestDaoMisc.java | 91 ++++ .../basicmodel/handling/AxModelWithReferences.java | 69 +++ .../basicmodel/handling/TestApexBasicModel.java | 133 +++++ .../handling/TestApexBasicModelConcepts.java | 279 ++++++++++ .../handling/TestApexBasicModelCreator.java | 126 +++++ .../handling/TestApexTestModelCreator0.java | 63 +++ .../handling/TestApexTestModelCreator1.java | 75 +++ .../handling/TestApexTestModelCreator2.java | 63 +++ .../basicmodel/handling/TestBasicModelTest.java | 150 ++++++ .../basicmodel/handling/TestConceptGetter.java | 171 ++++++ .../model/basicmodel/handling/TestExceptions.java | 44 ++ .../basicmodel/handling/TestModelFileWriter.java | 131 +++++ .../model/basicmodel/handling/TestModelReader.java | 155 ++++++ .../model/basicmodel/handling/TestModelSaver.java | 53 ++ .../basicmodel/handling/TestModelStringWriter.java | 99 ++++ .../model/basicmodel/handling/TestModelWriter.java | 98 ++++ .../basicmodel/handling/TestSchemaGenerator.java | 93 ++++ .../basicmodel/service/IllegalParameters.java | 32 ++ .../model/basicmodel/service/LegalParameters.java | 32 ++ .../basicmodel/service/TestAbstractParameters.java | 55 ++ .../model/basicmodel/service/TestModelService.java | 82 +++ .../basicmodel/service/TestParameterService.java | 79 +++ .../basicmodel/xml/TestAxReferenceKeyAdapter.java | 46 ++ .../src/test/resources/META-INF/persistence.xml | 16 +- .../src/test/resources/logback-test.xml | 10 +- model/context-model/pom.xml | 10 +- .../contextmodel/concepts/AxContextAlbum.java | 426 --------------- .../contextmodel/concepts/AxContextAlbums.java | 427 --------------- .../contextmodel/concepts/AxContextModel.java | 346 ------------ .../contextmodel/concepts/AxContextSchema.java | 383 -------------- .../contextmodel/concepts/AxContextSchemas.java | 424 --------------- .../model/contextmodel/concepts/package-info.java | 27 - .../contextmodel/handling/ContextComparer.java | 70 --- .../model/contextmodel/handling/package-info.java | 27 - .../contextmodel/concepts/AxContextAlbum.java | 425 +++++++++++++++ .../contextmodel/concepts/AxContextAlbums.java | 423 +++++++++++++++ .../contextmodel/concepts/AxContextModel.java | 345 ++++++++++++ .../contextmodel/concepts/AxContextSchema.java | 379 ++++++++++++++ .../contextmodel/concepts/AxContextSchemas.java | 419 +++++++++++++++ .../model/contextmodel/concepts/package-info.java | 28 + .../contextmodel/handling/ContextComparer.java | 70 +++ .../model/contextmodel/handling/package-info.java | 27 + .../contextmodel/concepts/TestContextAlbums.java | 210 -------- .../contextmodel/concepts/TestContextModel.java | 82 --- .../contextmodel/concepts/TestContextSchemas.java | 196 ------- .../handling/TestApexContextModel.java | 127 ----- .../handling/TestApexContextModelCreator.java | 106 ---- .../handling/TestContextComparison.java | 164 ------ .../handling/TestContextComparisonFactory.java | 122 ----- .../contextmodel/concepts/TestContextAlbums.java | 210 ++++++++ .../contextmodel/concepts/TestContextModel.java | 82 +++ .../contextmodel/concepts/TestContextSchemas.java | 196 +++++++ .../handling/TestApexContextModel.java | 127 +++++ .../handling/TestApexContextModelCreator.java | 123 +++++ .../handling/TestContextComparison.java | 164 ++++++ .../handling/TestContextComparisonFactory.java | 132 +++++ .../src/test/resources/META-INF/persistence.xml | 26 +- .../src/test/resources/json/ContextModel.json | 10 +- .../src/test/resources/logback-test.xml | 8 +- model/event-model/pom.xml | 67 +++ .../apex/model/eventmodel/concepts/AxEvent.java | 560 ++++++++++++++++++++ .../model/eventmodel/concepts/AxEventModel.java | 330 ++++++++++++ .../apex/model/eventmodel/concepts/AxEvents.java | 420 +++++++++++++++ .../apex/model/eventmodel/concepts/AxField.java | 406 +++++++++++++++ .../model/eventmodel/concepts/AxInputField.java | 104 ++++ .../model/eventmodel/concepts/AxOutputField.java | 104 ++++ .../model/eventmodel/concepts/package-info.java | 34 ++ .../model/eventmodel/concepts/TestEventModel.java | 89 ++++ .../apex/model/eventmodel/concepts/TestEvents.java | 298 +++++++++++ .../apex/model/eventmodel/concepts/TestField.java | 136 +++++ .../eventmodel/handling/TestApexEventModel.java | 184 +++++++ .../handling/TestApexEventModelCreator.java | 309 +++++++++++ .../src/test/resources/META-INF/persistence.xml | 56 ++ .../src/test/resources/logback-test.xml | 74 +++ model/pom.xml | 12 +- pom.xml | 3 +- 206 files changed, 16474 insertions(+), 13213 deletions(-) delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexConceptException.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexException.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexRuntimeException.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxArtifactKey.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConcept.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetter.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetterImpl.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKey.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInfo.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInformation.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyUse.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxModel.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxReferenceKey.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationMessage.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationResult.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDao.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDaoFactory.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/DAOParameters.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/CDATAConditioner.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/UUID2String.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/DefaultApexDao.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelCreator.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelException.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelFileWriter.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelReader.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelSaver.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelStringWriter.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelWriter.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexSchemaGenerator.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/AbstractParameters.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ModelService.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ParameterService.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModel.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModelCreator.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/package-info.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java delete mode 100644 model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexConceptException.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxArtifactKey.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetter.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImpl.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyUse.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxReferenceKey.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationMessage.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationResult.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDao.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDaoFactory.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/DAOParameters.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/CDATAConditioner.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/UUID2String.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelCreator.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelException.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelFileWriter.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelSaver.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelStringWriter.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexSchemaGenerator.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/AbstractParameters.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ModelService.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ParameterService.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModel.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModelCreator.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/package-info.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java create mode 100644 model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/package-info.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/AxKeyTest.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxKeyInfo.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxReferenceKey.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestEntity.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestExceptions.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestValidation.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/testKeyUse.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/EntityTest.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/TestDaoMisc.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/AxModelWithReferences.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModel.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelCreator.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator0.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator1.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator2.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestBasicModelTest.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestConceptGetter.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestExceptions.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelFileWriter.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelReader.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelSaver.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelStringWriter.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelWriter.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestSchemaGenerator.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/IllegalParameters.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/LegalParameters.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestAbstractParameters.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestModelService.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestParameterService.java delete mode 100644 model/basic-model/src/test/java/org/onap/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyTest.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxKeyInfo.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxReferenceKey.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestEntity.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestExceptions.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestValidation.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/testKeyUse.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/EntityTest.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/TestDaoMisc.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/AxModelWithReferences.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModel.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelCreator.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator0.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator1.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator2.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestBasicModelTest.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestConceptGetter.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestExceptions.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelFileWriter.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelReader.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelSaver.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelStringWriter.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelWriter.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestSchemaGenerator.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/IllegalParameters.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/LegalParameters.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestAbstractParameters.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestModelService.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestParameterService.java create mode 100644 model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbum.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbums.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextModel.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchema.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchemas.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/package-info.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/ContextComparer.java delete mode 100644 model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/package-info.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchema.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchemas.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/package-info.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/ContextComparer.java create mode 100644 model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/package-info.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextAlbums.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextModel.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextSchemas.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModel.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModelCreator.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparison.java delete mode 100644 model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparisonFactory.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextAlbums.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextModel.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextSchemas.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModel.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModelCreator.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparison.java create mode 100644 model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparisonFactory.java create mode 100644 model/event-model/pom.xml create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvent.java create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvents.java create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxInputField.java create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxOutputField.java create mode 100644 model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/package-info.java create mode 100644 model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEventModel.java create mode 100644 model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEvents.java create mode 100644 model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestField.java create mode 100644 model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModel.java create mode 100644 model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModelCreator.java create mode 100644 model/event-model/src/test/resources/META-INF/persistence.xml create mode 100644 model/event-model/src/test/resources/logback-test.xml diff --git a/.gitignore b/.gitignore index 236c0b3b4..3a9735328 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ target .metadata/ /bin/ +derby.log diff --git a/model/basic-model/pom.xml b/model/basic-model/pom.xml index cedb576ad..d663f92b2 100644 --- a/model/basic-model/pom.xml +++ b/model/basic-model/pom.xml @@ -43,12 +43,6 @@ eclipselink 2.6.2 - - org.apache.derby - derby - 10.13.1.1 - test - @@ -64,10 +58,10 @@ java - org.onap.apex.model.basicmodel.handling.ApexSchemaGenerator + org.onap.policy.apex.model.basicmodel.handling.ApexSchemaGenerator compile - org.onap.apex.model.basicmodel.concepts.AxModel + org.onap.policy.apex.model.basicmodel.concepts.AxModel ${project.build.directory}/model/xml/apex-basic-model.xsd diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexConceptException.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexConceptException.java deleted file mode 100644 index bfe296d97..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexConceptException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -/** - * This class is an exception thrown on Apex Concept errors. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexConceptException extends ApexException { - private static final long serialVersionUID = -8507246953751956974L; - - /** - * Instantiates a new apex concept exception. - * - * @param message the message on the exception - */ - public ApexConceptException(final String message) { - super(message); - } - - /** - * Instantiates a new apex concept exception. - * - * @param message the message on the exception - * @param e the exception that caused this Apex exception - */ - public ApexConceptException(final String message, final Exception e) { - super(message, e); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexException.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexException.java deleted file mode 100644 index 74a60e243..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexException.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -/** - * This class is a base exception from which all Apex exceptions are sub classes. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexException extends Exception { - private static final long serialVersionUID = -8507246953751956974L; - - // The object on which the exception was thrown - private transient Object object = null; - - /** - * Instantiates a new apex exception. - * - * @param message the message on the exception - */ - public ApexException(final String message) { - super(message); - } - - /** - * Instantiates a new apex exception. - * - * @param message the message on the exception - * @param object the object that the exception was thrown on - */ - public ApexException(final String message, final Object object) { - super(message); - this.object = object; - } - - /** - * Instantiates a new apex exception. - * - * @param message the message on the exception - * @param e the exception that caused this Apex exception - */ - public ApexException(final String message, final Exception e) { - super(message, e); - } - - /** - * Instantiates a new apex exception. - * - * @param message the message on the exception - * @param e the exception that caused this Apex exception - * @param object the object that the exception was thrown on - */ - public ApexException(final String message, final Exception e, final Object object) { - super(message, e); - this.object = object; - } - - /** - * Get the message from this exception and its causes. - * - * @return the cascaded messages from this exception and the exceptions that caused it - */ - public String getCascadedMessage() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getMessage()); - - for (Throwable t = this; t != null; t = t.getCause()) { - builder.append("\ncaused by: "); - builder.append(t.getMessage()); - } - - return builder.toString(); - } - - /** - * - * Get the object on which the exception was thrown. - * - * @return The object on which the exception was thrown - */ - public Object getObject() { - return object; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexRuntimeException.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexRuntimeException.java deleted file mode 100644 index 4cdfbe4b0..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/ApexRuntimeException.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -/** - * This class is a base run time exception from which all Apex run time exceptions are sub classes. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexRuntimeException extends RuntimeException { - private static final long serialVersionUID = -8507246953751956974L; - - // The object on which the exception was thrown - private transient Object object = null; - - /** - * Instantiates a new apex runtime exception. - * - * @param message the message on the exception - */ - public ApexRuntimeException(final String message) { - super(message); - } - - /** - * Instantiates a new apex runtime exception. - * - * @param message the message on the exception - * @param object the object that the exception was thrown on - */ - public ApexRuntimeException(final String message, final Object object) { - super(message); - this.object = object; - } - - /** - * Instantiates a new apex runtime exception. - * - * @param message the message on the exception - * @param e the exception that caused this Apex exception - */ - public ApexRuntimeException(final String message, final Exception e) { - super(message, e); - } - - /** - * Instantiates a new apex runtime exception. - * - * @param message the message on the exception - * @param e the exception that caused this Apex exception - * @param object the object that the exception was thrown on - */ - public ApexRuntimeException(final String message, final Exception e, final Object object) { - super(message, e); - this.object = object; - } - - /** - * Get the message from this exception and its causes. - * - * @return the message of this exception and all the exceptions that caused this exception - */ - public String getCascadedMessage() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getMessage()); - - for (Throwable t = this; t != null; t = t.getCause()) { - builder.append("\ncaused by: "); - builder.append(t.getMessage()); - } - - return builder.toString(); - } - - /** - * Get the object on which the exception was thrown. - * - * @return The object - */ - public Object getObject() { - return object; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxArtifactKey.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxArtifactKey.java deleted file mode 100644 index 1de7ae72e..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxArtifactKey.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * An artifact key uniquely identifies every first order entity in the system. Every first order concept in the system must have - * an {@link AxArtifactKey} to identify it. Concepts that are wholly contained in another concept are identified using - * a {@link AxReferenceKey} key. - *

- * Key validation checks that the name and version fields match the {@link NAME_REGEXP} and {@link VERSION_REGEXP} regular expressions respectively. - */ -@Embeddable -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "apexArtifactKey", namespace = "http://www.ericsson.com/apex") - -@XmlType(name = "AxArtifactKey", namespace = "http://www.ericsson.com/apex", propOrder = { "name", "version" }) - -public class AxArtifactKey extends AxKey { - private static final long serialVersionUID = 8932717618579392561L; - - private static final String NAME_TOKEN = "name"; - private static final String VERSION_TOKEN = "version"; - - @Column(name = NAME_TOKEN) - @XmlElement(required = true) - private String name; - - @Column(name = VERSION_TOKEN) - @XmlElement(required = true) - private String version; - - /** - * The default constructor creates a null artifact key. - */ - public AxArtifactKey() { - this(NULL_KEY_NAME, NULL_KEY_VERSION); - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxArtifactKey(final AxArtifactKey copyConcept) { - super(copyConcept); - } - - /** - * Constructor to create a key with the specified name and version. - * - * @param name the key name - * @param version the key version - */ - public AxArtifactKey(final String name, final String version) { - super(); - this.name = Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); - this.version = Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); - } - - /** - * Constructor to create a key using the key and version from the specified key ID. - * - * @param id the key ID in a format that respects the {@link KEY_ID_REGEXP} - */ - public AxArtifactKey(final String id) { - Assertions.argumentNotNull(id, "id may not be null"); - - // Check the incoming ID is valid - Assertions.validateStringParameter("id", id, KEY_ID_REGEXP); - - // Split on colon, if the id passes the regular expression test above - // it'll have just one colon separating the name and version - // No need for range checks or size checks on the array - final String[] nameVersionArray = id.split(":"); - - // Return the new key - name = Assertions.validateStringParameter(NAME_TOKEN, nameVersionArray[0], NAME_REGEXP); - version = Assertions.validateStringParameter(VERSION_TOKEN, nameVersionArray[1], VERSION_REGEXP); - } - - /** - * Get a null artifact key. - * - * @return a null artifact key - */ - public static final AxArtifactKey getNullKey() { - return new AxArtifactKey(AxKey.NULL_KEY_NAME, AxKey.NULL_KEY_VERSION); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return this; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = new ArrayList<>(); - keyList.add(getKey()); - return keyList; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#getID() - */ - @Override - public String getID() { - return name + ':' + version; - } - - /** - * Gets the key name. - * - * @return the key name - */ - public String getName() { - return name; - } - - /** - * Sets the key name. - * - * @param name the key name - */ - public void setName(final String name) { - this.name = Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); - } - - /** - * Gets the key version. - * - * @return the key version - */ - public String getVersion() { - return version; - } - - /** - * Sets the key version. - * - * @param version the key version - */ - public void setVersion(final String version) { - this.version = Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#getCompatibility(com. ericsson.apex.model.basicmodel.concepts.AxKey) - */ - @Override - public AxKey.Compatibility getCompatibility(final AxKey otherKey) { - if (!(otherKey instanceof AxArtifactKey)) { - return Compatibility.DIFFERENT; - } - final AxArtifactKey otherArtifactKey = (AxArtifactKey) otherKey; - - if (this.equals(otherArtifactKey)) { - return Compatibility.IDENTICAL; - } - if (!this.getName().equals(otherArtifactKey.getName())) { - return Compatibility.DIFFERENT; - } - - final String[] thisVersionArray = getVersion().split("\\."); - final String[] otherVersionArray = otherArtifactKey.getVersion().split("\\."); - - // There must always be at least one element in each version - if (!thisVersionArray[0].equals(otherVersionArray[0])) { - return Compatibility.MAJOR; - } - - if (thisVersionArray.length >= 2 && otherVersionArray.length >= 2 && !thisVersionArray[1].equals(otherVersionArray[1])) { - return Compatibility.MINOR; - } - - return Compatibility.PATCH; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#isCompatible(com. ericsson.apex.model.basicmodel.concepts.AxKey) - */ - @Override - public boolean isCompatible(final AxKey otherKey) { - if (!(otherKey instanceof AxArtifactKey)) { - return false; - } - final AxArtifactKey otherArtifactKey = (AxArtifactKey) otherKey; - - final Compatibility compatibility = this.getCompatibility(otherArtifactKey); - - return !(compatibility == Compatibility.DIFFERENT || compatibility == Compatibility.MAJOR); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com. ericsson.apex.model.basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult result) { - try { - Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); - } - catch (final IllegalArgumentException e) { - result.addValidationMessage( - new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, "name invalid-" + e.getMessage())); - } - - try { - Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); - } - catch (final IllegalArgumentException e) { - result.addValidationMessage( - new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, "version invalid-" + e.getMessage())); - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - name = Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); - version = Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("name="); - builder.append(name); - builder.append(",version="); - builder.append(version); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final AxConcept copyObject = target; - Assertions.instanceOf(copyObject, AxArtifactKey.class); - - final AxArtifactKey copy = ((AxArtifactKey) copyObject); - copy.setName(name); - copy.setVersion(version); - - return copyObject; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + name.hashCode(); - result = prime * result + version.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - - final AxArtifactKey other = (AxArtifactKey) obj; - - if (!name.equals(other.name)) { - return false; - } - return version.equals(other.version); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - Assertions.argumentNotNull(otherObj, "comparison object may not be null"); - - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxArtifactKey other = (AxArtifactKey) otherObj; - - if (!name.equals(other.name)) { - return name.compareTo(other.name); - } - return version.compareTo(other.version); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConcept.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConcept.java deleted file mode 100644 index 005d17d76..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConcept.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.io.Serializable; -import java.util.List; - -import javax.xml.bind.annotation.XmlType; - -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class is the base class for all Apex concept classes. It enforces implementation of abstract methods and interfaces on all concepts - * that are sub-classes of this class. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ - -@XmlType(name = "AxConcept", namespace = "http://www.ericsson.com/apex") - -public abstract class AxConcept implements Serializable, Comparable { - private static final long serialVersionUID = -7434939557282697490L; - - /** - * Default constructor - */ - public AxConcept() { - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxConcept(final AxConcept copyConcept) { - Assertions.argumentNotNull(copyConcept, "copy concept may not be null"); - copyConcept.copyTo(this); - } - - /** - * Gets the key of this concept. - * - * @return the concept key - */ - public abstract AxKey getKey(); - - /** - * Gets a list of all keys for this concept and all concepts that are defined or referenced by this concept and its sub-concepts. - * - * @return the keys used by this concept and it's contained concepts - */ - public abstract List getKeys(); - - /** - * Validate that this concept is structurally correct. - * - * @param result the parameter in which the result of the validation will be returned - * @return the validation result that was passed in in the @{link result} field with the result of this validation added - */ - public abstract AxValidationResult validate(AxValidationResult result); - - /** - * Clean this concept, tidy up any superfluous information such as leading and trailing white space. - */ - public abstract void clean(); - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public abstract boolean equals(Object otherObject); - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public abstract String toString(); - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public abstract int hashCode(); - - /** - * Copy this concept to another object. The target object must have the same class as the source object. - * - * @param target the target object to which this object is copied - * @return the copied object - */ - public abstract AxConcept copyTo(AxConcept target); - - /** - * Gets the ID string of this concept. - * - * @return the ID string of this concept - */ - public String getID() { - return getKey().getID(); - } - - /** - * Checks if this key matches the given key ID. - * - * @param id the key ID to match against - * @return true, if this key matches the ID - */ - public final boolean matchesID(final String id) { - Assertions.argumentNotNull(id, "id may not be null"); - - // Check the ID - return getID().equals(id); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetter.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetter.java deleted file mode 100644 index d5d1752e6..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetter.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.Set; - -/** - * This interface is used to allow get methods to be placed on concepts that have embedded maps. - *

- * It forces those concepts with maps to implement the get methods specified on this interface as convenience methods to avoid concept users having to use a - * second level of referencing to access concepts in the the maps. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of concept on which the interface is applied. - */ -public interface AxConceptGetter { - - /** - * Get the latest version for a concept with the given key. - * - * @param conceptKey The key of the concept - * @return The concept - */ - C get(AxArtifactKey conceptKey); - - /** - * Get the latest version for a concept with the given key name. - * - * @param conceptKeyName The name of the concept - * @return The concept - */ - C get(String conceptKeyName); - - /** - * Get the latest version for a concept with the given key name and version. - * - * @param conceptKeyName The name of the concept - * @param conceptKeyVersion The version of the concept - * @return The concept - */ - C get(String conceptKeyName, String conceptKeyVersion); - - /** - * Get the all versions for a concept with the given key name. - * - * @param conceptKeyName The name of the concept - * @return The concepts - */ - Set getAll(String conceptKeyName); - - /** - * Get the all versions for a concept with the given key name and starting version. - * - * @param conceptKeyName The name of the concept - * @param conceptKeyVersion The first version version of the concept to get - * @return The concepts - */ - Set getAll(String conceptKeyName, String conceptKeyVersion); -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetterImpl.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetterImpl.java deleted file mode 100644 index af9764113..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxConceptGetterImpl.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.NavigableMap; -import java.util.Set; -import java.util.TreeSet; - -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * Implements concept getting from navigable maps. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of concept on which the interface implementation is applied. - */ -public class AxConceptGetterImpl implements AxConceptGetter { - - // The map from which to get concepts - private final NavigableMap conceptMap; - - /** - * Constructor that sets the concept map on which the getter methods in the interface will operate.. - * - * @param conceptMap the concept map on which the method will operate - */ - public AxConceptGetterImpl(final NavigableMap conceptMap) { - this.conceptMap = conceptMap; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(com. ericsson.apex.core.basicmodel.concepts.AxArtifactKey) - */ - @Override - public C get(final AxArtifactKey conceptKey) { - return conceptMap.get(conceptKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String) - */ - @Override - public C get(final String conceptKeyName) { - Assertions.argumentNotNull(conceptKeyName, "conceptKeyName may not be null"); - - // The very fist key that could have this name - final AxArtifactKey lowestArtifactKey = new AxArtifactKey(conceptKeyName, "0.0.1"); - - // Check if we found a key for our name - AxArtifactKey foundKey = conceptMap.ceilingKey(lowestArtifactKey); - if (foundKey == null || !foundKey.getName().equals(conceptKeyName)) { - return null; - } - - // Look for higher versions of the key - do { - final AxArtifactKey nextkey = conceptMap.higherKey(foundKey); - if (nextkey == null || !nextkey.getName().equals(conceptKeyName)) { - break; - } - foundKey = nextkey; - } - while (true); - - return conceptMap.get(foundKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String, java.lang.String) - */ - @Override - public C get(final String conceptKeyName, final String conceptKeyVersion) { - Assertions.argumentNotNull(conceptKeyName, "conceptKeyName may not be null"); - - if (conceptKeyVersion != null) { - return conceptMap.get(new AxArtifactKey(conceptKeyName, conceptKeyVersion)); - } - else { - return this.get(conceptKeyName); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String) - */ - @Override - public Set getAll(final String conceptKeyName) { - return getAll(conceptKeyName, null); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String, java.lang.String) - */ - @Override - public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { - final Set returnSet = new TreeSet<>(); - - if (conceptKeyName == null) { - returnSet.addAll(conceptMap.values()); - return returnSet; - } - - // The very fist key that could have this name - final AxArtifactKey lowestArtifactKey = new AxArtifactKey(conceptKeyName, "0.0.1"); - if (conceptKeyVersion != null) { - lowestArtifactKey.setVersion(conceptKeyVersion); - } - - // Check if we found a key for our name - AxArtifactKey foundKey = conceptMap.ceilingKey(lowestArtifactKey); - if (foundKey == null || !foundKey.getName().equals(conceptKeyName)) { - return returnSet; - } - returnSet.add(conceptMap.get(foundKey)); - - // Look for higher versions of the key - do { - foundKey = conceptMap.higherKey(foundKey); - if (foundKey == null || !foundKey.getName().equals(conceptKeyName)) { - break; - } - returnSet.add(conceptMap.get(foundKey)); - } - while (true); - - return returnSet; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKey.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKey.java deleted file mode 100644 index 0d63dbf7d..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKey.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -/** - * The key uniquely identifies every entity in the system. This class is an abstract class to give a common parent for all key types in the - * system. - */ -public abstract class AxKey extends AxConcept { - private static final long serialVersionUID = 6281159885962014041L; - - /** Regular expression to specify the structure of key names. */ - public static final String NAME_REGEXP = "[A-Za-z0-9\\-_\\.]+"; - - /** Regular expression to specify the structure of key versions. */ - public static final String VERSION_REGEXP = "[A-Za-z0-9.]+"; - - /** Regular expression to specify the structure of key IDs. */ - public static final String KEY_ID_REGEXP = "[A-Za-z0-9\\-_\\.]+:[0-9].[0-9].[0-9]"; - - /** Specifies the value for names in NULL keys. */ - public static final String NULL_KEY_NAME = "NULL"; - - /** Specifies the value for versions in NULL keys. */ - public static final String NULL_KEY_VERSION = "0.0.0"; - - /** - * This enumeration is returned on key compatibility checks. - */ - public enum Compatibility { - /** The keys have different names. */ - DIFFERENT, - /** The name of the key matches but the Major version number of the keys is different (x in x.y.z do not match). */ - MAJOR, - /** The name of the key matches but the Minor version number of the keys is different (y in x.y.z do not match). */ - MINOR, - /** The name of the key matches but the Patch version number of the keys is different (z in x.y.z do not match). */ - PATCH, - /** The keys match completely. */ - IDENTICAL - } - - /** - * Default constructor - */ - public AxKey() { - super(); - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxKey(final AxKey copyConcept) { - super(copyConcept); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getID() - */ - @Override - public abstract String getID(); - - /** - * Return the result of a compatibility check of two keys. - * - * @param otherKey the key to check compatibility against - * @return the compatibility result of the check - */ - public abstract Compatibility getCompatibility(AxKey otherKey); - - /** - * Check if two keys are compatible, that is the keys are IDENTICAL or have only MINOR, PATCH differences. - * - * @param otherKey the key to check compatibility against - * @return true, if the keys are compatible - */ - public abstract boolean isCompatible(AxKey otherKey); -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInfo.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInfo.java deleted file mode 100644 index 1ffb40b27..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInfo.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.List; -import java.util.Random; -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.Convert; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.apex.model.basicmodel.dao.converters.CDATAConditioner; -import org.onap.apex.model.basicmodel.dao.converters.UUID2String; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * The key information on an {@link AxArtifactKey} key in an Apex policy model. Each {@link AxArtifactKey} must have an {@link AxKeyInfo} object. THe - * information held is the key's UUID and it's description. - *

- * Validation checks that all fields are defined and that the key is valid. It also observes that descriptions are blank and warns if the UUID is a zero UUID. - */ - -@Entity -@Table(name = "AxKeyInfo") - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "apexKeyInfo", namespace = "http://www.ericsson.com/apex") -@XmlType(name = "AxKeyInfo", namespace = "http://www.ericsson.com/apex", propOrder = { "key", "uuid", "description" }) - -public class AxKeyInfo extends AxConcept { - private static final long serialVersionUID = -4023935924068914308L; - - private static final int MAX_DESCRIPTION_LENGTH_8192 = 8192; - private static final int UUID_BYTE_LENGTH_16 = 16; - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - @Column(name = "uuid") - @Convert(converter = UUID2String.class) - @XmlJavaTypeAdapter(value = UUID2String.class) - @XmlElement(name = "UUID", required = true) - private UUID uuid; - - @Column(name = "description", length = MAX_DESCRIPTION_LENGTH_8192) - @Convert(converter = CDATAConditioner.class) - @XmlJavaTypeAdapter(value = CDATAConditioner.class) - @XmlElement(required = true) - private String description; - - /** - * The Default Constructor creates this concept with a NULL artifact key. - */ - public AxKeyInfo() { - this(new AxArtifactKey()); - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxKeyInfo(final AxKeyInfo copyConcept) { - super(copyConcept); - } - - /** - * Constructor to create this concept with the specified key. - * - * @param key the key of the concept - */ - public AxKeyInfo(final AxArtifactKey key) { - this(key, UUID.randomUUID(), "Generated description for concept referred to by key \"" + key.getID() + "\""); - } - - /** - * Constructor to create this concept and set all its fields. - * - * @param key the key of the concept - * @param uuid the UUID of the concept - * @param description the description of the concept - */ - public AxKeyInfo(final AxArtifactKey key, final UUID uuid, final String description) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(uuid, "uuid may not be null"); - Assertions.argumentNotNull(description, "description may not be null"); - - this.key = key; - this.uuid = uuid; - this.description = description.trim(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - return key.getKeys(); - } - - /** - * Sets the key of the concept. - * - * @param key the concept key - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the UUID of the concept. - * - * @return the uuid of the concept - */ - public UUID getUUID() { - return uuid; - } - - /** - * Sets the UUID of the concept. - * - * @param uuid the uuid of the concept - */ - public void setUuid(final UUID uuid) { - Assertions.argumentNotNull(uuid, "uuid may not be null"); - this.uuid = uuid; - } - - /** - * Gets the description of the concept. - * - * @return the description of the concept - */ - public String getDescription() { - return description; - } - - /** - * Sets the description of the concept. - * - * @param description the description of the concept - */ - public void setDescription(final String description) { - Assertions.argumentNotNull(description, "description may not be null"); - this.description = description.trim(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com. ericsson.apex.model.basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - - result = key.validate(result); - - if (description.trim().length() == 0) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.OBSERVATION, "description is blank")); - } - - if (uuid.equals(new UUID(0, 0))) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.WARNING, "UUID is a zero UUID: " + new UUID(0, 0))); - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - description = description.trim(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("artifactId="); - builder.append(key); - builder.append(",uuid="); - builder.append(uuid); - builder.append(",description="); - builder.append(description); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxKeyInfo.class); - - final AxKeyInfo copy = ((AxKeyInfo) copyObject); - copy.setKey(new AxArtifactKey(key)); - copy.setUuid(UUID.fromString(uuid.toString())); - copy.setDescription(description); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + uuid.hashCode(); - result = prime * result + description.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - - final AxKeyInfo other = (AxKeyInfo) obj; - if (!key.equals(other.key)) { - return false; - } - if (!uuid.equals(other.uuid)) { - return false; - } - final String thisdesc = CDATAConditioner.clean(description); - final String otherdesc = CDATAConditioner.clean(other.description); - return thisdesc.equals(otherdesc); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxKeyInfo other = (AxKeyInfo) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - if (!uuid.equals(other.uuid)) { - return uuid.compareTo(other.uuid); - } - return description.compareTo(other.description); - } - - /** - * Generate a reproducible UUID for a given string seed. - * - * @param seed the seed - * @return the uuid - */ - public static UUID generateReproducibleUUID(final String seed) { - final Random random; - if (seed != null && seed.length() > 0) { - random = new Random(seed.hashCode()); - } - else { - random = new Random(); - } - byte[] array = new byte[UUID_BYTE_LENGTH_16]; - random.nextBytes(array); - return UUID.nameUUIDFromBytes(array); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInformation.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInformation.java deleted file mode 100644 index 3082c4f5d..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyInformation.java +++ /dev/null @@ -1,448 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.Set; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.UUID; - -import javax.persistence.CascadeType; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * The Class AxKeyInformation holds a map of the key information for the entire Apex model. All Apex models {@link AxModel} must have an - * {@link AxKeyInformation} field. The {@link AxKeyInformation} class implements the helper methods of the {@link AxConceptGetter} interface to allow - * {@link AxKeyInfo} instances to be retrieved by calling methods directly on this class without referencing the contained map. - *

- * Validation checks that the key is not null, that the key information map is not empty, that each key and value in the map is defined, that the key in each - * map entry matches the key if each entry value, and that no duplicate UUIDs exist. Each key information entry is then validated individually. - */ -@Entity -@Table(name = "AxKeyInformation") - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "AxKeyInformation", namespace = "http://www.ericsson.com/apex", propOrder = { "key", "keyInfoMap" }) - -public class AxKeyInformation extends AxConcept implements AxConceptGetter { - private static final long serialVersionUID = -2746380769017043888L; - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - // @formatter:off - @ManyToMany(cascade = CascadeType.ALL) - @JoinTable( - joinColumns = { - @JoinColumn(name = "keyInfoMapName", referencedColumnName = "name"), - @JoinColumn(name = "keyInfoMapVersion", referencedColumnName = "version"), - }, - inverseJoinColumns = { - @JoinColumn(name = "keyInfoName", referencedColumnName = "name"), - @JoinColumn(name = "keyInfoVersion", referencedColumnName = "version") - }) - private Map keyInfoMap; - // @formatter:on - - /** - * The Default Constructor creates this concept with a null key. - */ - public AxKeyInformation() { - this(new AxArtifactKey()); - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxKeyInformation(final AxKeyInformation copyConcept) { - super(copyConcept); - } - - /** - * Constructor to create this concept with the specified key. - * - * @param key the key of the concept - */ - public AxKeyInformation(final AxArtifactKey key) { - this(key, new TreeMap()); - } - - /** - * Constructor to create this concept and set all its fields. - * - * @param key the key of the concept - * @param keyInfoMap the key info map of the concept - */ - public AxKeyInformation(final AxArtifactKey key, final Map keyInfoMap) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(keyInfoMap, "keyInfoMap may not be null"); - - this.key = key; - this.keyInfoMap = new TreeMap<>(); - this.keyInfoMap.putAll(keyInfoMap); - } - - /** - * When a model is unmarshalled from disk or from the database, the key information map is returned as a raw Hash Map. This method is called by JAXB - * after unmarshaling and is used to convert the hash map to a {@link NavigableMap} so that it will work with the {@link AxConceptGetter} interface. - * - * @param u the unmarshaler that is unmarshaling the model - * @param parent the parent object of this object in the unmarshaler - */ - public void afterUnmarshal(final Unmarshaller u, final Object parent) { - // The map must be navigable to allow name and version searching, - // unmarshaling returns a hash map - final NavigableMap navigablekeyInfoMap = new TreeMap<>(); - navigablekeyInfoMap.putAll(keyInfoMap); - keyInfoMap = navigablekeyInfoMap; - } - - /** - * This method generates default key information for all keys found in the concept passed in as a parameter that do not already have key information. - * - * @param concept the concept for which to generate key information - */ - public void generateKeyInfo(final AxConcept concept) { - for (final AxKey axKey : concept.getKeys()) { - if (!(axKey instanceof AxArtifactKey)) { - continue; - } - - final AxArtifactKey artifactKey = (AxArtifactKey) axKey; - if (!keyInfoMap.containsKey(artifactKey)) { - final AxKeyInfo keyInfo = new AxKeyInfo(artifactKey); - //generate a reproducible UUID - keyInfo.setUuid(AxKeyInfo.generateReproducibleUUID(keyInfo.getID() + keyInfo.getDescription())); - keyInfoMap.put(artifactKey, keyInfo); - } - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = key.getKeys(); - keyList.addAll(keyInfoMap.keySet()); - - return keyList; - } - - /** - * Sets the key of this concept. - * - * @param key the key of this concept - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the key info map of this concept. - * - * @return the key info map of this concept - */ - public Map getKeyInfoMap() { - return keyInfoMap; - } - - /** - * Sets the key info map of this concept. - * - * @param keyInfoMap the key info map of this concept - */ - public void setKeyInfoMap(final Map keyInfoMap) { - Assertions.argumentNotNull(keyInfoMap, "keyInfoMap may not be null"); - this.keyInfoMap = new TreeMap<>(); - this.keyInfoMap.putAll(keyInfoMap); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com. ericsson.apex.model.basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - - result = key.validate(result); - - if (keyInfoMap.size() == 0) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "keyInfoMap may not be empty")); - } - else { - final Set uuidSet = new TreeSet<>(); - - for (final Entry keyInfoEntry : keyInfoMap.entrySet()) { - result = validateKeyInfoEntry(keyInfoEntry, uuidSet, result); - } - } - - return result; - } - - /** - * Validate an key information entry - * @param keyInfoEntry the key information entry - * @param uuidSet the set of UUIDs encountered in validation so far, the UUID of this entry is added to the set - * @param result the validation result to append to - * @return The validation result - */ - private AxValidationResult validateKeyInfoEntry(final Entry keyInfoEntry, Set uuidSet, AxValidationResult result) { - if (keyInfoEntry.getKey().equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key on keyInfoMap entry " + keyInfoEntry.getKey() + " may not be the null key")); - } - else if (keyInfoEntry.getValue() == null) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "value on keyInfoMap entry " + keyInfoEntry.getKey() + " may not be null")); - } - else { - if (!keyInfoEntry.getKey().equals(keyInfoEntry.getValue().getKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key on keyInfoMap entry " + keyInfoEntry.getKey() + " does not equal entry key " + keyInfoEntry.getValue().getKey())); - } - - result = keyInfoEntry.getValue().validate(result); - - if (uuidSet.contains(keyInfoEntry.getValue().getUUID())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "duplicate UUID found on keyInfoMap entry " + keyInfoEntry.getKey() + ":" + keyInfoEntry.getValue().getUUID())); - } - else { - uuidSet.add(keyInfoEntry.getValue().getUUID()); - } - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - for (final Entry keyInfoEntry : keyInfoMap.entrySet()) { - keyInfoEntry.getKey().clean(); - keyInfoEntry.getValue().clean(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("key="); - builder.append(key); - builder.append(",keyInfoMap="); - builder.append(keyInfoMap); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxKeyInformation.class); - - final AxKeyInformation copy = ((AxKeyInformation) copyObject); - copy.setKey(new AxArtifactKey(key)); - final Map newKeyInfoMap = new TreeMap<>(); - for (final Entry keyInfoMapEntry : keyInfoMap.entrySet()) { - newKeyInfoMap.put(new AxArtifactKey(keyInfoMapEntry.getKey()), new AxKeyInfo(keyInfoMapEntry.getValue())); - } - copy.setKeyInfoMap(newKeyInfoMap); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + keyInfoMap.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - final AxKeyInformation other = (AxKeyInformation) obj; - if (!key.equals(other.key)) { - return false; - } - return keyInfoMap.equals(other.keyInfoMap); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxKeyInformation other = (AxKeyInformation) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - if (!keyInfoMap.equals(other.keyInfoMap)) { - return (keyInfoMap.hashCode() - other.keyInfoMap.hashCode()); - } - - return 0; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(com. ericsson.apex.core.basicmodel.concepts.AxArtifactKey) - */ - @Override - public AxKeyInfo get(final AxArtifactKey conceptKey) { - return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).get(conceptKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String) - */ - @Override - public AxKeyInfo get(final String conceptKeyName) { - return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).get(conceptKeyName); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String, java.lang.String) - */ - @Override - public AxKeyInfo get(final String conceptKeyName, final String conceptKeyVersion) { - return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).get(conceptKeyName, conceptKeyVersion); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String) - */ - @Override - public Set getAll(final String conceptKeyName) { - return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).getAll(conceptKeyName); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String, java.lang.String) - */ - @Override - public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { - return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).getAll(conceptKeyName, conceptKeyVersion); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyUse.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyUse.java deleted file mode 100644 index 990c8f7de..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxKeyUse.java +++ /dev/null @@ -1,245 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.List; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class records a usage of a key in the system. When the list of keys being used by a concept is built using the getKeys() method of - * the {@link AxConcept} class, an instance of this class is created for every key occurrence. The list of keys returned by the getKeys() - * method is a list of {@link AxKeyUse} objects. - *

- * Validation checks that each key is valid. - */ - -public class AxKeyUse extends AxKey { - private static final long serialVersionUID = 2007147220109881705L; - - private AxKey usedKey; - - /** - * The Default Constructor creates this concept with a null key. - */ - public AxKeyUse() { - this(new AxArtifactKey()); - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxKeyUse(final AxKeyUse copyConcept) { - super(copyConcept); - } - - /** - * This constructor creates an instance of this class, and holds a reference to a used key. - * - * @param usedKey a used key - */ - public AxKeyUse(final AxKey usedKey) { - Assertions.argumentNotNull(usedKey, "usedKey may not be null"); - this.usedKey = usedKey; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxKey getKey() { - return usedKey; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - return usedKey.getKeys(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#getID() - */ - @Override - public String getID() { - return usedKey.getID(); - } - - /** - * Sets the key. - * - * @param key the key - */ - public void setKey(final AxKey key) { - Assertions.argumentNotNull(key, "usedKey may not be null"); - this.usedKey = key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#getCompatibility(com. ericsson.apex.model.basicmodel.concepts.AxKey) - */ - @Override - public AxKey.Compatibility getCompatibility(final AxKey otherKey) { - return usedKey.getCompatibility(otherKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#isCompatible(com. ericsson.apex.model.basicmodel.concepts.AxKey) - */ - @Override - public boolean isCompatible(final AxKey otherKey) { - return usedKey.isCompatible(otherKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com. ericsson.apex.model.basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult result) { - if (usedKey.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(usedKey, this.getClass(), ValidationResult.INVALID, "usedKey is a null key")); - } - return usedKey.validate(result); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - usedKey.clean(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("usedKey="); - builder.append(usedKey); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxKeyUse.class); - - final AxKeyUse copy = ((AxKeyUse) copyObject); - try { - copy.usedKey = usedKey.getClass().newInstance(); - } - catch (Exception e) { - throw new ApexRuntimeException("error copying concept key: " + e.getMessage(), e); - } - usedKey.copyTo(copy.usedKey); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + usedKey.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - throw new IllegalArgumentException("comparison object may not be null"); - } - - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - - final AxKeyUse other = (AxKeyUse) obj; - return usedKey.equals(other.usedKey); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - Assertions.argumentNotNull(otherObj, "comparison object may not be null"); - - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxKeyUse other = (AxKeyUse) otherObj; - - return usedKey.compareTo(other.usedKey); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxModel.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxModel.java deleted file mode 100644 index f0489c734..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxModel.java +++ /dev/null @@ -1,471 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import javax.persistence.CascadeType; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class is the base class for all models in Apex. All model classes inherit from this model so all models must have a key and have key information. - *

- * Validation checks that the model key is valid. It goes on to check for null keys and checks each key for uniqueness in the model. A check is carried out to - * ensure that an {@link AxKeyInfo} instance exists for every {@link AxArtifactKey} key. For each {@link AxReferenceKey} instance, a check is made that its - * parent and local name are nut null and that a {@link AxKeyInfo} entry exists for its parent. Then a check is made that each used {@link AxArtifactKey} and - * {@link AxReferenceKey} usage references a key that exists. Finally, a check is made to ensure that an {@link AxArtifactKey} instance exists for every - * {@link AxKeyInfo} instance. - */ - -@Entity -@Table(name = "AxModel") -@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) - -@XmlRootElement(name = "apexModel", namespace = "http://www.ericsson.com/apex") -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "AxModel", namespace = "http://www.ericsson.com/apex", propOrder = { "key", "keyInformation" }) - -public class AxModel extends AxConcept { - private static final String IS_A_NULL_KEY = " is a null key"; - - private static final long serialVersionUID = -771659065637205430L; - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - // @formatter:off - @OneToOne(cascade = CascadeType.ALL) - @JoinColumns({ - @JoinColumn(name = "keyInformationName", referencedColumnName = "name"), - @JoinColumn(name = "keyInformationVersion", referencedColumnName = "version") - }) - @XmlElement(name = "keyInformation", required = true) - private AxKeyInformation keyInformation; - // @formatter:on - - /** - * The Default Constructor creates this concept with a NULL artifact key. - */ - public AxModel() { - this(new AxArtifactKey()); - } - - /** - * Copy constructor - * @param copyConcept the concept to copy from - */ - public AxModel(final AxModel copyConcept) { - super(copyConcept); - } - - /** - * Constructor to create this concept with the specified key. - * - * @param key the key of this concept - */ - public AxModel(final AxArtifactKey key) { - this(key, new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion()))); - } - - /** - * Constructor to create this concept and set all its fields. - * - * @param key the key of this concept - * @param keyInformation the key information of this concept - */ - public AxModel(final AxArtifactKey key, final AxKeyInformation keyInformation) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(keyInformation, "keyInformation may not be null"); - - this.key = key; - this.keyInformation = keyInformation; - } - - /** - * Registers this model with the {@link ModelService}. All models are registered with the model service so that models can be references from anywhere in - * the Apex system without being passed as references through deep call chains. - */ - public void register() { - ModelService.registerModel(AxKeyInformation.class, getKeyInformation()); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = key.getKeys(); - - // We just add the key for the KeyInformation itself. We don't add the - // keys from key information because - // that is a list of key information for existing keys - keyList.add(keyInformation.getKey()); - - return keyList; - } - - /** - * Sets the key of this concept. - * - * @param key the key of this concept - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the key information of this concept. - * - * @return the key information of this concept - */ - public AxKeyInformation getKeyInformation() { - return keyInformation; - } - - /** - * Sets the key information of this concept. - * - * @param keyInformation the key information of this concept - */ - public void setKeyInformation(final AxKeyInformation keyInformation) { - Assertions.argumentNotNull(keyInformation, "keyInformation may not be null"); - this.keyInformation = keyInformation; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com. ericsson.apex.model.basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - - result = key.validate(result); - result = keyInformation.validate(result); - - // Key consistency check - final Set artifactKeySet = new TreeSet<>(); - final Set referenceKeySet = new TreeSet<>(); - final Set usedKeySet = new TreeSet<>(); - - for (final AxKey axKey : this.getKeys()) { - // Check for the two type of keys we have - if (axKey instanceof AxArtifactKey) { - result = validateArtifactKeyInModel((AxArtifactKey) axKey, artifactKeySet, result); - } - else if (axKey instanceof AxReferenceKey) { - result = validateReferenceKeyInModel((AxReferenceKey) axKey, referenceKeySet, result); - } - // It must be an AxKeyUse, nothing else is legal - else { - usedKeySet.add((AxKeyUse) axKey); - } - } - - // Check all reference keys have correct parent keys - for (final AxReferenceKey referenceKey : referenceKeySet) { - if (!artifactKeySet.contains(referenceKey.getParentArtifactKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "parent artifact key not found for reference key " + referenceKey)); - } - } - - result = validateKeyUses(usedKeySet, artifactKeySet, referenceKeySet, result); - - // Check key information for unused key information - for (final AxArtifactKey keyInfoKey : keyInformation.getKeyInfoMap().keySet()) { - if (!artifactKeySet.contains(keyInfoKey)) { - result.addValidationMessage( - new AxValidationMessage(keyInfoKey, this.getClass(), ValidationResult.WARNING, "key not found for key information entry")); - } - } - - return result; - } - - /** - * Check for consistent usage of an artifact key in the model - * @param artifactKey The artifact key to check - * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to the set - * @param result The validation result to append to - * @return the result of the validation - */ - private AxValidationResult validateArtifactKeyInModel(final AxArtifactKey artifactKey, Set artifactKeySet, AxValidationResult result) { - // Null key check - if (artifactKey.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key " + artifactKey + IS_A_NULL_KEY)); - } - - // Null key name start check - if (artifactKey.getName().toUpperCase().startsWith(AxKey.NULL_KEY_NAME)) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key " + artifactKey + " name starts with keyword " + AxKey.NULL_KEY_NAME)); - } - - // Unique key check - if (artifactKeySet.contains(artifactKey)) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "duplicate key " + artifactKey + " found")); - } - else { - artifactKeySet.add(artifactKey); - } - - // Key information check - if (!keyInformation.getKeyInfoMap().containsKey(artifactKey)) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key information not found for key " + artifactKey)); - } - - return result; - } - - /** - * Check for consistent usage of a reference key in the model - * @param artifactKey The reference key to check - * @param referenceKeySet The set of reference keys encountered so far, this key is appended to the set - * @param result The validation result to append to - * @return the result of the validation - */ - private AxValidationResult validateReferenceKeyInModel(final AxReferenceKey referenceKey, Set referenceKeySet, AxValidationResult result) { - // Null key check - if (referenceKey.equals(AxReferenceKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key " + referenceKey + IS_A_NULL_KEY)); - } - - // Null parent key check - if (referenceKey.getParentArtifactKey().equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "parent artifact key of key " + referenceKey + IS_A_NULL_KEY)); - } - - // Null local name check - if (referenceKey.getLocalName().equals(AxKey.NULL_KEY_NAME)) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key " + referenceKey + " has a null local name")); - } - - // Null key name start check - if (referenceKey.getParentArtifactKey().getName().toUpperCase().startsWith(AxKey.NULL_KEY_NAME)) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key " + referenceKey + " parent name starts with keyword " + AxKey.NULL_KEY_NAME)); - } - - // Unique key check - if (referenceKeySet.contains(referenceKey)) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "duplicate key " + referenceKey + " found")); - } - else { - referenceKeySet.add(referenceKey); - } - - // Key information check - if (!keyInformation.getKeyInfoMap().containsKey(referenceKey.getParentArtifactKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key information not found for parent key of key " + referenceKey)); - } - - return result; - } - - /** - * Check for consistent usage of cross-key references in the model - * @param usedKeySet The set of all keys used in the model - * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to the set - * @param referenceKeySet The set of reference keys encountered so far, this key is appended to the set - * @param result The validation result to append to - * @return the result of the validation - */ - private AxValidationResult validateKeyUses(final Set usedKeySet, final Set artifactKeySet, - final Set referenceKeySet, AxValidationResult result) { - // Check all key uses - for (final AxKeyUse usedKey : usedKeySet) { - if (usedKey.getKey() instanceof AxArtifactKey) { - // AxArtifact key usage, check the key exists - if (!artifactKeySet.contains(usedKey.getKey())) { - result.addValidationMessage(new AxValidationMessage(usedKey.getKey(), this.getClass(), ValidationResult.INVALID, - "an artifact key used in the model is not defined")); - } - } - else { - // AxReference key usage, check the key exists - if (!referenceKeySet.contains(usedKey.getKey())) { - result.addValidationMessage(new AxValidationMessage(usedKey.getKey(), this.getClass(), ValidationResult.INVALID, - "a reference key used in the model is not defined")); - } - } - } - - return result; - } - - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - keyInformation.clean(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("key="); - builder.append(key); - builder.append(",keyInformation="); - builder.append(keyInformation); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxModel.class); - - final AxModel copy = ((AxModel) copyObject); - copy.setKey(new AxArtifactKey(key)); - copy.setKeyInformation(new AxKeyInformation(keyInformation)); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + keyInformation.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - - final AxModel other = (AxModel) obj; - if (!key.equals(other.key)) { - return false; - } - return keyInformation.equals(other.keyInformation); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxModel other = (AxModel) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - return keyInformation.compareTo(other.keyInformation); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxReferenceKey.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxReferenceKey.java deleted file mode 100644 index 9401152d0..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxReferenceKey.java +++ /dev/null @@ -1,556 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * A reference key identifies entities in the system that are contained in other entities. Every contained concept in the system must have an - * {@link AxReferenceKey} to identify it. Non-contained first order concepts are identified using an {@link AxArtifactKey} key. - *

- * An {@link AxReferenceKey} contains an {@link AxArtifactKey} key reference to the first order entity that contains it. The local name of the reference key - * must uniquely identify the referenced concept among those concepts contained in the reference key's parent. In other words, if a parent concept has more than - * one child, the local name in the key of all its children must be unique. - *

- * If a reference key's parent is itself a reference key, then the parent's local name must be set in the reference key. If the parent is a first order concept, - * then the parent's local name in the key will be set to NULL. - *

- * Key validation checks that the parent name and parent version fields match the {@link NAME_REGEXP} and {@link VERSION_REGEXP} regular expressions - * respectively and that the local name fields match the {@link LOCAL_NAME_REGEXP} regular expression. - */ -@Embeddable -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "apexReferenceKey", namespace = "http://www.ericsson.com/apex") -@XmlType(name = "AxReferenceKey", namespace = "http://www.ericsson.com/apex", propOrder = { "parentKeyName", "parentKeyVersion", "parentLocalName", - "localName" }) - -public class AxReferenceKey extends AxKey { - private static final String PARENT_KEY_NAME = "parentKeyName"; - private static final String PARENT_KEY_VERSION = "parentKeyVersion"; - private static final String PARENT_LOCAL_NAME = "parentLocalName"; - private static final String LOCAL_NAME = "localName"; - - private static final long serialVersionUID = 8932717618579392561L; - - /** Regular expression to specify the structure of local names in reference keys.*/ - public static final String LOCAL_NAME_REGEXP = "[A-Za-z0-9\\-_\\.]+|^$"; - - /** Regular expression to specify the structure of IDs in reference keys.*/ - public static final String REFERENCE_KEY_ID_REGEXP = "[A-Za-z0-9\\-_]+:[0-9].[0-9].[0-9]:[A-Za-z0-9\\-_]+:[A-Za-z0-9\\-_]+"; - - private static final int PARENT_NAME_FIELD = 0; - private static final int PARENT_VERSION_FIELD = 1; - private static final int PARENT_LOCAL_NAME_FIELD = 2; - private static final int LOCAL_NAME_FIELD = 3; - - @Column(name = PARENT_KEY_NAME) - @XmlElement(required = true) - private String parentKeyName; - - @Column(name = PARENT_KEY_VERSION) - @XmlElement(required = true) - private String parentKeyVersion; - - @Column(name = PARENT_LOCAL_NAME) - @XmlElement(required = true) - private String parentLocalName; - - @Column(name = LOCAL_NAME) - @XmlElement(required = true) - private String localName; - - /** - * The default constructor creates a null reference key. - */ - public AxReferenceKey() { - this(NULL_KEY_NAME, NULL_KEY_VERSION, NULL_KEY_NAME, NULL_KEY_NAME); - } - - /** - * The Copy Constructor creates a key by copying another key. - * - * @param referenceKey the reference key to copy from - */ - public AxReferenceKey(final AxReferenceKey referenceKey) { - this(referenceKey.getParentKeyName(), referenceKey.getParentKeyVersion(), referenceKey.getParentLocalName(), referenceKey.getLocalName()); - } - - /** - * Constructor to create a null reference key for the specified parent artifact key. - * - * @param axArtifactKey the parent artifact key of this reference key - */ - public AxReferenceKey(final AxArtifactKey axArtifactKey) { - this(axArtifactKey.getName(), axArtifactKey.getVersion(), NULL_KEY_NAME, NULL_KEY_NAME); - } - - /** - * Constructor to create a reference key for the given parent artifact key with the given local name. - * - * @param axArtifactKey the parent artifact key of this reference key - * @param localName the local name of this reference key - */ - public AxReferenceKey(final AxArtifactKey axArtifactKey, final String localName) { - this(axArtifactKey, NULL_KEY_NAME, localName); - } - - /** - * Constructor to create a reference key for the given parent reference key with the given local name. - * - * @param parentReferenceKey the parent reference key of this reference key - * @param localName the local name of this reference key - */ - public AxReferenceKey(final AxReferenceKey parentReferenceKey, final String localName) { - this(parentReferenceKey.getParentArtifactKey(), parentReferenceKey.getLocalName(), localName); - } - - /** - * Constructor to create a reference key for the given parent reference key (specified by the parent reference key's artifact key and local name) with the - * given local name. - * - * @param axArtifactKey the artifact key of the parent reference key of this reference key - * @param parentLocalName the local name of the parent reference key of this reference key - * @param localName the local name of this reference key - */ - public AxReferenceKey(final AxArtifactKey axArtifactKey, final String parentLocalName, final String localName) { - this(axArtifactKey.getName(), axArtifactKey.getVersion(), parentLocalName, localName); - } - - /** - * Constructor to create a reference key for the given parent artifact key (specified by the parent artifact key's name and version) with the given local - * name. - * - * @param parentKeyName the name of the parent artifact key of this reference key - * @param parentKeyVersion the version of the parent artifact key of this reference key - * @param localName the local name of this reference key - */ - public AxReferenceKey(final String parentKeyName, final String parentKeyVersion, final String localName) { - this(parentKeyName, parentKeyVersion, NULL_KEY_NAME, localName); - } - - /** - * Constructor to create a reference key for the given parent key (specified by the parent key's name, version nad local name) with the given local name. - * - * @param parentKeyName the parent key name of this reference key - * @param parentKeyVersion the parent key version of this reference key - * @param parentLocalName the parent local name of this reference key - * @param localName the local name of this reference key - */ - public AxReferenceKey(final String parentKeyName, final String parentKeyVersion, final String parentLocalName, final String localName) { - super(); - this.parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); - this.parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); - this.parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); - this.localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); - } - - /** - * Constructor to create a key from the specified key ID. - * - * @param id the key ID in a format that respects the {@link KEY_ID_REGEXP} - */ - public AxReferenceKey(final String id) { - final String conditionedId = Assertions.validateStringParameter("id", id, REFERENCE_KEY_ID_REGEXP); - - // Split on colon, if the id passes the regular expression test above - // it'll have just three colons separating the parent name, - // parent version, parent local name, and and local name - // No need for range checks or size checks on the array - final String[] nameVersionNameArray = conditionedId.split(":"); - - // Initiate the new key - parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, nameVersionNameArray[PARENT_NAME_FIELD], NAME_REGEXP); - parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, nameVersionNameArray[PARENT_VERSION_FIELD], VERSION_REGEXP); - parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, nameVersionNameArray[PARENT_LOCAL_NAME_FIELD], LOCAL_NAME_REGEXP); - localName = Assertions.validateStringParameter(LOCAL_NAME, nameVersionNameArray[LOCAL_NAME_FIELD], LOCAL_NAME_REGEXP); - } - - /** - * Get a null reference key. - * - * @return a null reference key - */ - public static AxReferenceKey getNullKey() { - return new AxReferenceKey(AxKey.NULL_KEY_NAME, AxKey.NULL_KEY_VERSION, AxKey.NULL_KEY_NAME, AxKey.NULL_KEY_NAME); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxReferenceKey getKey() { - return this; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = new ArrayList<>(); - keyList.add(getKey()); - return keyList; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#getID() - */ - @Override - public String getID() { - return parentKeyName + ':' + parentKeyVersion + ':' + parentLocalName + ':' + localName; - } - - /** - * Gets the parent artifact key of this reference key. - * - * @return the parent artifact key of this reference key - */ - public AxArtifactKey getParentArtifactKey() { - return new AxArtifactKey(parentKeyName, parentKeyVersion); - } - - /** - * Gets the parent reference key of this reference key. - * - * @return the parent reference key of this reference key - */ - public AxReferenceKey getParentReferenceKey() { - return new AxReferenceKey(parentKeyName, parentKeyVersion, parentLocalName); - } - - /** - * Sets the parent artifact key of this reference key. - * - * @param parentKey the parent artifact key of this reference key - */ - public void setParentArtifactKey(final AxArtifactKey parentKey) { - Assertions.argumentNotNull(parentKey, "parentKey may not be null"); - - parentKeyName = parentKey.getName(); - parentKeyVersion = parentKey.getVersion(); - parentLocalName = NULL_KEY_NAME; - } - - /** - * Sets the parent reference key of this reference key. - * - * @param parentKey the parent reference key of this reference key - */ - public void setParentReferenceKey(final AxReferenceKey parentKey) { - Assertions.argumentNotNull(parentKey, "parentKey may not be null"); - - parentKeyName = parentKey.getParentKeyName(); - parentKeyVersion = parentKey.getParentKeyVersion(); - parentLocalName = parentKey.getLocalName(); - } - - /** - * Gets the parent key name of this reference key. - * - * @return the parent key name of this reference key - */ - public String getParentKeyName() { - return parentKeyName; - } - - /** - * Sets the parent key name of this reference key. - * - * @param parentKeyName the parent key name of this reference key - */ - public void setParentKeyName(final String parentKeyName) { - this.parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); - } - - /** - * Gets the parent key version of this reference key. - * - * @return the parent key version of this reference key - */ - public String getParentKeyVersion() { - return parentKeyVersion; - } - - /** - * Sets the parent key version of this reference key. - * - * @param parentKeyVersion the parent key version of this reference key - */ - public void setParentKeyVersion(final String parentKeyVersion) { - this.parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); - } - - /** - * Gets the parent local name of this reference key. - * - * @return the parent local name of this reference key - */ - public String getParentLocalName() { - return parentLocalName; - } - - /** - * Sets the parent local name of this reference key. - * - * @param parentLocalName the parent local name of this reference key - */ - public void setParentLocalName(final String parentLocalName) { - this.parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); - } - - /** - * Gets the local name of this reference key. - * - * @return the local name of this reference key - */ - public String getLocalName() { - return localName; - } - - /** - * Sets the local name of this reference key. - * - * @param localName the local name of this reference key - */ - public void setLocalName(final String localName) { - this.localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#getCompatibility(com. ericsson.apex.model.basicmodel.concepts.AxKey) - */ - @Override - public AxKey.Compatibility getCompatibility(final AxKey otherKey) { - if (!(otherKey instanceof AxReferenceKey)) { - return Compatibility.DIFFERENT; - } - final AxReferenceKey otherReferenceKey = (AxReferenceKey) otherKey; - - return this.getParentArtifactKey().getCompatibility(otherReferenceKey.getParentArtifactKey()); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxKey#isCompatible(com. ericsson.apex.model.basicmodel.concepts.AxKey) - */ - @Override - public boolean isCompatible(final AxKey otherKey) { - if (!(otherKey instanceof AxReferenceKey)) { - return false; - } - final AxReferenceKey otherReferenceKey = (AxReferenceKey) otherKey; - - return this.getParentArtifactKey().isCompatible(otherReferenceKey.getParentArtifactKey()); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com. ericsson.apex.model.basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult result) { - try { - Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); - } - catch (final IllegalArgumentException e) { - result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, "parentKeyName invalid-" + e.getMessage())); - } - - try { - Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); - } - catch (final IllegalArgumentException e) { - result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, "parentKeyVersion invalid-" + e.getMessage())); - } - - try { - Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); - } - catch (final IllegalArgumentException e) { - result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, "parentLocalName invalid-" + e.getMessage())); - } - - try { - Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); - } - catch (final IllegalArgumentException e) { - result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, "localName invalid-" + e.getMessage())); - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); - parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); - parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); - localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("parentKeyName="); - builder.append(parentKeyName); - builder.append(",parentKeyVersion="); - builder.append(parentKeyVersion); - builder.append(",parentLocalName="); - builder.append(parentLocalName); - builder.append(",localName="); - builder.append(localName); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxReferenceKey.class); - - final AxReferenceKey copy = ((AxReferenceKey) copyObject); - copy.setParentKeyName(parentKeyName); - copy.setParentKeyVersion(parentKeyVersion); - copy.setLocalName(localName); - copy.setParentLocalName(parentLocalName); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + parentKeyName.hashCode(); - result = prime * result + parentKeyVersion.hashCode(); - result = prime * result + parentLocalName.hashCode(); - result = prime * result + localName.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - throw new IllegalArgumentException("comparison object may not be null"); - } - - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - final AxReferenceKey other = (AxReferenceKey) obj; - - if (!parentKeyName.equals(other.parentKeyName)) { - return false; - } - if (!parentKeyVersion.equals(other.parentKeyVersion)) { - return false; - } - if (!parentLocalName.equals(other.parentLocalName)) { - return false; - } - return localName.equals(other.localName); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - Assertions.argumentNotNull(otherObj, "comparison object may not be null"); - - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxReferenceKey other = (AxReferenceKey) otherObj; - if (!parentKeyName.equals(other.parentKeyName)) { - return parentKeyName.compareTo(other.parentKeyName); - } - if (!parentKeyVersion.equals(other.parentKeyVersion)) { - return parentKeyVersion.compareTo(other.parentKeyVersion); - } - if (!parentLocalName.equals(other.parentLocalName)) { - return parentLocalName.compareTo(other.parentLocalName); - } - return localName.compareTo(other.localName); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationMessage.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationMessage.java deleted file mode 100644 index ef8eb317c..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationMessage.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * A validation message is created for each validation observation observed during validation of a concept. The message holds the key and - * the class of the concept on which the observation was made as well as the type of observation and a message describing the observation. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class AxValidationMessage { - private final AxKey observedKey; - private ValidationResult validationResult = ValidationResult.VALID; - private final String observedClass; - private final String message; - - /** - * Create an validation observation with the given fields. - * - * @param observedKey the key of the class on which the validation observation was made - * @param observedClass the class on which the validation observation was made - * @param validationResult the type of observation made - * @param message a message describing the observation - */ - public AxValidationMessage(final AxKey observedKey, final Class observedClass, final ValidationResult validationResult, final String message) { - Assertions.argumentNotNull(observedKey, "observedKey may not be null"); - Assertions.argumentNotNull(observedClass, "observedClass may not be null"); - Assertions.argumentNotNull(validationResult, "validationResult may not be null"); - Assertions.argumentNotNull(message, "message may not be null"); - - this.observedKey = observedKey; - this.observedClass = observedClass.getCanonicalName(); - this.validationResult = validationResult; - this.message = message; - } - - /** - * Gets the key of the observation. - * - * @return the key of the observation - */ - public AxKey getObservedKey() { - return observedKey; - } - - /** - * Gets the observed class. - * - * @return the observed class - */ - public String getObservedClass() { - return observedClass; - } - - /** - * Gets the type of observation made. - * - * @return the type of observation made - */ - public ValidationResult getValidationResult() { - return validationResult; - } - - /** - * Get a description of the observation. - * - * @return the observation description - */ - public String getMessage() { - return message; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return observedKey.toString() + ':' + observedClass + ':' + validationResult.name() + ':' + message; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationResult.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationResult.java deleted file mode 100644 index 363fd1596..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/AxValidationResult.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.LinkedList; -import java.util.List; - -/** - * This class records the result of a validation and holds all validatino observation messages. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class AxValidationResult { - /** - * The ValidationResult enumeration describes the severity of a validation result. - */ - public enum ValidationResult { - /** No problems or observations were detected during validation. */ - VALID, - /** Observations were made on a concept (such as blank descriptions) of a nature that will not affect the use of the concept. */ - OBSERVATION, - /** Warnings were made on a concept (such as defined but unused concepts) of a nature that may affect the use of the concept. */ - WARNING, - /** - * Errors were detected on a concept (such as referenced but undefined concepts) of a nature that will affect the use of the concept. - */ - INVALID - } - - // The actual verification result - private ValidationResult validationResult = ValidationResult.VALID; - - // Messages collected during the verification process - private final List messageList = new LinkedList<>(); - - /** - * Check if a validation reported a valid concept, returns true if the model is usable (that is, even if the model has warnings or - * observations). - * - * @return true, if the concept is reported as valid and can be used - */ - public boolean isValid() { - return validationResult != ValidationResult.INVALID; - } - - /** - * Check if a validation reported a concept with no errors or warnings, returns true if the model is OK to use. - * - * @return true, if the concept has no warnings or errors - */ - public boolean isOK() { - return validationResult == ValidationResult.VALID || validationResult == ValidationResult.OBSERVATION; - } - - /** - * Gets the validation result. - * - * @return the validation result on a concept - */ - public ValidationResult getValidationResult() { - return validationResult; - } - - /** - * Gets the list of validation results on the concept. - * - * @return the list of validaiton results - */ - public List getMessageList() { - return messageList; - } - - /** - * Adds a validation message to the validation result, used by validate() implementations on {@link AxConcept} subclasses to report - * validaiton observations. - * - * @param validationMessage the validation message - */ - public void addValidationMessage(final AxValidationMessage validationMessage) { - messageList.add(validationMessage); - - // Check if the incoming message has a more sever status than the - // current one on the overall validation result, - // if so, the overall result goes to that level - if (validationMessage.getValidationResult().ordinal() > validationResult.ordinal()) { - validationResult = validationMessage.getValidationResult(); - } - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - - switch (validationResult) { - case VALID: - - builder.append("***validation of model successful***"); - return builder.toString(); - case OBSERVATION: - - builder.append("\n***observations noted during validation of model***\n"); - break; - case WARNING: - - builder.append("\n***warnings issued during validation of model***\n"); - break; - case INVALID: - builder.append("\n***validation of model failed***\n"); - break; - default: - break; - } - - for (final AxValidationMessage message : messageList) { - builder.append(message); - builder.append("\n"); - } - - builder.append("********************************"); - return builder.toString(); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/package-info.java deleted file mode 100644 index 4d5c91c66..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/concepts/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * This package contains the fundamental concepts for all APEX models. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ - -@XmlSchema(namespace = "http://www.ericsson.com/apex", elementFormDefault = XmlNsForm.QUALIFIED, xmlns = { - @XmlNs(namespaceURI = "http://www.ericsson.com/apex", prefix = "") }) - -package org.onap.apex.model.basicmodel.concepts; - -import javax.xml.bind.annotation.XmlNs; -import javax.xml.bind.annotation.XmlNsForm; -import javax.xml.bind.annotation.XmlSchema; diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDao.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDao.java deleted file mode 100644 index 5aab39c1b..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDao.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao; - -import java.util.Collection; -import java.util.List; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; - -/** - * The Interface ApexDao describes the DAO interface for reading and writing Apex {@link AxConcept} concepts to and from databases using - * JDBC. - * - * @author Sergey Sachkov - * @author liam.fallon@ericsson.com - */ -public interface ApexDao { - - /** - * Initialize the Apex DAO with the given parameters. - * - * @param daoParameters parameters to use to access the database - * @throws ApexException on initialization errors - */ - void init(DAOParameters daoParameters) throws ApexException; - - /** - * Close the Apex DAO. - */ - void close(); - - /** - * Creates an Apex concept on the database. - * - * @param the type of the object to create, a subclass of {@link AxConcept} - * @param obj the object to create - */ - void create(T obj); - - /** - * Delete an Apex concept on the database. - * - * @param the type of the object to delete, a subclass of {@link AxConcept} - * @param obj the object to delete - */ - void delete(T obj); - - /** - * Delete an Apex concept on the database. - * - * @param the type of the object to delete, a subclass of {@link AxConcept} - * @param aClass the class of the object to delete, a subclass of {@link AxConcept} - * @param key the key of the object to delete - */ - void delete(Class aClass, AxArtifactKey key); - - /** - * Delete an Apex concept on the database. - * - * @param the type of the object to delete, a subclass of {@link AxConcept} - * @param aClass the class of the object to delete, a subclass of {@link AxConcept} - * @param key the key of the object to delete - */ - void delete(Class aClass, AxReferenceKey key); - - /** - * Create a collection of objects in the database. - * - * @param the type of the object to create, a subclass of {@link AxConcept} - * @param objs the objects to create - */ - void create(Collection objs); - - /** - * Delete a collection of objects in the database. - * - * @param the type of the objects to delete, a subclass of {@link AxConcept} - * @param objs the objects to delete - */ - void delete(Collection objs); - - /** - * Delete a collection of objects in the database referred to by artifact key. - * - * @param the type of the objects to delete, a subclass of {@link AxConcept} - * @param aClass the class of the objects to delete, a subclass of {@link AxConcept} - * @param keys the keys of the objects to delete - * @return the number of objects deleted - */ - int deleteByArtifactKey(Class aClass, Collection keys); - - /** - * Delete a collection of objects in the database referred to by reference key. - * - * @param the type of the objects to delete, a subclass of {@link AxConcept} - * @param aClass the class of the objects to delete, a subclass of {@link AxConcept} - * @param keys the keys of the objects to delete - * @return the number of objects deleted - */ - int deleteByReferenceKey(Class aClass, Collection keys); - - /** - * Delete all objects of a given class in the database. - * - * @param the type of the objects to delete, a subclass of {@link AxConcept} - * @param aClass the class of the objects to delete, a subclass of {@link AxConcept} - */ - void deleteAll(Class aClass); - - /** - * Get an object from the database, referred to by artifact key. - * - * @param the type of the object to get, a subclass of {@link AxConcept} - * @param aClass the class of the object to get, a subclass of {@link AxConcept} - * @param key the key of the object to get - * @return the object that was retrieved from the database - */ - T get(Class aClass, AxArtifactKey key); - - /** - * Get an object from the database, referred to by reference key. - * - * @param the type of the object to get, a subclass of {@link AxConcept} - * @param aClass the class of the object to get, a subclass of {@link AxConcept} - * @param key the key of the object to get - * @return the object that was retrieved from the database or null if the object was not retrieved - */ - T get(Class aClass, AxReferenceKey key); - - /** - * Get all the objects in the database of a given type. - * - * @param the type of the objects to get, a subclass of {@link AxConcept} - * @param aClass the class of the objects to get, a subclass of {@link AxConcept} - * @return the objects or null if no objects were retrieved - */ - List getAll(Class aClass); - - /** - * Get all the objects in the database of the given type with the given parent artifact key. - * - * @param the type of the objects to get, a subclass of {@link AxConcept} - * @param aClass the class of the objects to get, a subclass of {@link AxConcept} - * @param parentKey the parent key of the concepts to get - * @return the all - */ - List getAll(Class aClass, AxArtifactKey parentKey); - - /** - * Get a concept from the database with the given artifact key. - * - * @param the type of the object to get, a subclass of {@link AxConcept} - * @param aClass the class of the object to get, a subclass of {@link AxConcept} - * @param artifactID the artifact key of the concept to get - * @return the concept that matches the key or null if the concept is not retrieved - */ - T getArtifact(Class aClass, AxArtifactKey artifactID); - - /** - * Get a concept from the database with the given reference key. - * - * @param the type of the object to get, a subclass of {@link AxConcept} - * @param aClass the class of the object to get, a subclass of {@link AxConcept} - * @param artifactID the artifact key of the concept to get - * @return the concept that matches the key or null if the concept is not retrieved - */ - T getArtifact(Class aClass, AxReferenceKey artifactID); - - /** - * Get the number of instances of a concept that exist in the database. - * - * @param the type of the object to get, a subclass of {@link AxConcept} - * @param aClass the class of the object to get, a subclass of {@link AxConcept} - * @return the number of instances of the concept in the database - */ - long size(Class aClass); - - /** - * Update a concept in the database. - * - * @param the type of the object to get, a subclass of {@link AxConcept} - * @param obj the object to update - * @return the updated object - */ - T update(T obj); -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDaoFactory.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDaoFactory.java deleted file mode 100644 index ecb8a4658..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/ApexDaoFactory.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.utilities.Assertions; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This factory class returns an Apex DAO for the configured persistence mechanism. The factory uses the plugin class specified in {@link DAOParameters} to - * instantiate a DAO instance. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexDaoFactory { - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexDaoFactory.class); - - /** - * Return an Apex DAO for the required APEX DAO plugin class. - * - * @param daoParameters parameters to use to read the database configuration information - * @return the Apex DAO - * @throws ApexException on invalid JPA plugins - */ - public ApexDao createApexDao(final DAOParameters daoParameters) throws ApexException { - Assertions.argumentNotNull(daoParameters, ApexException.class, "Parameter \"daoParameters\" may not be null"); - - // Get the class for the DAO using reflection - Object apexDaoObject = null; - try { - apexDaoObject = Class.forName(daoParameters.getPluginClass()).newInstance(); - } - catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { - LOGGER.error("Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e); - throw new ApexException("Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e); - } - - // Check the class is an Apex DAO - if (!(apexDaoObject instanceof ApexDao)) { - LOGGER.error("Specified Apex DAO plugin class \"" + daoParameters.getPluginClass() + "\" does not implement the ApexDao interface"); - throw new ApexException("Specified Apex DAO plugin class \"" + daoParameters.getPluginClass() + "\" does not implement the ApexDao interface"); - } - - return (ApexDao) apexDaoObject; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/DAOParameters.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/DAOParameters.java deleted file mode 100644 index ccf15fea7..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/DAOParameters.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao; - -import java.util.Properties; - -/** - * This class is a POJO that holds properties for Apex DAOs. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class DAOParameters { - /** The default Apex DAO plugin class. */ - public static final String DEFAULT_PLUGIN_CLASS = "org.onap.apex.model.basicmodel.dao.impl.DefaultApexDao"; - - private String pluginClass = DEFAULT_PLUGIN_CLASS; - private String persistenceUnit; - - private Properties jdbcProperties = new Properties(); - - /** - * Gets the DAO plugin class, this is the DAO class to use and it must implement the {@link ApexDao} interface. - * - * @return the DAO plugin class - */ - public String getPluginClass() { - return pluginClass; - } - - /** - * Sets the DAO plugin class, a class that implements the {@link ApexDao} interface. - * - * @param daoPluginClass the DAO plugin class - */ - public void setPluginClass(final String daoPluginClass) { - pluginClass = daoPluginClass; - } - - /** - * Gets the persistence unit for the DAO. The persistence unit defines the JDBC properties the DAO will use. The persistence unit must defined in the - * {@code META-INF/persistence.xml} resource file - * - * @return the persistence unit to use for JDBC access - */ - public String getPersistenceUnit() { - return persistenceUnit; - } - - /** - * Sets the persistence unit for the DAO. The persistence unit defines the JDBC properties the DAO will use. The persistence unit must defined in the - * {@code META-INF/persistence.xml} resource file - * - * @param daoPersistenceUnit the persistence unit to use for JDBC access - */ - public void setPersistenceUnit(final String daoPersistenceUnit) { - persistenceUnit = daoPersistenceUnit; - } - - /** - * Gets the JDBC properties. - * - * @return the JDBC properties - */ - public Properties getJdbcProperties() { - return jdbcProperties; - } - - /** - * Sets the JDBC properties. - * - * @param jdbcProperties the JDBC properties - */ - public void setJdbcProperties(final Properties jdbcProperties) { - this.jdbcProperties = jdbcProperties; - } - - /** - * Gets a single JDBC property. - * - * @param key the key of the property - * @return the JDBC property - */ - public String getJdbcProperty(final String key) { - return jdbcProperties.getProperty(key); - } - - /** - * Sets a single JDBC property. - * - * @param key the key of the property - * @param value the value of the JDBC property - */ - public void setJdbcProperty(final String key, final String value) { - jdbcProperties.setProperty(key, value); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "DAOParameters [pluginClass=" + pluginClass + ", persistenceUnit=" + persistenceUnit + ", jdbcProperties=" + jdbcProperties + "]"; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/CDATAConditioner.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/CDATAConditioner.java deleted file mode 100644 index d949ab28a..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/CDATAConditioner.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao.converters; - -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; -import javax.xml.bind.annotation.adapters.XmlAdapter; - -/** - * The Class CDATAConditioner converts a CDATA String to and from database format by removing spaces at the ends of lines and - * platform-specific new line endings. - * - * @author John Keeney (John.Keeney@ericsson.com) - */ -@Converter -public class CDATAConditioner extends XmlAdapter implements AttributeConverter { - - private static final String NL = "\n"; - - /* - * (non-Javadoc) - * - * @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object) - */ - @Override - public String convertToDatabaseColumn(final String raw) { - return clean(raw); - } - - /* - * (non-Javadoc) - * - * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object) - */ - @Override - public String convertToEntityAttribute(final String db) { - return clean(db); - } - - /* - * (non-Javadoc) - * - * @see javax.xml.bind.annotation.adapters.XmlAdapter - */ - @Override - public String unmarshal(final String v) throws Exception { - return this.convertToEntityAttribute(v); - } - - /* - * (non-Javadoc) - * - * @see javax.xml.bind.annotation.adapters.XmlAdapter - */ - @Override - public String marshal(final String v) throws Exception { - return this.convertToDatabaseColumn(v); - } - - /** - * Clean. - * - * @param in the in - * @return the string - */ - public static final String clean(final String in) { - if (in == null) { - return null; - } - else { - return in.replaceAll("\\s+$", "").replaceAll("\\r?\\n", NL); - } - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/UUID2String.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/UUID2String.java deleted file mode 100644 index 4e6b66025..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/UUID2String.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao.converters; - -import java.util.UUID; - -import javax.persistence.AttributeConverter; -import javax.persistence.Converter; -import javax.xml.bind.annotation.adapters.XmlAdapter; - -/** - * The Class UUIDConverter converts a UUID to and from database format. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -@Converter -public class UUID2String extends XmlAdapter implements AttributeConverter { - - /* - * (non-Javadoc) - * - * @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object) - */ - @Override - public String convertToDatabaseColumn(final UUID uuid) { - String returnString; - if (uuid == null) { - returnString = ""; - } - else { - returnString = uuid.toString(); - } - return returnString; - } - - /* - * (non-Javadoc) - * - * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object) - */ - @Override - public UUID convertToEntityAttribute(final String uuidString) { - return UUID.fromString(uuidString); - } - - /* - * (non-Javadoc) - * - * @see javax.xml.bind.annotation.adapters.XmlAdapter - */ - @Override - public UUID unmarshal(final String v) throws Exception { - return this.convertToEntityAttribute(v); - } - - /* - * (non-Javadoc) - * - * @see javax.xml.bind.annotation.adapters.XmlAdapter - */ - @Override - public String marshal(final UUID v) throws Exception { - return this.convertToDatabaseColumn(v); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/package-info.java deleted file mode 100644 index c7bad6777..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/converters/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains converters used by APEX EclipseLink marshaling and unmarshaling of {@link org.onap.apex.model.basicmodel.concepts.AxConcept} - * instances to and from files and databases. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.basicmodel.dao.converters; diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/DefaultApexDao.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/DefaultApexDao.java deleted file mode 100644 index a73a15e41..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/DefaultApexDao.java +++ /dev/null @@ -1,526 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao.impl; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.dao.ApexDao; -import org.onap.apex.model.basicmodel.dao.DAOParameters; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * The Class DefaultApexDao is an JPA implementation of the {@link ApexDao} class for Apex concepts ({@link AxConcept}). It uses the default - * JPA implementation in the javax {@link Persistence} class. - * - * - * @author Sergey Sachkov (sergey.sachkov@ericsson.com) - */ -public class DefaultApexDao implements ApexDao { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(DefaultApexDao.class); - - private static final String SELECT_C_FROM = "SELECT c FROM "; - private static final String AND_C_KEY_LOCAL_NAME = "' AND c.key.localName='"; - private static final String AND_C_KEY_PARENT_KEY_VERSION = "' AND c.key.parentKeyVersion='"; - private static final String C_WHERE_C_KEY_PARENT_KEY_NAME = " c WHERE c.key.parentKeyName='"; - private static final String AND_C_KEY_VERSION = "' AND c.key.version='"; - private static final String C_WHERE_C_KEY_NAME = " c WHERE c.key.name='"; - private static final String DELETE_FROM = "DELETE FROM "; - - // Entity manager for JPA - private EntityManagerFactory emf = null; - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#init(com.ericsson.apex.model.basicmodel.dao.DAOParameters) - */ - @Override - public void init(final DAOParameters daoParameters) throws ApexException { - if (daoParameters == null || daoParameters.getPersistenceUnit() == null) { - LOGGER.error("Apex persistence unit parameter not set"); - throw new ApexException("Apex persistence unit parameter not set"); - } - - LOGGER.debug("Creating Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" . . ."); - try { - emf = Persistence.createEntityManagerFactory(daoParameters.getPersistenceUnit(), daoParameters.getJdbcProperties()); - } - catch (final Exception e) { - LOGGER.warn("Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed", e); - throw new ApexException("Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed", e); - } - LOGGER.debug("Created Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\""); - } - - /** - * Gets the entity manager for this DAO. - * - * @return the entity manager - */ - protected final synchronized EntityManager getEntityManager() { - if (emf == null) { - LOGGER.warn("Apex DAO has not been initialized"); - throw new ApexRuntimeException("Apex DAO has not been initialized"); - } - - return emf.createEntityManager(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#close() - */ - @Override - public final void close() { - if (emf != null) { - emf.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#create(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public void create(final T obj) { - if (obj == null) { - return; - } - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - mg.merge(obj); - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#delete(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public void delete(final T obj) { - if (obj == null) { - return; - } - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - mg.remove(mg.contains(obj) ? obj : mg.merge(obj)); - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#delete(java.lang.Class, - * com.ericsson.apex.model.basicmodel.concepts.AxArtifactKey) - */ - @Override - public void delete(final Class aClass, final AxArtifactKey key) { - if (key == null) { - return; - } - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName() + AND_C_KEY_VERSION - + key.getVersion() + "'", aClass).executeUpdate(); - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#delete(java.lang.Class, - * com.ericsson.apex.model.basicmodel.concepts.AxReferenceKey) - */ - @Override - public void delete(final Class aClass, final AxReferenceKey key) { - if (key == null) { - return; - } - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + key.getParentKeyName() - + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion() + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", - aClass).executeUpdate(); - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#create(java.util.Collection) - */ - @Override - public void create(final Collection objs) { - if (objs == null || objs.isEmpty()) { - return; - } - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - for (final T t : objs) { - mg.merge(t); - } - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#delete(java.util.Collection) - */ - @Override - public void delete(final Collection objs) { - if (objs == null || objs.isEmpty()) { - return; - } - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - for (final T t : objs) { - mg.remove(mg.contains(t) ? t : mg.merge(t)); - } - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#deleteByArtifactKey(java.lang.Class, java.util.Collection) - */ - @Override - public int deleteByArtifactKey(final Class aClass, final Collection keys) { - if (keys == null || keys.isEmpty()) { - return 0; - } - int deletedCount = 0; - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - for (final AxArtifactKey key : keys) { - deletedCount += mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName() - + AND_C_KEY_VERSION + key.getVersion() + "'", aClass).executeUpdate(); - } - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - return deletedCount; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#deleteByReferenceKey(java.lang.Class, java.util.Collection) - */ - @Override - public int deleteByReferenceKey(final Class aClass, final Collection keys) { - if (keys == null || keys.isEmpty()) { - return 0; - } - int deletedCount = 0; - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - for (final AxReferenceKey key : keys) { - deletedCount += mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME - + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion() + AND_C_KEY_LOCAL_NAME - + key.getLocalName() + "'", aClass).executeUpdate(); - } - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - return deletedCount; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#deleteAll(java.lang.Class) - */ - @Override - public void deleteAll(final Class aClass) { - final EntityManager mg = getEntityManager(); - try { - mg.getTransaction().begin(); - mg.createQuery(DELETE_FROM + aClass.getSimpleName() + " c ", aClass).executeUpdate(); - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#get(java.lang.Class, com.ericsson.apex.model.basicmodel.concepts.AxArtifactKey) - */ - @Override - public T get(final Class aClass, final AxArtifactKey key) { - if (aClass == null) { - return null; - } - final EntityManager mg = getEntityManager(); - try { - final T t = mg.find(aClass, key); - if (t != null) { - // This clone is created to force the JPA DAO to recurse down through the object - try { - T clonedT = aClass.newInstance(); - t.copyTo(clonedT); - return clonedT; - } - catch (Exception e) { - LOGGER.warn("Could not clone object of class \"" + aClass.getCanonicalName() + "\"", e); - return null; - } - } - else { - return null; - } - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#get(java.lang.Class, com.ericsson.apex.model.basicmodel.concepts.AxReferenceKey) - */ - @Override - public T get(final Class aClass, final AxReferenceKey key) { - if (aClass == null) { - return null; - } - final EntityManager mg = getEntityManager(); - try { - final T t = mg.find(aClass, key); - if (t != null) { - try { - T clonedT = aClass.newInstance(); - t.copyTo(clonedT); - return clonedT; - } - catch (Exception e) { - LOGGER.warn("Could not clone object of class \"" + aClass.getCanonicalName() + "\"", e); - return null; - } - } - else { - return null; - } - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#getAll(java.lang.Class) - */ - @Override - public List getAll(final Class aClass) { - if (aClass == null) { - return Collections.emptyList(); - } - final EntityManager mg = getEntityManager(); - try { - return mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + " c", aClass).getResultList(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#getAll(java.lang.Class, - * com.ericsson.apex.model.basicmodel.concepts.AxArtifactKey) - */ - @Override - public List getAll(final Class aClass, final AxArtifactKey parentKey) { - if (aClass == null) { - return Collections.emptyList(); - } - final EntityManager mg = getEntityManager(); - try { - return mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + parentKey.getName() - + AND_C_KEY_PARENT_KEY_VERSION + parentKey.getVersion() + "'", aClass).getResultList(); - } - finally { - mg.close(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#getArtifact(java.lang.Class, - * com.ericsson.apex.model.basicmodel.concepts.AxArtifactKey) - */ - @Override - public T getArtifact(final Class aClass, final AxArtifactKey key) { - if (aClass == null || key == null) { - return null; - } - final EntityManager mg = getEntityManager(); - List ret; - try { - ret = mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName() - + AND_C_KEY_VERSION + key.getVersion() + "'", aClass).getResultList(); - } - finally { - mg.close(); - } - if (ret == null || ret.isEmpty()) { - return null; - } - if (ret.size() > 1) { - throw new IllegalArgumentException( - "More than one result was returned for search for " + aClass + " with key " + key.getID() + ": " + ret); - } - return ret.get(0); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#getArtifact(java.lang.Class, - * com.ericsson.apex.model.basicmodel.concepts.AxReferenceKey) - */ - @Override - public T getArtifact(final Class aClass, final AxReferenceKey key) { - if (aClass == null || key == null) { - return null; - } - final EntityManager mg = getEntityManager(); - List ret; - try { - ret = mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + key.getParentKeyName() - + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion() + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", - aClass).getResultList(); - } - finally { - mg.close(); - } - if (ret == null || ret.isEmpty()) { - return null; - } - if (ret.size() > 1) { - throw new IllegalArgumentException( - "More than one result was returned for search for " + aClass + " with key " + key.getID() + ": " + ret); - } - return ret.get(0); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#update(com.ericsson.apex.model.basicmodel.concepts.AxConcept) - */ - @Override - public T update(final T obj) { - final EntityManager mg = getEntityManager(); - T ret; - try { - mg.getTransaction().begin(); - ret = mg.merge(obj); - mg.flush(); - mg.getTransaction().commit(); - } - finally { - mg.close(); - } - return ret; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.dao.ApexDao#size(java.lang.Class) - */ - @Override - public long size(final Class aClass) { - if (aClass == null) { - return 0; - } - final EntityManager mg = getEntityManager(); - long size = 0; - try { - size = mg.createQuery("SELECT COUNT(c) FROM " + aClass.getSimpleName() + " c", Long.class).getSingleResult(); - } - finally { - mg.close(); - } - return size; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/package-info.java deleted file mode 100644 index 16da22646..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/impl/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains a default DAO implementation for APEX {@link org.onap.apex.model.basicmodel.concepts.AxConcept} classes that uses javax persistence. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.basicmodel.dao.impl; diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/package-info.java deleted file mode 100644 index 0ad255a9a..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/dao/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Defines and implements the Data Access Object (DAO) that allows Apex {@link org.onap.apex.model.basicmodel.concepts.AxConcept} concepts to - * be read from and written to databases over JDBC. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.basicmodel.dao; diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelCreator.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelCreator.java deleted file mode 100644 index 5a9de967f..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelCreator.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import org.onap.apex.model.basicmodel.concepts.AxModel; - -/** - * This interface is implemented by factories that create Apex models. It is mainly used by unit test classes that generate Apex models for test purposes. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of Apex model to create, must be a sub class of {@link AxModel} - */ -public interface ApexModelCreator { - - /** - * Gets the model created by the model creator. - * - * @return the model created by the model creator - */ - M getModel(); -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelException.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelException.java deleted file mode 100644 index 252bee4ed..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import org.onap.apex.model.basicmodel.concepts.ApexException; - -/** - * This exception is invoked if an exception occurs in model handling. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexModelException extends ApexException { - private static final long serialVersionUID = -4245694568321686450L; - - /** - * Instantiates a new apex model handling exception. - * - * @param message the message - */ - public ApexModelException(final String message) { - super(message); - } - - /** - * Instantiates a new apex model handling exception. - * - * @param message the message - * @param e the e - */ - public ApexModelException(final String message, final Exception e) { - super(message, e); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelFileWriter.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelFileWriter.java deleted file mode 100644 index 8d9cf2ae0..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelFileWriter.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.File; -import java.io.FileOutputStream; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class writes an Apex model to a file. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of Apex model to write to file, must be a sub class of {@link AxModel} - */ -public class ApexModelFileWriter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelFileWriter.class); - - // Should models being written to files be valid - private boolean validateFlag; - - /** - * Constructor, set the validation flag. - * - * @param validateFlag indicates if validation be performed prior to output - */ - public ApexModelFileWriter(final boolean validateFlag) { - this.validateFlag = validateFlag; - } - - /** - * Write a model to an XML file. - * - * @param model The model to write - * @param rootModelClass The concept class - * @param modelFileName The name of the file to write to - * @throws ApexException thrown on errors - */ - public void apexModelWriteXMLFile(final M model, final Class rootModelClass, final String modelFileName) - throws ApexException { - LOGGER.debug("running apexModelWriteXMLFile . . ."); - - final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); - modelWriter.setValidateFlag(validateFlag); - modelWriter.getCDataFieldSet().add("description"); - modelWriter.getCDataFieldSet().add("logic"); - modelWriter.getCDataFieldSet().add("uiLogic"); - - writeModelFile(model, modelWriter, modelFileName); - - LOGGER.debug("ran apexModelWriteXMLFile"); - } - - /** - * Write a model to an JSON file. - * - * @param model The model to write - * @param rootModelClass The concept class - * @param modelFileName The name of the file to write to - * @throws ApexException thrown on errors - */ - public void apexModelWriteJSONFile(final M model, final Class rootModelClass, final String modelFileName) - throws ApexException { - LOGGER.debug("running apexModelWriteJSONFile . . ."); - - final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); - modelWriter.setJsonOutput(true); - modelWriter.setValidateFlag(validateFlag); - - writeModelFile(model, modelWriter, modelFileName); - - LOGGER.debug("ran apexModelWriteJSONFile"); - } - - /** - * Checks if the validation flag is set. - * - * @return true, the validation flag is set - */ - public boolean isValidateFlag() { - return validateFlag; - } - - /** - * Sets the validate flag. - * - * @param validateFlag the validate flag value - */ - public void setValidateFlag(final boolean validateFlag) { - this.validateFlag = validateFlag; - } - - /** - * Write a model to a file using a model writer. - * - * @param model The model to write - * @param modelWriter the model writer to use to write the model to the file - * @param modelFileName the file name of the file to write to - * @throws ApexException on exceptions writing the model - */ - private void writeModelFile(final M model, final ApexModelWriter modelWriter, final String modelFileName) throws ApexException { - final File modelFile = new File(modelFileName); - if (!modelFile.getParentFile().exists() && !modelFile.getParentFile().mkdirs()) { - LOGGER.warn("could not create directory " + modelFile.getParentFile()); - throw new ApexException("could not create directory " + modelFile.getParentFile()); - } - - try { - final FileOutputStream fileOutputStream = new FileOutputStream(modelFile); - modelWriter.write(model, fileOutputStream); - fileOutputStream.close(); - } - catch (final Exception e) { - LOGGER.warn("error processing file " + modelFile.getAbsolutePath(), e); - throw new ApexException("error processing file " + modelFile.getAbsolutePath(), e); - } - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelReader.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelReader.java deleted file mode 100644 index 84760f5db..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelReader.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.net.URL; -import java.util.regex.Pattern; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - -import org.eclipse.persistence.jaxb.JAXBContextFactory; -import org.eclipse.persistence.jaxb.MarshallerProperties; -import org.eclipse.persistence.oxm.MediaType; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; -import org.onap.policy.apex.model.utilities.ResourceUtils; -import org.onap.policy.apex.model.utilities.TextFileUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class reads an Apex concept from an XML file into a Java Apex Concept {@link AxConcept}. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of Apex concept to read, must be a sub class of {@link AxConcept} - */ -public class ApexModelReader { - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelReader.class); - - // Regular expressions for checking input types - private static final String XML_INPUT_TYPE_REGEXP = "^\\s*<\\?xml.*>\\s*"; // (starts with - private static final String JSON_INPUT_TYPE_REGEXP = "^\\s*[\\(\\{\\[][\\s+\\S]*[\\)\\}\\]]"; // starts with some kind of bracket [ or ( - // or {, then has something, then has - // and has a close bracket - - //  The root class of the concept we are reading - private final Class rootConceptClass; - - // The unmarshaller for the Apex concepts - private Unmarshaller unmarshaller = null; - - // All read concepts are validated after reading if this flag is set - private boolean validateFlag = true; - - /** - * Constructor, initiates the reader with validation on. - * - * @param rootConceptClass the root concept class for concept reading - * @throws ApexModelException the apex concept reader exception - */ - public ApexModelReader(final Class rootConceptClass) throws ApexModelException { - // Save the root concept class - this.rootConceptClass = rootConceptClass; - - try { - final JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {rootConceptClass}, null); - - // Set up the unmarshaller to carry out validation - unmarshaller = jaxbContext.createUnmarshaller(); - unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); - } - catch (final JAXBException e) { - LOGGER.error("Unable to set JAXB context", e); - throw new ApexModelException("Unable to set JAXB context", e); - } - } - - /** - * Constructor, initiates the reader. - * - * @param rootConceptClass the root concept class for concept reading - * @param validate whether to perform validation by default - * @throws ApexModelException the apex concept reader exception - */ - public ApexModelReader(final Class rootConceptClass, final boolean validate) throws ApexModelException { - this(rootConceptClass); - this.validateFlag = validate; - } - - /** - * Set the schema to use for reading XML files. - * - * @param schemaFileName the schema file to use - * @throws ApexModelException if the schema cannot be set - */ - public void setSchema(final String schemaFileName) throws ApexModelException { - // Has a schema been set - if (schemaFileName != null) { - try { - // Set the concept schema - final URL schemaURL = ResourceUtils.getURLResource(schemaFileName); - final Schema apexConceptSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL); - unmarshaller.setSchema(apexConceptSchema); - } - catch (final Exception e) { - LOGGER.error("Unable to load schema ", e); - throw new ApexModelException("Unable to load schema", e); - } - } - else { - // Clear the schema - unmarshaller.setSchema(null); - } - } - - /** - * This method checks the specified Apex concept XML file and reads it into an Apex concept. - * - * @param apexConceptStream the apex concept stream - * @return the Apex concept - * @throws ApexModelException on reading exceptions - */ - public C read(final InputStream apexConceptStream) throws ApexModelException { - Assertions.argumentNotNull(apexConceptStream, "concept stream may not be null"); - - return read(new BufferedReader(new InputStreamReader(apexConceptStream))); - } - - /** - * This method reads the specified Apex reader into an Apex concept. - * - * @param apexConceptReader the apex concept reader - * @return the Apex concept - * @throws ApexModelException on reading exceptions - */ - public C read(final BufferedReader apexConceptReader) throws ApexModelException { - Assertions.argumentNotNull(apexConceptReader, "concept reader may not be null"); - - LOGGER.entry("reading Apex concept into a String . . ."); - - // Get the Apex concept as a string - String apexConceptString = null; - try { - apexConceptString = TextFileUtils.getReaderAsString(apexConceptReader).trim(); - } - catch (final IOException e) { - throw new ApexModelException("Unable to read Apex concept ", e); - } - - return read(apexConceptString); - } - - /** - * This method reads the specified Apex string into an Apex concept. - * - * @param apexConceptString the apex concept as a string - * @return the Apex concept - * @throws ApexModelException on reading exceptions - */ - public C read(final String apexConceptString) throws ApexModelException { - Assertions.argumentNotNull(apexConceptString, "concept string may not be null"); - - LOGGER.entry("reading Apex concept from string . . ."); - - final String apexString = apexConceptString.trim(); - - // Set the type of input for this stream - setInputType(apexString); - - // The Apex Concept - C apexConcept = null; - - // Use JAXB to read and verify the Apex concept XML file - try { - // Load the configuration file - final StreamSource source = new StreamSource(new StringReader(apexString)); - final JAXBElement rootElement = unmarshaller.unmarshal(source, rootConceptClass); - apexConcept = rootElement.getValue(); - } - catch (final JAXBException e) { - throw new ApexModelException("Unable to unmarshal Apex concept ", e); - } - - LOGGER.debug("reading of Apex concept {} completed"); - - // Check if the concept should be validated - if (validateFlag) { - // Validate the configuration file - final AxValidationResult validationResult = apexConcept.validate(new AxValidationResult()); - LOGGER.debug(validationResult.toString()); - if (validationResult.isValid()) { - return apexConcept; - } - else { - LOGGER.error("Apex concept validation failed" + validationResult.toString()); - throw new ApexModelException("Apex concept validation failed" + validationResult.toString()); - } - } - else { - // No validation check - return apexConcept; - } - } - - /** - * Gets the value of the validation flag. - * - * @return the validation flag value - */ - public boolean getValidateFlag() { - return validateFlag; - } - - /** - * Sets the validation flag. - * - * @param validateFlag the validation flag value - */ - public void setValidateFlag(final boolean validateFlag) { - this.validateFlag = validateFlag; - } - - /** - * Set the type of input for the concept reader. - * - * @param apexConceptString The stream with - * @throws ApexModelException on errors setting input type - */ - private void setInputType(final String apexConceptString) throws ApexModelException { - // Check the input type - if (Pattern.compile(JSON_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) { - //is json - try { - unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); - unmarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true); - } - catch (final Exception e) { - LOGGER.warn("JAXB error setting marshaller for JSON Input", e); - throw new ApexModelException("JAXB error setting marshaller for JSON Input", e); - } - } - else if (Pattern.compile(XML_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) { - //is xml - try { - unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML); - } - catch (final Exception e) { - LOGGER.warn("JAXB error setting marshaller for XML Input", e); - throw new ApexModelException("JAXB error setting marshaller for XML Input", e); - } - } - else { - LOGGER.warn("format of input for Apex concept is neither JSON nor XML"); - throw new ApexModelException("format of input for Apex concept is neither JSON nor XML"); - } - } - -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelSaver.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelSaver.java deleted file mode 100644 index 7f4efee99..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelSaver.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.File; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.policy.apex.model.utilities.Assertions; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class is used to save Apex models to file in XML or JSON format. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of Apex model to save to file, must be a sub class of {@link AxModel} - */ -public class ApexModelSaver { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelSaver.class); - - // The class of the model and the model to write to disk - private final Class rootModelClass; - private final M model; - - // The path into which to write the models - private final String writePath; - - /** - * Constructor, specifies the type of the Apex model (a sub class of {@link AxModel}), the model to write, and the path of a directory to which to write the - * model. - * - * @param rootModelClass the class of the model, a sub class of {@link AxModel} - * @param model the model to write, an instance of a sub class of {@link AxModel} - * @param writePath the directory to which models will be written. The name of the written model will be the Model Name for its key with the suffix - * {@code .xml} or {@code .json}. - */ - public ApexModelSaver(final Class rootModelClass, final M model, final String writePath) { - Assertions.argumentNotNull(rootModelClass, "argument rootModelClass may not be null"); - Assertions.argumentNotNull(model, "argument model may not be null"); - Assertions.argumentNotNull(writePath, "writePath rootModelClass may not be null"); - - this.rootModelClass = rootModelClass; - this.model = model; - this.writePath = writePath; - } - - /** - * Write an Apex model to a file in XML format. The model will be written to {@code } - * - * @throws ApexException on errors writing the Apex model - */ - public void apexModelWriteXML() throws ApexException { - LOGGER.debug("running apexModelWriteXML . . ."); - - // Write the file to disk - final File xmlFile = new File(writePath + File.separatorChar + model.getKey().getName() + ".xml"); - new ApexModelFileWriter(true).apexModelWriteXMLFile(model, rootModelClass, xmlFile.getPath()); - - LOGGER.debug("ran apexModelWriteXML"); - } - - /** - * Write an Apex model to a file in JSON format. The model will be written to {@code } - * - * @throws ApexException on errors writing the Apex model - */ - public void apexModelWriteJSON() throws ApexException { - LOGGER.debug("running apexModelWriteJSON . . ."); - - // Write the file to disk - final File jsonFile = new File(writePath + File.separatorChar + model.getKey().getName() + ".json"); - new ApexModelFileWriter(true).apexModelWriteJSONFile(model, rootModelClass, jsonFile.getPath()); - - LOGGER.debug("ran apexModelWriteJSON"); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelStringWriter.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelStringWriter.java deleted file mode 100644 index 882092c05..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelStringWriter.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.ByteArrayOutputStream; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.policy.apex.model.utilities.Assertions; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class writes an Apex concept to a string. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the type of Apex concept to write to a string, must be a sub class of {@link AxConcept} - */ -public class ApexModelStringWriter { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelStringWriter.class); - - // Should concepts being written to files be valid - private boolean validateFlag; - - /** - * Constructor, set the validation flag. - * - * @param validateFlag Should validation be performed prior to output - */ - public ApexModelStringWriter(final boolean validateFlag) { - this.validateFlag = validateFlag; - } - - /** - * Write a concept to a string. - * - * @param concept The concept to write - * @param rootConceptClass The concept class - * @param jsonFlag writes JSON if true, and a generic string if false - * @return The string with the concept - * @throws ApexException thrown on errors - */ - public String writeString(final C concept, final Class rootConceptClass, final boolean jsonFlag) throws ApexException { - Assertions.argumentNotNull(concept, "concept may not be null"); - - if (jsonFlag) { - return writeJSONString(concept, rootConceptClass); - } - else { - return concept.toString(); - } - } - - /** - * Write a concept to an XML string. - * - * @param concept The concept to write - * @param rootConceptClass The concept class - * @return The string with the concept - * @throws ApexException thrown on errors - */ - public String writeXMLString(final C concept, final Class rootConceptClass) throws ApexException { - LOGGER.debug("running writeXMLString . . ."); - - final ApexModelWriter conceptWriter = new ApexModelWriter<>(rootConceptClass); - conceptWriter.setValidateFlag(validateFlag); - conceptWriter.getCDataFieldSet().add("description"); - conceptWriter.getCDataFieldSet().add("logic"); - conceptWriter.getCDataFieldSet().add("uiLogic"); - - final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); - try { - conceptWriter.write(concept, baOutputStream); - baOutputStream.close(); - } - catch (final Exception e) { - LOGGER.warn("error writing XML string", e); - throw new ApexException("error writing XML string", e); - } - - LOGGER.debug("ran writeXMLString"); - return baOutputStream.toString(); - } - - /** - * Write a concept to a JSON string. - * - * @param concept The concept to write - * @param rootConceptClass The concept class - * @return The string with the concept - * @throws ApexException thrown on errors - */ - public String writeJSONString(final C concept, final Class rootConceptClass) throws ApexException { - LOGGER.debug("running writeJSONString . . ."); - - final ApexModelWriter conceptWriter = new ApexModelWriter<>(rootConceptClass); - conceptWriter.setJsonOutput(true); - conceptWriter.setValidateFlag(validateFlag); - - final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); - try { - conceptWriter.write(concept, baOutputStream); - baOutputStream.close(); - } - catch (final Exception e) { - LOGGER.warn("error writing JSON string", e); - throw new ApexException("error writing JSON string", e); - } - - LOGGER.debug("ran writeJSONString"); - return baOutputStream.toString(); - } - - /** - * Checks if is validate flag. - * - * @return true, if checks if is validate flag - */ - public boolean isValidateFlag() { - return validateFlag; - } - - /** - * Sets the validate flag. - * - * @param validateFlag the validate flag - */ - public void setValidateFlag(final boolean validateFlag) { - this.validateFlag = validateFlag; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelWriter.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelWriter.java deleted file mode 100644 index 5b7a9568b..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexModelWriter.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.Set; -import java.util.TreeSet; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -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.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.eclipse.persistence.jaxb.JAXBContextFactory; -import org.eclipse.persistence.jaxb.MarshallerProperties; -import org.eclipse.persistence.oxm.MediaType; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; -import org.w3c.dom.Document; - -/** - * This class writes an Apex concept to an XML file or JSON file from a Java Apex Concept. - * - * @author John Keeney (john.keeney@ericsson.com) - * @param the type of Apex concept to write, must be a sub class of {@link AxConcept} - */ -public class ApexModelWriter { - private static final String CONCEPT_MAY_NOT_BE_NULL = "concept may not be null"; - private static final String CONCEPT_WRITER_MAY_NOT_BE_NULL = "concept writer may not be null"; - private static final String CONCEPT_STREAM_MAY_NOT_BE_NULL = "concept stream may not be null"; - - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelWriter.class); - - // Writing as JSON or XML - private boolean jsonOutput = false; - - // The list of fields to output as CDATA - private final Set cDataFieldSet = new TreeSet<>(); - - // The Marshaller for the Apex concepts - private Marshaller marshaller = null; - - // All written concepts are validated before writing if this flag is set - private boolean validateFlag = true; - - /** - * Constructor, initiates the writer. - * - * @param rootConceptClass the root concept class for concept reading - * @throws ApexModelException the apex concept writer exception - */ - public ApexModelWriter(final Class rootConceptClass) throws ApexModelException { - // Set up Eclipselink for XML and JSON output - System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory"); - - try { - final JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {rootConceptClass}, null); - - // Set up the unmarshaller to carry out validation - marshaller = jaxbContext.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - marshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); - } - catch (final JAXBException e) { - LOGGER.error("JAXB marshaller creation exception", e); - throw new ApexModelException("JAXB marshaller creation exception", e); - } - } - - /** - * The set of fields to be output as CDATA. - * - * @return the set of fields - */ - public Set getCDataFieldSet() { - return cDataFieldSet; - } - - /** - * Return true if JSON output enabled, XML output if false. - * - * @return true for JSON output - */ - public boolean isJsonOutput() { - return jsonOutput; - } - - /** - * Set the value of JSON output, true for JSON output, false for XML output. - * - * @param jsonOutput true for JSON output - * @throws ApexModelException on errors setting output type - */ - public void setJsonOutput(final boolean jsonOutput) throws ApexModelException { - this.jsonOutput = jsonOutput; - - // Set up output specific parameters - if (this.jsonOutput) { - try { - marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); - marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true); - } - catch (final Exception e) { - LOGGER.warn("JAXB error setting marshaller for JSON output", e); - throw new ApexModelException("JAXB error setting marshaller for JSON output", e); - } - } - else { - try { - marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML); - } - catch (final Exception e) { - LOGGER.warn("JAXB error setting marshaller for XML output", e); - throw new ApexModelException("JAXB error setting marshaller for XML output", e); - } - } - } - - /** - * This method validates the Apex concept then writes it into a stream. - * - * @param concept the concept to write - * @param apexConceptStream the stream to write to - * @throws ApexModelException on validation or writing exceptions - */ - public void write(final C concept, final OutputStream apexConceptStream) throws ApexModelException { - Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); - Assertions.argumentNotNull(apexConceptStream, CONCEPT_STREAM_MAY_NOT_BE_NULL); - - this.write(concept, new OutputStreamWriter(apexConceptStream)); - } - - /** - * This method validates the Apex concept then writes it into a writer. - * - * @param concept the concept to write - * @param apexConceptWriter the writer to write to - * @throws ApexModelException on validation or writing exceptions - */ - public void write(final C concept, final Writer apexConceptWriter) throws ApexModelException { - Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); - Assertions.argumentNotNull(apexConceptWriter, CONCEPT_WRITER_MAY_NOT_BE_NULL); - - // Check if we should validate the concept - if (validateFlag) { - // Validate the concept first - final AxValidationResult validationResult = concept.validate(new AxValidationResult()); - LOGGER.debug(validationResult.toString()); - if (!validationResult.isValid()) { - LOGGER.warn(validationResult.toString()); - throw new ApexModelException("Apex concept xml (" + concept.getKey().getID() + ") validation failed"); - } - } - - if (jsonOutput) { - writeJSON(concept, apexConceptWriter); - } - else { - writeXML(concept, apexConceptWriter); - } - } - - /** - * This method writes the Apex concept into a writer in XML format. - * - * @param concept the concept to write - * @param apexConceptWriter the writer to write to - * @throws ApexModelException on validation or writing exceptions - */ - private void writeXML(final C concept, final Writer apexConceptWriter) throws ApexModelException { - Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); - - LOGGER.debug("writing Apex concept XML . . ."); - - try { - // Write the concept into a DOM document, then transform to add CDATA fields and pretty print, then write out the result - final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); - final Document document = docBuilderFactory.newDocumentBuilder().newDocument(); - - // Marshal the concept into the empty document. - marshaller.marshal(concept, document); - - // Transform the DOM to the output stream - final TransformerFactory transformerFactory = TransformerFactory.newInstance(); - final Transformer domTransformer = transformerFactory.newTransformer(); - - // Pretty print - try { - domTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); - // May fail if not using XALAN XSLT engine. But not in any way vital - domTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - } - catch (final Exception ignore) { - // We ignore exceptions here and catch errors below - } - - // Convert the cDataFieldSet into a space delimited string - domTransformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cDataFieldSet.toString().replaceAll("[\\[\\]\\,]", " ")); - domTransformer.transform(new DOMSource(document), new StreamResult(apexConceptWriter)); - } - catch (JAXBException | TransformerException | ParserConfigurationException e) { - LOGGER.warn("Unable to marshal Apex concept XML", e); - throw new ApexModelException("Unable to marshal Apex concept XML", e); - } - LOGGER.debug("wrote Apex concept XML"); - } - - /** - * This method writes the Apex concept into a writer in JSON format. - * - * @param concept the concept to write - * @param apexConceptWriter the writer to write to - * @throws ApexModelException on validation or writing exceptions - */ - private void writeJSON(final C concept, final Writer apexConceptWriter) throws ApexModelException { - Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); - - LOGGER.debug("writing Apex concept JSON . . ."); - - try { - marshaller.marshal(concept, apexConceptWriter); - } - catch (final JAXBException e) { - LOGGER.warn("Unable to marshal Apex concept JSON", e); - throw new ApexModelException("Unable to marshal Apex concept JSON", e); - } - LOGGER.debug("wrote Apex concept JSON"); - } - - /** - * Gets the validation flag value. - * - * @return the validation flag value - */ - public boolean getValidateFlag() { - return validateFlag; - } - - /** - * Sets the validation flag. - * - * @param validateFlag the validation flag value - */ - public void setValidateFlag(final boolean validateFlag) { - this.validateFlag = validateFlag; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexSchemaGenerator.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexSchemaGenerator.java deleted file mode 100644 index 5055df630..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/handling/ApexSchemaGenerator.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.StringWriter; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.SchemaOutputResolver; -import javax.xml.transform.Result; -import javax.xml.transform.stream.StreamResult; - -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class generates the XML model schema from the given Apex concept classes. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ApexSchemaGenerator { - // Get a reference to the logger - private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexSchemaGenerator.class); - - /** - * A Main method to allow schema generation from the command line or from maven or scripts. - * - * @param args the command line arguments, usage is {@code ApexSchemaGenerator apex-root-class [schema-file-name]} - */ - public static void main(final String[] args) { - PrintStream printStream = null; - - if (args.length == 1) { - printStream = System.out; - } - else if (args.length == 2) { - final File schemaFile = new File(args[1]); - - try { - schemaFile.getParentFile().mkdirs(); - printStream = new PrintStream(schemaFile); - } - catch (final Exception e) { - LOGGER.error("error on Apex schema output", e); - return; - } - } - else { - LOGGER.error("usage: ApexSchemaGenerator apex-root-class [schema-file-name]"); - return; - } - - // Get the schema - final String schema = new ApexSchemaGenerator().generate(args[0]); - - // Output the schema - printStream.println(schema); - - printStream.close(); - } - - /** - * Generates the XML schema (XSD) for the Apex model described using JAXB annotations. - * - * @param rootClassName the name of the root class for schema generation - * @return The schema - */ - public String generate(final String rootClassName) { - JAXBContext jaxbContext; - try { - jaxbContext = JAXBContext.newInstance(Class.forName(rootClassName)); - } - catch (final ClassNotFoundException e) { - LOGGER.error("could not create JAXB context, root class " + rootClassName + " not found", e); - return null; - } - catch (final JAXBException e) { - LOGGER.error("could not create JAXB context", e); - return null; - } - - final ApexSchemaOutputResolver sor = new ApexSchemaOutputResolver(); - try { - jaxbContext.generateSchema(sor); - } - catch (final IOException e) { - LOGGER.error("error generating the Apex schema (XSD) file", e); - return null; - } - - String schemaString = sor.getSchema(); - schemaString = fixForUnqualifiedBug(schemaString); - - return schemaString; - } - - /** - * There is a bug in schema generation that does not specify the elements from Java Maps as being unqualified. This method "hacks" those - * elements in the schema to fix this, the elements being {@code entry}, {@code key}, and {@code value} - * - * @param schemaString The schema in which elements should be fixed - * @return the string - */ - private String fixForUnqualifiedBug(final String schemaString) { - // Fix the "entry" element - String newSchemaString = schemaString.replaceAll("", - ""); - - // Fix the "key" element - newSchemaString = newSchemaString.replaceAll(" getParameterClass() { - try { - return (Class) Class.forName(parameterClassName); - } - catch (final ClassNotFoundException e) { - throw new ApexRuntimeException("class not found for parameter class name \"" + parameterClassName + "\""); - } - } - - /** - * Gets the parameter class name. - * - * @return the parameter class name - */ - public final String getParameterClassName() { - return parameterClassName; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "AbstractParameters [parameterClassName=" + parameterClassName + "]"; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ModelService.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ModelService.java deleted file mode 100644 index 688beaa4f..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ModelService.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.onap.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.apex.model.basicmodel.concepts.AxConcept; - -/** - * The model service makes Apex models available to all classes in a JVM. - * - * The reason for having a model service is to avoid having to pass concept and model definitions down long call chains in modules such as the Apex engine and - * editor. The model service makes the model and concept definitions available statically. - * - * Note that the use of the model service means that only a single Apex model of a particular type may exist in Apex (particularly the engine) at any time. Of - * course the model in a JVM can be changed at any time provided all users of the model are stopped and restrted in an orderly manner. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public abstract class ModelService { - // The map holding the models - private static Map, AxConcept> modelMap = new ConcurrentHashMap<>(); - - /** - * This class is an abstract static class that cannot be extended. - */ - private ModelService() { - } - - /** - * Register a model with the model service. - * - * @param the generic type - * @param modelClass the class of the model, used to index the model - * @param model The model - */ - public static void registerModel(final Class modelClass, final M model) { - modelMap.put(modelClass, model); - } - - /** - * Remove a model from the model service. - * - * @param the generic type - * @param modelClass the class of the model, used to index the model - */ - public static void deregisterModel(final Class modelClass) { - modelMap.remove(modelClass); - } - - /** - * Get a model from the model service. - * - * @param the generic type - * @param modelClass the class of the model, used to index the model - * @return The model - */ - @SuppressWarnings("unchecked") - public static M getModel(final Class modelClass) { - final M model = (M) modelMap.get(modelClass); - - if (model == null) { - throw new ApexRuntimeException("Model for " + modelClass.getCanonicalName() + " not found in model service"); - } - - return model; - } - - /** - * Check if a model is defined on the model service. - * - * @param the generic type - * @param modelClass the class of the model, used to index the model - * @return true if the model is defined - */ - public static boolean existsModel(final Class modelClass) { - return modelMap.get(modelClass) != null; - } - - /** - * Clear all models in the model service. - */ - public static void clear() { - modelMap.clear(); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ParameterService.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ParameterService.java deleted file mode 100644 index 9a254b0d6..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/ParameterService.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.onap.apex.model.basicmodel.concepts.ApexRuntimeException; - -/** - * The parameter service makes Apex parameters available to all classes in a JVM. - * - * The reason for having a parameter service is to avoid having to pass parameters down long call chains in modules such as the Apex engine and editor. The - * parameter service makes parameters available statically. - * - * The parameter service must be used with care because changing a parameter set anywhere in a JVM will affect all users of those parameters anywhere in the - * JVM. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public abstract class ParameterService { - // The map holding the parameters - private static Map, AbstractParameters> parameterMap = new ConcurrentHashMap<>(); - - /** - * This class is an abstract static class that cannot be extended. - */ - private ParameterService() { - } - - /** - * Register parameters with the parameter service. - * - * @param

the generic type - * @param parametersClass the class of the parameter, used to index the parameter - * @param parameters the parameters - */ - public static

void registerParameters(final Class

parametersClass, final P parameters) { - parameterMap.put(parametersClass, parameters); - } - - /** - * Remove parameters from the parameter service. - * - * @param

the generic type - * @param parametersClass the class of the parameter, used to index the parameter - */ - public static

void deregisterParameters(final Class

parametersClass) { - parameterMap.remove(parametersClass); - } - - /** - * Get parameters from the parameter service. - * - * @param

the generic type - * @param parametersClass the class of the parameter, used to index the parameter - * @return The parameter - */ - @SuppressWarnings("unchecked") - public static

P getParameters(final Class

parametersClass) { - final P parameter = (P) parameterMap.get(parametersClass); - - if (parameter == null) { - throw new ApexRuntimeException("Parameters for " + parametersClass.getCanonicalName() + " not found in parameter service"); - } - - return parameter; - } - - /** - * Check if parameters is defined on the parameter service. - * - * @param

the generic type - * @param parametersClass the class of the parameter, used to index the parameter - * @return true if the parameter is defined - */ - public static

boolean existsParameters(final Class

parametersClass) { - return parameterMap.get(parametersClass) != null; - } - - /** - * Get all the entries in the parameters map. - * - * @return The entries - */ - public static Set, AbstractParameters>> getAll() { - return parameterMap.entrySet(); - } - - /** - * Clear all parameters in the parameter service. - */ - public static void clear() { - parameterMap.clear(); - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/package-info.java deleted file mode 100644 index da6c69898..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/service/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains the static services in Apex that make models and parameters available to all objects in the JVM. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.basicmodel.service; diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModel.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModel.java deleted file mode 100644 index e7e50677e..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModel.java +++ /dev/null @@ -1,332 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.net.URL; - -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.dao.ApexDao; -import org.onap.apex.model.basicmodel.dao.ApexDaoFactory; -import org.onap.apex.model.basicmodel.dao.DAOParameters; -import org.onap.apex.model.basicmodel.handling.ApexModelFileWriter; -import org.onap.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.apex.model.basicmodel.handling.ApexModelWriter; -import org.onap.policy.apex.model.utilities.ResourceUtils; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This class tests reading and writing of Apex models to file and to a database using JPA. It also tests validation of Apex models. This class is designed for - * use in unit tests in modules that define Apex models. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the generic type - */ -public class TestApexModel { - private static final String MODEL_IS_INVALID = "model is invalid "; - private static final String ERROR_PROCESSING_FILE = "error processing file "; - private static final String TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE = "test model does not equal model read from XML file "; - private static final String ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL = "error creating temporary file for Apex model"; - - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexModel.class); - - // The root model class that specifies the root to import and export from - private final Class rootModelClass; - - // The class that provides the model - private TestApexModelCreator modelCreator = null; - - /** - * Constructor, defines the subclass of {@link AxModel} that is being tested and the {@link TestApexModelCreator} object that is used to generate Apex - * models. - * - * @param rootModelClass the Apex model class, a sub class of {@link AxModel} - * @param modelCreator the @link TestApexModelCreator} that will generate Apex models of various types for testing - */ - public TestApexModel(final Class rootModelClass, final TestApexModelCreator modelCreator) { - this.rootModelClass = rootModelClass; - this.modelCreator = modelCreator; - } - - /** - * Get a test Apex model using the model creator. - * - * @return the test Apex model - */ - public final M getModel() { - return modelCreator.getModel(); - } - - /** - * Test write and read in XML format. - * - * @throws ApexException on write/read errors - */ - public final void testApexModelWriteReadXML() throws ApexException { - LOGGER.debug("running testApexModelWriteReadXML . . ."); - - final M model = modelCreator.getModel(); - - // Write the file to disk - File xmlFile; - - try { - xmlFile = File.createTempFile("ApexModel", ".xml"); - xmlFile.deleteOnExit(); - } - catch (final Exception e) { - LOGGER.warn(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); - throw new ApexException(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); - } - new ApexModelFileWriter(true).apexModelWriteXMLFile(model, rootModelClass, xmlFile.getPath()); - - // Read the file from disk - final ApexModelReader modelReader = new ApexModelReader<>(rootModelClass); - - try { - final URL apexModelURL = ResourceUtils.getLocalFile(xmlFile.getAbsolutePath()); - final M fileModel = modelReader.read(apexModelURL.openStream()); - if (!model.equals(fileModel)) { - LOGGER.warn(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + xmlFile.getAbsolutePath()); - throw new ApexException(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + xmlFile.getAbsolutePath()); - } - } - catch (final Exception e) { - LOGGER.warn(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e); - throw new ApexException(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e); - } - - final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); - modelWriter.getCDataFieldSet().add("description"); - modelWriter.getCDataFieldSet().add("logic"); - modelWriter.getCDataFieldSet().add("uiLogic"); - - final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); - modelWriter.write(model, baOutputStream); - final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray()); - final M byteArrayModel = modelReader.read(baInputStream); - if (!model.equals(byteArrayModel)) { - LOGGER.warn("test model does not equal XML marshalled and unmarshalled model"); - throw new ApexException("test model does not equal XML marshalled and unmarshalled model"); - } - - LOGGER.debug("ran testApexModelWriteReadXML"); - } - - /** - * Test write and read in JSON format. - * - * @throws ApexException on write/read errors - */ - public final void testApexModelWriteReadJSON() throws ApexException { - LOGGER.debug("running testApexModelWriteReadJSON . . ."); - - final M model = modelCreator.getModel(); - - // Write the file to disk - File jsonFile; - try { - jsonFile = File.createTempFile("ApexModel", ".xml"); - jsonFile.deleteOnExit(); - } - catch (final Exception e) { - LOGGER.warn(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); - throw new ApexException(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); - } - new ApexModelFileWriter(true).apexModelWriteJSONFile(model, rootModelClass, jsonFile.getPath()); - - // Read the file from disk - final ApexModelReader modelReader = new ApexModelReader<>(rootModelClass); - - try { - final URL apexModelURL = ResourceUtils.getLocalFile(jsonFile.getAbsolutePath()); - final M fileModel = modelReader.read(apexModelURL.openStream()); - if (!model.equals(fileModel)) { - LOGGER.warn(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + jsonFile.getAbsolutePath()); - throw new ApexException(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + jsonFile.getAbsolutePath()); - } - } - catch (final Exception e) { - LOGGER.warn(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e); - throw new ApexException(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e); - } - - final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); - modelWriter.setJsonOutput(true); - - final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); - modelWriter.write(model, baOutputStream); - final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray()); - final M byteArrayModel = modelReader.read(baInputStream); - if (!model.equals(byteArrayModel)) { - LOGGER.warn("test model does not equal JSON marshalled and unmarshalled model"); - throw new ApexException("test model does not equal JSON marshalled and unmarshalled model"); - } - - LOGGER.debug("ran testApexModelWriteReadJSON"); - } - - /** - * Test write and read of an Apex model to database using JPA. - * - * @param daoParameters the DAO parameters to use for JPA/JDBC - * @throws ApexException thrown on errors writing or reading the model to database - */ - public final void testApexModelWriteReadJPA(final DAOParameters daoParameters) throws ApexException { - LOGGER.debug("running testApexModelWriteReadJPA . . ."); - - final M model = modelCreator.getModel(); - - final ApexDao apexDao = new ApexDaoFactory().createApexDao(daoParameters); - apexDao.init(daoParameters); - - apexDao.create(model); - final M dbJPAModel = apexDao.get(rootModelClass, model.getKey()); - apexDao.close(); - - if (!model.equals(dbJPAModel)) { - LOGGER.warn("test model does not equal model written and read using generic JPA"); - throw new ApexException("test model does not equal model written and read using generic JPA"); - } - - LOGGER.debug("ran testApexModelWriteReadJPA"); - } - - /** - * Test that an Apex model is valid. - * - * @return the result of the validation - * @throws ApexException thrown on errors validating the Apex model - */ - public final AxValidationResult testApexModelValid() throws ApexException { - LOGGER.debug("running testApexModelVaid . . ."); - - final M model = modelCreator.getModel(); - final AxValidationResult result = model.validate(new AxValidationResult()); - - if (!result.isValid()) { - LOGGER.warn(MODEL_IS_INVALID + result.toString()); - throw new ApexException(MODEL_IS_INVALID + result.toString()); - } - - LOGGER.debug("ran testApexModelVaid"); - return result; - } - - /** - * Test that an Apex model is structured incorrectly. - * - * @return the result of the validation - * @throws ApexException thrown on errors validating the Apex model - */ - public final AxValidationResult testApexModelVaidateMalstructured() throws ApexException { - LOGGER.debug("running testApexModelVaidateMalstructured . . ."); - - final M model = modelCreator.getMalstructuredModel(); - final AxValidationResult result = model.validate(new AxValidationResult()); - - if (result.isValid()) { - LOGGER.warn("model should not be valid " + result.toString()); - throw new ApexException("should not be valid " + result.toString()); - } - - LOGGER.debug("ran testApexModelVaidateMalstructured"); - return result; - } - - /** - * Test that an Apex model has observations. - * - * @return the result of the validation - * @throws ApexException thrown on errors validating the Apex model - */ - public final AxValidationResult testApexModelVaidateObservation() throws ApexException { - LOGGER.debug("running testApexModelVaidateObservation . . ."); - - final M model = modelCreator.getObservationModel(); - final AxValidationResult result = model.validate(new AxValidationResult()); - - if (!result.isValid()) { - LOGGER.warn(MODEL_IS_INVALID + result.toString()); - throw new ApexException(MODEL_IS_INVALID + result.toString()); - } - - if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.OBSERVATION)) { - LOGGER.warn("model should have observations"); - throw new ApexException("model should have observations"); - } - - LOGGER.debug("ran testApexModelVaidateObservation"); - return result; - } - - /** - * Test that an Apex model has warnings. - * - * @return the result of the validation - * @throws ApexException thrown on errors validating the Apex model - */ - public final AxValidationResult testApexModelVaidateWarning() throws ApexException { - LOGGER.debug("running testApexModelVaidateWarning . . ."); - - final M model = modelCreator.getWarningModel(); - final AxValidationResult result = model.validate(new AxValidationResult()); - - if (!result.isValid()) { - LOGGER.warn(MODEL_IS_INVALID + result.toString()); - throw new ApexException(MODEL_IS_INVALID + result.toString()); - } - - if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.WARNING)) { - LOGGER.warn("model should have warnings"); - throw new ApexException("model should have warnings"); - } - - LOGGER.debug("ran testApexModelVaidateWarning"); - return result; - } - - /** - * Test that an Apex model is invalid. - * - * @return the result of the validation - * @throws ApexException thrown on errors validating the Apex model - */ - public final AxValidationResult testApexModelVaidateInvalidModel() throws ApexException { - LOGGER.debug("running testApexModelVaidateInvalidModel . . ."); - - final M model = modelCreator.getInvalidModel(); - final AxValidationResult result = model.validate(new AxValidationResult()); - - if (result.isValid()) { - LOGGER.warn("model should not be valid " + result.toString()); - throw new ApexException("should not be valid " + result.toString()); - } - - LOGGER.debug("ran testApexModelVaidateInvalidModel"); - return result; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModelCreator.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModelCreator.java deleted file mode 100644 index 7213c6694..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/TestApexModelCreator.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.test; - -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelCreator; - -/** - * The Interface TestApexModelCreator is used to create models for Apex model tests. It is mainly used by unit tests for Apex domain models so that - * developers can write test Java programs to create models. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - * @param the generic type - */ -public interface TestApexModelCreator extends ApexModelCreator { - - /** - * Gets the malstructured model. - * - * @return the malstructured model - */ - M getMalstructuredModel(); - - /** - * Gets the observation model. - * - * @return the observation model - */ - M getObservationModel(); - - /** - * Gets the warning model. - * - * @return the warning model - */ - M getWarningModel(); - - /** - * Gets the invalid model. - * - * @return the invalid model - */ - M getInvalidModel(); -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/package-info.java deleted file mode 100644 index 6bd6b73fb..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/test/package-info.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains utility classes that allow testing of validation and reads and writes on APEX models to files and databases. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.basicmodel.test; diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java deleted file mode 100644 index a2bfbb80a..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.xml; - -import java.io.Serializable; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.XmlAdapter; - -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; - -/** - * This class manages marshaling and unmarshaling of Apex {@link AxReferenceKey} concepts using JAXB. The local name in reference keys must have specific - * handling. - */ -@XmlAccessorType(XmlAccessType.PROPERTY) -@XmlType(namespace = "http://www.ericsson.com/apex") -public class AxReferenceKeyAdapter extends XmlAdapter implements Serializable { - - private static final long serialVersionUID = -3480405083900107029L; - - /* - * (non-Javadoc) - * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object) - */ - @Override - public final String marshal(final AxReferenceKey key) throws Exception { - return key.getLocalName(); - } - - /* - * (non-Javadoc) - * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object) - */ - @Override - public final AxReferenceKey unmarshal(final String key) throws Exception { - final AxReferenceKey axReferenceKey = new AxReferenceKey(); - axReferenceKey.setLocalName(key); - return axReferenceKey; - } -} diff --git a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/package-info.java b/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/package-info.java deleted file mode 100644 index 77bc0c13b..000000000 --- a/model/basic-model/src/main/java/org/onap/apex/model/basicmodel/xml/package-info.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains utility classes for managing marshaling and unmarshaling of APEX models using JAXB. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ - -@XmlSchema(namespace = "http://www.ericsson.com/apex", elementFormDefault = XmlNsForm.QUALIFIED, xmlns = { - @XmlNs(namespaceURI = "http://www.ericsson.com/apex", prefix = "") }) - -package org.onap.apex.model.basicmodel.xml; - -import javax.xml.bind.annotation.XmlNs; -import javax.xml.bind.annotation.XmlNsForm; -import javax.xml.bind.annotation.XmlSchema; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexConceptException.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexConceptException.java new file mode 100644 index 000000000..1ffb2776c --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexConceptException.java @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +/** + * This class is an exception thrown on Apex Concept errors. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexConceptException extends ApexException { + private static final long serialVersionUID = -8507246953751956974L; + + /** + * Instantiates a new apex concept exception. + * + * @param message the message on the exception + */ + public ApexConceptException(final String message) { + super(message); + } + + /** + * Instantiates a new apex concept exception. + * + * @param message the message on the exception + * @param e the exception that caused this Apex exception + */ + public ApexConceptException(final String message, final Exception e) { + super(message, e); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java new file mode 100644 index 000000000..2dcbf7bcf --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexException.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +/** + * This class is a base exception from which all Apex exceptions are sub classes. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexException extends Exception { + private static final long serialVersionUID = -8507246953751956974L; + + // The object on which the exception was thrown + private transient Object object = null; + + /** + * Instantiates a new apex exception. + * + * @param message the message on the exception + */ + public ApexException(final String message) { + super(message); + } + + /** + * Instantiates a new apex exception. + * + * @param message the message on the exception + * @param object the object that the exception was thrown on + */ + public ApexException(final String message, final Object object) { + super(message); + this.object = object; + } + + /** + * Instantiates a new apex exception. + * + * @param message the message on the exception + * @param e the exception that caused this Apex exception + */ + public ApexException(final String message, final Exception e) { + super(message, e); + } + + /** + * Instantiates a new apex exception. + * + * @param message the message on the exception + * @param e the exception that caused this Apex exception + * @param object the object that the exception was thrown on + */ + public ApexException(final String message, final Exception e, final Object object) { + super(message, e); + this.object = object; + } + + /** + * Get the message from this exception and its causes. + * + * @return the cascaded messages from this exception and the exceptions that caused it + */ + public String getCascadedMessage() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getMessage()); + + for (Throwable t = this; t != null; t = t.getCause()) { + builder.append("\ncaused by: "); + builder.append(t.getMessage()); + } + + return builder.toString(); + } + + /** + * + * Get the object on which the exception was thrown. + * + * @return The object on which the exception was thrown + */ + public Object getObject() { + return object; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java new file mode 100644 index 000000000..f3db3ae60 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/ApexRuntimeException.java @@ -0,0 +1,101 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +/** + * This class is a base run time exception from which all Apex run time exceptions are sub classes. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexRuntimeException extends RuntimeException { + private static final long serialVersionUID = -8507246953751956974L; + + // The object on which the exception was thrown + private transient Object object = null; + + /** + * Instantiates a new apex runtime exception. + * + * @param message the message on the exception + */ + public ApexRuntimeException(final String message) { + super(message); + } + + /** + * Instantiates a new apex runtime exception. + * + * @param message the message on the exception + * @param object the object that the exception was thrown on + */ + public ApexRuntimeException(final String message, final Object object) { + super(message); + this.object = object; + } + + /** + * Instantiates a new apex runtime exception. + * + * @param message the message on the exception + * @param e the exception that caused this Apex exception + */ + public ApexRuntimeException(final String message, final Exception e) { + super(message, e); + } + + /** + * Instantiates a new apex runtime exception. + * + * @param message the message on the exception + * @param e the exception that caused this Apex exception + * @param object the object that the exception was thrown on + */ + public ApexRuntimeException(final String message, final Exception e, final Object object) { + super(message, e); + this.object = object; + } + + /** + * Get the message from this exception and its causes. + * + * @return the message of this exception and all the exceptions that caused this exception + */ + public String getCascadedMessage() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getMessage()); + + for (Throwable t = this; t != null; t = t.getCause()) { + builder.append("\ncaused by: "); + builder.append(t.getMessage()); + } + + return builder.toString(); + } + + /** + * Get the object on which the exception was thrown. + * + * @return The object + */ + public Object getObject() { + return object; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxArtifactKey.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxArtifactKey.java new file mode 100644 index 000000000..382d5024f --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxArtifactKey.java @@ -0,0 +1,384 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * An artifact key uniquely identifies every first order entity in the system. Every first order concept in the system + * must have an {@link AxArtifactKey} to identify it. Concepts that are wholly contained in another concept are + * identified using a {@link AxReferenceKey} key. + *

+ * Key validation checks that the name and version fields match the {@link NAME_REGEXP} and {@link VERSION_REGEXP} + * regular expressions respectively. + */ +@Embeddable +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexArtifactKey", namespace = "http://www.onap.org/policy/apex-pdp") + +@XmlType(name = "AxArtifactKey", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "name", "version" }) + +public class AxArtifactKey extends AxKey { + private static final long serialVersionUID = 8932717618579392561L; + + private static final String NAME_TOKEN = "name"; + private static final String VERSION_TOKEN = "version"; + + @Column(name = NAME_TOKEN) + @XmlElement(required = true) + private String name; + + @Column(name = VERSION_TOKEN) + @XmlElement(required = true) + private String version; + + /** + * The default constructor creates a null artifact key. + */ + public AxArtifactKey() { + this(NULL_KEY_NAME, NULL_KEY_VERSION); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxArtifactKey(final AxArtifactKey copyConcept) { + super(copyConcept); + } + + /** + * Constructor to create a key with the specified name and version. + * + * @param name the key name + * @param version the key version + */ + public AxArtifactKey(final String name, final String version) { + super(); + this.name = Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); + this.version = Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); + } + + /** + * Constructor to create a key using the key and version from the specified key ID. + * + * @param id the key ID in a format that respects the {@link KEY_ID_REGEXP} + */ + public AxArtifactKey(final String id) { + Assertions.argumentNotNull(id, "id may not be null"); + + // Check the incoming ID is valid + Assertions.validateStringParameter("id", id, KEY_ID_REGEXP); + + // Split on colon, if the id passes the regular expression test above + // it'll have just one colon separating the name and version + // No need for range checks or size checks on the array + final String[] nameVersionArray = id.split(":"); + + // Return the new key + name = Assertions.validateStringParameter(NAME_TOKEN, nameVersionArray[0], NAME_REGEXP); + version = Assertions.validateStringParameter(VERSION_TOKEN, nameVersionArray[1], VERSION_REGEXP); + } + + /** + * Get a null artifact key. + * + * @return a null artifact key + */ + public static final AxArtifactKey getNullKey() { + return new AxArtifactKey(AxKey.NULL_KEY_NAME, AxKey.NULL_KEY_VERSION); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return this; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = new ArrayList<>(); + keyList.add(getKey()); + return keyList; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxKey#getID() + */ + @Override + public String getID() { + return name + ':' + version; + } + + /** + * Gets the key name. + * + * @return the key name + */ + public String getName() { + return name; + } + + /** + * Sets the key name. + * + * @param name the key name + */ + public void setName(final String name) { + this.name = Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); + } + + /** + * Gets the key version. + * + * @return the key version + */ + public String getVersion() { + return version; + } + + /** + * Sets the key version. + * + * @param version the key version + */ + public void setVersion(final String version) { + this.version = Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxKey#getCompatibility(org.onap.policy.apex.model.basicmodel. + * concepts.AxKey) + */ + @Override + public AxKey.Compatibility getCompatibility(final AxKey otherKey) { + if (!(otherKey instanceof AxArtifactKey)) { + return Compatibility.DIFFERENT; + } + final AxArtifactKey otherArtifactKey = (AxArtifactKey) otherKey; + + if (this.equals(otherArtifactKey)) { + return Compatibility.IDENTICAL; + } + if (!this.getName().equals(otherArtifactKey.getName())) { + return Compatibility.DIFFERENT; + } + + final String[] thisVersionArray = getVersion().split("\\."); + final String[] otherVersionArray = otherArtifactKey.getVersion().split("\\."); + + // There must always be at least one element in each version + if (!thisVersionArray[0].equals(otherVersionArray[0])) { + return Compatibility.MAJOR; + } + + if (thisVersionArray.length >= 2 && otherVersionArray.length >= 2 + && !thisVersionArray[1].equals(otherVersionArray[1])) { + return Compatibility.MINOR; + } + + return Compatibility.PATCH; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxKey#isCompatible(org.onap.policy.apex.model.basicmodel.concepts. + * AxKey) + */ + @Override + public boolean isCompatible(final AxKey otherKey) { + if (!(otherKey instanceof AxArtifactKey)) { + return false; + } + final AxArtifactKey otherArtifactKey = (AxArtifactKey) otherKey; + + final Compatibility compatibility = this.getCompatibility(otherArtifactKey); + + return !(compatibility == Compatibility.DIFFERENT || compatibility == Compatibility.MAJOR); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult result) { + try { + Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, + "name invalid-" + e.getMessage())); + } + + try { + Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, + "version invalid-" + e.getMessage())); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + name = Assertions.validateStringParameter(NAME_TOKEN, name, NAME_REGEXP); + version = Assertions.validateStringParameter(VERSION_TOKEN, version, VERSION_REGEXP); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("name="); + builder.append(name); + builder.append(",version="); + builder.append(version); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final AxConcept copyObject = target; + Assertions.instanceOf(copyObject, AxArtifactKey.class); + + final AxArtifactKey copy = ((AxArtifactKey) copyObject); + copy.setName(name); + copy.setVersion(version); + + return copyObject; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + name.hashCode(); + result = prime * result + version.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxArtifactKey other = (AxArtifactKey) obj; + + if (!name.equals(other.name)) { + return false; + } + return version.equals(other.version); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + Assertions.argumentNotNull(otherObj, "comparison object may not be null"); + + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxArtifactKey other = (AxArtifactKey) otherObj; + + if (!name.equals(other.name)) { + return name.compareTo(other.name); + } + return version.compareTo(other.version); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java new file mode 100644 index 000000000..3d7f5027f --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConcept.java @@ -0,0 +1,139 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.io.Serializable; +import java.util.List; + +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is the base class for all Apex concept classes. It enforces implementation of abstract methods and + * interfaces on all concepts that are sub-classes of this class. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +@XmlType(name = "AxConcept", namespace = "http://www.onap.org/policy/apex-pdp") + +public abstract class AxConcept implements Serializable, Comparable { + private static final long serialVersionUID = -7434939557282697490L; + + /** + * Default constructor + */ + public AxConcept() {} + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxConcept(final AxConcept copyConcept) { + Assertions.argumentNotNull(copyConcept, "copy concept may not be null"); + copyConcept.copyTo(this); + } + + /** + * Gets the key of this concept. + * + * @return the concept key + */ + public abstract AxKey getKey(); + + /** + * Gets a list of all keys for this concept and all concepts that are defined or referenced by this concept and its + * sub-concepts. + * + * @return the keys used by this concept and it's contained concepts + */ + public abstract List getKeys(); + + /** + * Validate that this concept is structurally correct. + * + * @param result the parameter in which the result of the validation will be returned + * @return the validation result that was passed in in the @{link result} field with the result of this validation + * added + */ + public abstract AxValidationResult validate(AxValidationResult result); + + /** + * Clean this concept, tidy up any superfluous information such as leading and trailing white space. + */ + public abstract void clean(); + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public abstract boolean equals(Object otherObject); + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public abstract String toString(); + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public abstract int hashCode(); + + /** + * Copy this concept to another object. The target object must have the same class as the source object. + * + * @param target the target object to which this object is copied + * @return the copied object + */ + public abstract AxConcept copyTo(AxConcept target); + + /** + * Gets the ID string of this concept. + * + * @return the ID string of this concept + */ + public String getID() { + return getKey().getID(); + } + + /** + * Checks if this key matches the given key ID. + * + * @param id the key ID to match against + * @return true, if this key matches the ID + */ + public final boolean matchesID(final String id) { + Assertions.argumentNotNull(id, "id may not be null"); + + // Check the ID + return getID().equals(id); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetter.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetter.java new file mode 100644 index 000000000..0735f87c3 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetter.java @@ -0,0 +1,77 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.Set; + +/** + * This interface is used to allow get methods to be placed on concepts that have embedded maps. + *

+ * It forces those concepts with maps to implement the get methods specified on this interface as convenience methods to avoid concept users having to use a + * second level of referencing to access concepts in the the maps. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of concept on which the interface is applied. + */ +public interface AxConceptGetter { + + /** + * Get the latest version for a concept with the given key. + * + * @param conceptKey The key of the concept + * @return The concept + */ + C get(AxArtifactKey conceptKey); + + /** + * Get the latest version for a concept with the given key name. + * + * @param conceptKeyName The name of the concept + * @return The concept + */ + C get(String conceptKeyName); + + /** + * Get the latest version for a concept with the given key name and version. + * + * @param conceptKeyName The name of the concept + * @param conceptKeyVersion The version of the concept + * @return The concept + */ + C get(String conceptKeyName, String conceptKeyVersion); + + /** + * Get the all versions for a concept with the given key name. + * + * @param conceptKeyName The name of the concept + * @return The concepts + */ + Set getAll(String conceptKeyName); + + /** + * Get the all versions for a concept with the given key name and starting version. + * + * @param conceptKeyName The name of the concept + * @param conceptKeyVersion The first version version of the concept to get + * @return The concepts + */ + Set getAll(String conceptKeyName, String conceptKeyVersion); +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImpl.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImpl.java new file mode 100644 index 000000000..b4bff80c8 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxConceptGetterImpl.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.NavigableMap; +import java.util.Set; +import java.util.TreeSet; + +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * Implements concept getting from navigable maps. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of concept on which the interface implementation is applied. + */ +public class AxConceptGetterImpl implements AxConceptGetter { + + // The map from which to get concepts + private final NavigableMap conceptMap; + + /** + * Constructor that sets the concept map on which the getter methods in the interface will operate.. + * + * @param conceptMap the concept map on which the method will operate + */ + public AxConceptGetterImpl(final NavigableMap conceptMap) { + this.conceptMap = conceptMap; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.apex.core.basicmodel. + * concepts.AxArtifactKey) + */ + @Override + public C get(final AxArtifactKey conceptKey) { + return conceptMap.get(conceptKey); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String) + */ + @Override + public C get(final String conceptKeyName) { + Assertions.argumentNotNull(conceptKeyName, "conceptKeyName may not be null"); + + // The very fist key that could have this name + final AxArtifactKey lowestArtifactKey = new AxArtifactKey(conceptKeyName, "0.0.1"); + + // Check if we found a key for our name + AxArtifactKey foundKey = conceptMap.ceilingKey(lowestArtifactKey); + if (foundKey == null || !foundKey.getName().equals(conceptKeyName)) { + return null; + } + + // Look for higher versions of the key + do { + final AxArtifactKey nextkey = conceptMap.higherKey(foundKey); + if (nextkey == null || !nextkey.getName().equals(conceptKeyName)) { + break; + } + foundKey = nextkey; + } while (true); + + return conceptMap.get(foundKey); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String, java.lang.String) + */ + @Override + public C get(final String conceptKeyName, final String conceptKeyVersion) { + Assertions.argumentNotNull(conceptKeyName, "conceptKeyName may not be null"); + + if (conceptKeyVersion != null) { + return conceptMap.get(new AxArtifactKey(conceptKeyName, conceptKeyVersion)); + } else { + return this.get(conceptKeyName); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String) + */ + @Override + public Set getAll(final String conceptKeyName) { + return getAll(conceptKeyName, null); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String, java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { + final Set returnSet = new TreeSet<>(); + + if (conceptKeyName == null) { + returnSet.addAll(conceptMap.values()); + return returnSet; + } + + // The very fist key that could have this name + final AxArtifactKey lowestArtifactKey = new AxArtifactKey(conceptKeyName, "0.0.1"); + if (conceptKeyVersion != null) { + lowestArtifactKey.setVersion(conceptKeyVersion); + } + + // Check if we found a key for our name + AxArtifactKey foundKey = conceptMap.ceilingKey(lowestArtifactKey); + if (foundKey == null || !foundKey.getName().equals(conceptKeyName)) { + return returnSet; + } + returnSet.add(conceptMap.get(foundKey)); + + // Look for higher versions of the key + do { + foundKey = conceptMap.higherKey(foundKey); + if (foundKey == null || !foundKey.getName().equals(conceptKeyName)) { + break; + } + returnSet.add(conceptMap.get(foundKey)); + } while (true); + + return returnSet; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java new file mode 100644 index 000000000..36b49259b --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKey.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +/** + * The key uniquely identifies every entity in the system. This class is an abstract class to give a common parent for + * all key types in the system. + */ +public abstract class AxKey extends AxConcept { + private static final long serialVersionUID = 6281159885962014041L; + + /** Regular expression to specify the structure of key names. */ + public static final String NAME_REGEXP = "[A-Za-z0-9\\-_\\.]+"; + + /** Regular expression to specify the structure of key versions. */ + public static final String VERSION_REGEXP = "[A-Za-z0-9.]+"; + + /** Regular expression to specify the structure of key IDs. */ + public static final String KEY_ID_REGEXP = "[A-Za-z0-9\\-_\\.]+:[0-9].[0-9].[0-9]"; + + /** Specifies the value for names in NULL keys. */ + public static final String NULL_KEY_NAME = "NULL"; + + /** Specifies the value for versions in NULL keys. */ + public static final String NULL_KEY_VERSION = "0.0.0"; + + /** + * This enumeration is returned on key compatibility checks. + */ + public enum Compatibility { + /** The keys have different names. */ + DIFFERENT, + /** + * The name of the key matches but the Major version number of the keys is different (x in x.y.z do not match). + */ + MAJOR, + /** + * The name of the key matches but the Minor version number of the keys is different (y in x.y.z do not match). + */ + MINOR, + /** + * The name of the key matches but the Patch version number of the keys is different (z in x.y.z do not match). + */ + PATCH, + /** The keys match completely. */ + IDENTICAL + } + + /** + * Default constructor + */ + public AxKey() { + super(); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxKey(final AxKey copyConcept) { + super(copyConcept); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getID() + */ + @Override + public abstract String getID(); + + /** + * Return the result of a compatibility check of two keys. + * + * @param otherKey the key to check compatibility against + * @return the compatibility result of the check + */ + public abstract Compatibility getCompatibility(AxKey otherKey); + + /** + * Check if two keys are compatible, that is the keys are IDENTICAL or have only MINOR, PATCH differences. + * + * @param otherKey the key to check compatibility against + * @return true, if the keys are compatible + */ + public abstract boolean isCompatible(AxKey otherKey); +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java new file mode 100644 index 000000000..6c709fa63 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java @@ -0,0 +1,365 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.List; +import java.util.Random; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Convert; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner; +import org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * The key information on an {@link AxArtifactKey} key in an Apex policy model. Each {@link AxArtifactKey} must have an + * {@link AxKeyInfo} object. THe information held is the key's UUID and it's description. + *

+ * Validation checks that all fields are defined and that the key is valid. It also observes that descriptions are blank + * and warns if the UUID is a zero UUID. + */ + +@Entity +@Table(name = "AxKeyInfo") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexKeyInfo", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxKeyInfo", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "key", "uuid", "description" }) + +public class AxKeyInfo extends AxConcept { + private static final long serialVersionUID = -4023935924068914308L; + + private static final int MAX_DESCRIPTION_LENGTH_8192 = 8192; + private static final int UUID_BYTE_LENGTH_16 = 16; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + @Column(name = "uuid") + @Convert(converter = UUID2String.class) + @XmlJavaTypeAdapter(value = UUID2String.class) + @XmlElement(name = "UUID", required = true) + private UUID uuid; + + @Column(name = "description", length = MAX_DESCRIPTION_LENGTH_8192) + @Convert(converter = CDATAConditioner.class) + @XmlJavaTypeAdapter(value = CDATAConditioner.class) + @XmlElement(required = true) + private String description; + + /** + * The Default Constructor creates this concept with a NULL artifact key. + */ + public AxKeyInfo() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxKeyInfo(final AxKeyInfo copyConcept) { + super(copyConcept); + } + + /** + * Constructor to create this concept with the specified key. + * + * @param key the key of the concept + */ + public AxKeyInfo(final AxArtifactKey key) { + this(key, UUID.randomUUID(), "Generated description for concept referred to by key \"" + key.getID() + "\""); + } + + /** + * Constructor to create this concept and set all its fields. + * + * @param key the key of the concept + * @param uuid the UUID of the concept + * @param description the description of the concept + */ + public AxKeyInfo(final AxArtifactKey key, final UUID uuid, final String description) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(uuid, "uuid may not be null"); + Assertions.argumentNotNull(description, "description may not be null"); + + this.key = key; + this.uuid = uuid; + this.description = description.trim(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + return key.getKeys(); + } + + /** + * Sets the key of the concept. + * + * @param key the concept key + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the UUID of the concept. + * + * @return the uuid of the concept + */ + public UUID getUUID() { + return uuid; + } + + /** + * Sets the UUID of the concept. + * + * @param uuid the uuid of the concept + */ + public void setUuid(final UUID uuid) { + Assertions.argumentNotNull(uuid, "uuid may not be null"); + this.uuid = uuid; + } + + /** + * Gets the description of the concept. + * + * @return the description of the concept + */ + public String getDescription() { + return description; + } + + /** + * Sets the description of the concept. + * + * @param description the description of the concept + */ + public void setDescription(final String description) { + Assertions.argumentNotNull(description, "description may not be null"); + this.description = description.trim(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (description.trim().length() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.OBSERVATION, + "description is blank")); + } + + if (uuid.equals(new UUID(0, 0))) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.WARNING, + "UUID is a zero UUID: " + new UUID(0, 0))); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + description = description.trim(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("artifactId="); + builder.append(key); + builder.append(",uuid="); + builder.append(uuid); + builder.append(",description="); + builder.append(description); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxKeyInfo.class); + + final AxKeyInfo copy = ((AxKeyInfo) copyObject); + copy.setKey(new AxArtifactKey(key)); + copy.setUuid(UUID.fromString(uuid.toString())); + copy.setDescription(description); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + uuid.hashCode(); + result = prime * result + description.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxKeyInfo other = (AxKeyInfo) obj; + if (!key.equals(other.key)) { + return false; + } + if (!uuid.equals(other.uuid)) { + return false; + } + final String thisdesc = CDATAConditioner.clean(description); + final String otherdesc = CDATAConditioner.clean(other.description); + return thisdesc.equals(otherdesc); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxKeyInfo other = (AxKeyInfo) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!uuid.equals(other.uuid)) { + return uuid.compareTo(other.uuid); + } + return description.compareTo(other.description); + } + + /** + * Generate a reproducible UUID for a given string seed. + * + * @param seed the seed + * @return the uuid + */ + public static UUID generateReproducibleUUID(final String seed) { + final Random random; + if (seed != null && seed.length() > 0) { + random = new Random(seed.hashCode()); + } else { + random = new Random(); + } + final byte[] array = new byte[UUID_BYTE_LENGTH_16]; + random.nextBytes(array); + return UUID.nameUUIDFromBytes(array); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java new file mode 100644 index 000000000..2ddbe5def --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInformation.java @@ -0,0 +1,460 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.UUID; + +import javax.persistence.CascadeType; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * The Class AxKeyInformation holds a map of the key information for the entire Apex model. All Apex models + * {@link AxModel} must have an {@link AxKeyInformation} field. The {@link AxKeyInformation} class implements the helper + * methods of the {@link AxConceptGetter} interface to allow {@link AxKeyInfo} instances to be retrieved by calling + * methods directly on this class without referencing the contained map. + *

+ * Validation checks that the key is not null, that the key information map is not empty, that each key and value in the + * map is defined, that the key in each map entry matches the key if each entry value, and that no duplicate UUIDs + * exist. Each key information entry is then validated individually. + */ +@Entity +@Table(name = "AxKeyInformation") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxKeyInformation", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "key", "keyInfoMap" }) + +public class AxKeyInformation extends AxConcept implements AxConceptGetter { + private static final long serialVersionUID = -2746380769017043888L; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + // @formatter:off + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable( + joinColumns = { @JoinColumn(name = "keyInfoMapName", referencedColumnName = "name"), + @JoinColumn(name = "keyInfoMapVersion", referencedColumnName = "version"), }, + inverseJoinColumns = { @JoinColumn(name = "keyInfoName", referencedColumnName = "name"), + @JoinColumn(name = "keyInfoVersion", referencedColumnName = "version") }) + private Map keyInfoMap; + // @formatter:on + + /** + * The Default Constructor creates this concept with a null key. + */ + public AxKeyInformation() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxKeyInformation(final AxKeyInformation copyConcept) { + super(copyConcept); + } + + /** + * Constructor to create this concept with the specified key. + * + * @param key the key of the concept + */ + public AxKeyInformation(final AxArtifactKey key) { + this(key, new TreeMap()); + } + + /** + * Constructor to create this concept and set all its fields. + * + * @param key the key of the concept + * @param keyInfoMap the key info map of the concept + */ + public AxKeyInformation(final AxArtifactKey key, final Map keyInfoMap) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(keyInfoMap, "keyInfoMap may not be null"); + + this.key = key; + this.keyInfoMap = new TreeMap<>(); + this.keyInfoMap.putAll(keyInfoMap); + } + + /** + * When a model is unmarshalled from disk or from the database, the key information map is returned as a raw Hash + * Map. This method is called by JAXB after unmarshaling and is used to convert the hash map to a + * {@link NavigableMap} so that it will work with the {@link AxConceptGetter} interface. + * + * @param u the unmarshaler that is unmarshaling the model + * @param parent the parent object of this object in the unmarshaler + */ + public void afterUnmarshal(final Unmarshaller u, final Object parent) { + // The map must be navigable to allow name and version searching, + // unmarshaling returns a hash map + final NavigableMap navigablekeyInfoMap = new TreeMap<>(); + navigablekeyInfoMap.putAll(keyInfoMap); + keyInfoMap = navigablekeyInfoMap; + } + + /** + * This method generates default key information for all keys found in the concept passed in as a parameter that do + * not already have key information. + * + * @param concept the concept for which to generate key information + */ + public void generateKeyInfo(final AxConcept concept) { + for (final AxKey axKey : concept.getKeys()) { + if (!(axKey instanceof AxArtifactKey)) { + continue; + } + + final AxArtifactKey artifactKey = (AxArtifactKey) axKey; + if (!keyInfoMap.containsKey(artifactKey)) { + final AxKeyInfo keyInfo = new AxKeyInfo(artifactKey); + // generate a reproducible UUID + keyInfo.setUuid(AxKeyInfo.generateReproducibleUUID(keyInfo.getID() + keyInfo.getDescription())); + keyInfoMap.put(artifactKey, keyInfo); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + keyList.addAll(keyInfoMap.keySet()); + + return keyList; + } + + /** + * Sets the key of this concept. + * + * @param key the key of this concept + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the key info map of this concept. + * + * @return the key info map of this concept + */ + public Map getKeyInfoMap() { + return keyInfoMap; + } + + /** + * Sets the key info map of this concept. + * + * @param keyInfoMap the key info map of this concept + */ + public void setKeyInfoMap(final Map keyInfoMap) { + Assertions.argumentNotNull(keyInfoMap, "keyInfoMap may not be null"); + this.keyInfoMap = new TreeMap<>(); + this.keyInfoMap.putAll(keyInfoMap); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (keyInfoMap.size() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "keyInfoMap may not be empty")); + } else { + final Set uuidSet = new TreeSet<>(); + + for (final Entry keyInfoEntry : keyInfoMap.entrySet()) { + result = validateKeyInfoEntry(keyInfoEntry, uuidSet, result); + } + } + + return result; + } + + /** + * Validate an key information entry + * + * @param keyInfoEntry the key information entry + * @param uuidSet the set of UUIDs encountered in validation so far, the UUID of this entry is added to the set + * @param result the validation result to append to + * @return The validation result + */ + private AxValidationResult validateKeyInfoEntry(final Entry keyInfoEntry, + final Set uuidSet, AxValidationResult result) { + if (keyInfoEntry.getKey().equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on keyInfoMap entry " + keyInfoEntry.getKey() + " may not be the null key")); + } else if (keyInfoEntry.getValue() == null) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "value on keyInfoMap entry " + keyInfoEntry.getKey() + " may not be null")); + } else { + if (!keyInfoEntry.getKey().equals(keyInfoEntry.getValue().getKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on keyInfoMap entry " + keyInfoEntry.getKey() + " does not equal entry key " + + keyInfoEntry.getValue().getKey())); + } + + result = keyInfoEntry.getValue().validate(result); + + if (uuidSet.contains(keyInfoEntry.getValue().getUUID())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "duplicate UUID found on keyInfoMap entry " + keyInfoEntry.getKey() + ":" + + keyInfoEntry.getValue().getUUID())); + } else { + uuidSet.add(keyInfoEntry.getValue().getUUID()); + } + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + for (final Entry keyInfoEntry : keyInfoMap.entrySet()) { + keyInfoEntry.getKey().clean(); + keyInfoEntry.getValue().clean(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",keyInfoMap="); + builder.append(keyInfoMap); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxKeyInformation.class); + + final AxKeyInformation copy = ((AxKeyInformation) copyObject); + copy.setKey(new AxArtifactKey(key)); + final Map newKeyInfoMap = new TreeMap<>(); + for (final Entry keyInfoMapEntry : keyInfoMap.entrySet()) { + newKeyInfoMap.put(new AxArtifactKey(keyInfoMapEntry.getKey()), new AxKeyInfo(keyInfoMapEntry.getValue())); + } + copy.setKeyInfoMap(newKeyInfoMap); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + keyInfoMap.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxKeyInformation other = (AxKeyInformation) obj; + if (!key.equals(other.key)) { + return false; + } + return keyInfoMap.equals(other.keyInfoMap); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxKeyInformation other = (AxKeyInformation) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!keyInfoMap.equals(other.keyInfoMap)) { + return (keyInfoMap.hashCode() - other.keyInfoMap.hashCode()); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.core.basicmodel.concepts. + * AxArtifactKey) + */ + @Override + public AxKeyInfo get(final AxArtifactKey conceptKey) { + return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).get(conceptKey); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String) + */ + @Override + public AxKeyInfo get(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).get(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang. String, java.lang.String) + */ + @Override + public AxKeyInfo get(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).get(conceptKeyName, + conceptKeyVersion); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String) + */ + @Override + public Set getAll(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).getAll(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java. lang.String, java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) keyInfoMap).getAll(conceptKeyName, + conceptKeyVersion); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyUse.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyUse.java new file mode 100644 index 000000000..eeb8dc650 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyUse.java @@ -0,0 +1,252 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.List; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class records a usage of a key in the system. When the list of keys being used by a concept is built using the + * getKeys() method of the {@link AxConcept} class, an instance of this class is created for every key occurrence. The + * list of keys returned by the getKeys() method is a list of {@link AxKeyUse} objects. + *

+ * Validation checks that each key is valid. + */ + +public class AxKeyUse extends AxKey { + private static final long serialVersionUID = 2007147220109881705L; + + private AxKey usedKey; + + /** + * The Default Constructor creates this concept with a null key. + */ + public AxKeyUse() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxKeyUse(final AxKeyUse copyConcept) { + super(copyConcept); + } + + /** + * This constructor creates an instance of this class, and holds a reference to a used key. + * + * @param usedKey a used key + */ + public AxKeyUse(final AxKey usedKey) { + Assertions.argumentNotNull(usedKey, "usedKey may not be null"); + this.usedKey = usedKey; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxKey getKey() { + return usedKey; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + return usedKey.getKeys(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxKey#getID() + */ + @Override + public String getID() { + return usedKey.getID(); + } + + /** + * Sets the key. + * + * @param key the key + */ + public void setKey(final AxKey key) { + Assertions.argumentNotNull(key, "usedKey may not be null"); + this.usedKey = key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxKey#getCompatibility(org.onap.policy.apex.model.basicmodel. + * concepts.AxKey) + */ + @Override + public AxKey.Compatibility getCompatibility(final AxKey otherKey) { + return usedKey.getCompatibility(otherKey); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxKey#isCompatible(org.onap.policy.apex.model.basicmodel.concepts. + * AxKey) + */ + @Override + public boolean isCompatible(final AxKey otherKey) { + return usedKey.isCompatible(otherKey); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult result) { + if (usedKey.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(usedKey, this.getClass(), ValidationResult.INVALID, + "usedKey is a null key")); + } + return usedKey.validate(result); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + usedKey.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("usedKey="); + builder.append(usedKey); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxKeyUse.class); + + final AxKeyUse copy = ((AxKeyUse) copyObject); + try { + copy.usedKey = usedKey.getClass().newInstance(); + } catch (final Exception e) { + throw new ApexRuntimeException("error copying concept key: " + e.getMessage(), e); + } + usedKey.copyTo(copy.usedKey); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + usedKey.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("comparison object may not be null"); + } + + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxKeyUse other = (AxKeyUse) obj; + return usedKey.equals(other.usedKey); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + Assertions.argumentNotNull(otherObj, "comparison object may not be null"); + + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxKeyUse other = (AxKeyUse) otherObj; + + return usedKey.compareTo(other.usedKey); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java new file mode 100644 index 000000000..dac1d693c --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java @@ -0,0 +1,479 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.persistence.CascadeType; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is the base class for all models in Apex. All model classes inherit from this model so all models must + * have a key and have key information. + *

+ * Validation checks that the model key is valid. It goes on to check for null keys and checks each key for uniqueness + * in the model. A check is carried out to ensure that an {@link AxKeyInfo} instance exists for every + * {@link AxArtifactKey} key. For each {@link AxReferenceKey} instance, a check is made that its parent and local name + * are nut null and that a {@link AxKeyInfo} entry exists for its parent. Then a check is made that each used + * {@link AxArtifactKey} and {@link AxReferenceKey} usage references a key that exists. Finally, a check is made to + * ensure that an {@link AxArtifactKey} instance exists for every {@link AxKeyInfo} instance. + */ + +@Entity +@Table(name = "AxModel") +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) + +@XmlRootElement(name = "apexModel", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxModel", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "key", "keyInformation" }) + +public class AxModel extends AxConcept { + private static final String IS_A_NULL_KEY = " is a null key"; + + private static final long serialVersionUID = -771659065637205430L; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + // @formatter:off + @OneToOne(cascade = CascadeType.ALL) + @JoinColumns({ @JoinColumn(name = "keyInformationName", referencedColumnName = "name"), + @JoinColumn(name = "keyInformationVersion", referencedColumnName = "version") }) + @XmlElement(name = "keyInformation", required = true) + private AxKeyInformation keyInformation; + // @formatter:on + + /** + * The Default Constructor creates this concept with a NULL artifact key. + */ + public AxModel() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxModel(final AxModel copyConcept) { + super(copyConcept); + } + + /** + * Constructor to create this concept with the specified key. + * + * @param key the key of this concept + */ + public AxModel(final AxArtifactKey key) { + this(key, new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion()))); + } + + /** + * Constructor to create this concept and set all its fields. + * + * @param key the key of this concept + * @param keyInformation the key information of this concept + */ + public AxModel(final AxArtifactKey key, final AxKeyInformation keyInformation) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(keyInformation, "keyInformation may not be null"); + + this.key = key; + this.keyInformation = keyInformation; + } + + /** + * Registers this model with the {@link ModelService}. All models are registered with the model service so that + * models can be references from anywhere in the Apex system without being passed as references through deep call + * chains. + */ + public void register() { + ModelService.registerModel(AxKeyInformation.class, getKeyInformation()); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + + // We just add the key for the KeyInformation itself. We don't add the + // keys from key information because + // that is a list of key information for existing keys + keyList.add(keyInformation.getKey()); + + return keyList; + } + + /** + * Sets the key of this concept. + * + * @param key the key of this concept + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the key information of this concept. + * + * @return the key information of this concept + */ + public AxKeyInformation getKeyInformation() { + return keyInformation; + } + + /** + * Sets the key information of this concept. + * + * @param keyInformation the key information of this concept + */ + public void setKeyInformation(final AxKeyInformation keyInformation) { + Assertions.argumentNotNull(keyInformation, "keyInformation may not be null"); + this.keyInformation = keyInformation; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + result = keyInformation.validate(result); + + // Key consistency check + final Set artifactKeySet = new TreeSet<>(); + final Set referenceKeySet = new TreeSet<>(); + final Set usedKeySet = new TreeSet<>(); + + for (final AxKey axKey : this.getKeys()) { + // Check for the two type of keys we have + if (axKey instanceof AxArtifactKey) { + result = validateArtifactKeyInModel((AxArtifactKey) axKey, artifactKeySet, result); + } else if (axKey instanceof AxReferenceKey) { + result = validateReferenceKeyInModel((AxReferenceKey) axKey, referenceKeySet, result); + } + // It must be an AxKeyUse, nothing else is legal + else { + usedKeySet.add((AxKeyUse) axKey); + } + } + + // Check all reference keys have correct parent keys + for (final AxReferenceKey referenceKey : referenceKeySet) { + if (!artifactKeySet.contains(referenceKey.getParentArtifactKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "parent artifact key not found for reference key " + referenceKey)); + } + } + + result = validateKeyUses(usedKeySet, artifactKeySet, referenceKeySet, result); + + // Check key information for unused key information + for (final AxArtifactKey keyInfoKey : keyInformation.getKeyInfoMap().keySet()) { + if (!artifactKeySet.contains(keyInfoKey)) { + result.addValidationMessage(new AxValidationMessage(keyInfoKey, this.getClass(), + ValidationResult.WARNING, "key not found for key information entry")); + } + } + + return result; + } + + /** + * Check for consistent usage of an artifact key in the model + * + * @param artifactKey The artifact key to check + * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to the set + * @param result The validation result to append to + * @return the result of the validation + */ + private AxValidationResult validateArtifactKeyInModel(final AxArtifactKey artifactKey, + final Set artifactKeySet, final AxValidationResult result) { + // Null key check + if (artifactKey.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key " + artifactKey + IS_A_NULL_KEY)); + } + + // Null key name start check + if (artifactKey.getName().toUpperCase().startsWith(AxKey.NULL_KEY_NAME)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key " + artifactKey + " name starts with keyword " + AxKey.NULL_KEY_NAME)); + } + + // Unique key check + if (artifactKeySet.contains(artifactKey)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "duplicate key " + artifactKey + " found")); + } else { + artifactKeySet.add(artifactKey); + } + + // Key information check + if (!keyInformation.getKeyInfoMap().containsKey(artifactKey)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key information not found for key " + artifactKey)); + } + + return result; + } + + /** + * Check for consistent usage of a reference key in the model + * + * @param artifactKey The reference key to check + * @param referenceKeySet The set of reference keys encountered so far, this key is appended to the set + * @param result The validation result to append to + * @return the result of the validation + */ + private AxValidationResult validateReferenceKeyInModel(final AxReferenceKey referenceKey, + final Set referenceKeySet, final AxValidationResult result) { + // Null key check + if (referenceKey.equals(AxReferenceKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key " + referenceKey + IS_A_NULL_KEY)); + } + + // Null parent key check + if (referenceKey.getParentArtifactKey().equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "parent artifact key of key " + referenceKey + IS_A_NULL_KEY)); + } + + // Null local name check + if (referenceKey.getLocalName().equals(AxKey.NULL_KEY_NAME)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key " + referenceKey + " has a null local name")); + } + + // Null key name start check + if (referenceKey.getParentArtifactKey().getName().toUpperCase().startsWith(AxKey.NULL_KEY_NAME)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key " + referenceKey + " parent name starts with keyword " + AxKey.NULL_KEY_NAME)); + } + + // Unique key check + if (referenceKeySet.contains(referenceKey)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "duplicate key " + referenceKey + " found")); + } else { + referenceKeySet.add(referenceKey); + } + + // Key information check + if (!keyInformation.getKeyInfoMap().containsKey(referenceKey.getParentArtifactKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key information not found for parent key of key " + referenceKey)); + } + + return result; + } + + /** + * Check for consistent usage of cross-key references in the model + * + * @param usedKeySet The set of all keys used in the model + * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to the set + * @param referenceKeySet The set of reference keys encountered so far, this key is appended to the set + * @param result The validation result to append to + * @return the result of the validation + */ + private AxValidationResult validateKeyUses(final Set usedKeySet, final Set artifactKeySet, + final Set referenceKeySet, final AxValidationResult result) { + // Check all key uses + for (final AxKeyUse usedKey : usedKeySet) { + if (usedKey.getKey() instanceof AxArtifactKey) { + // AxArtifact key usage, check the key exists + if (!artifactKeySet.contains(usedKey.getKey())) { + result.addValidationMessage(new AxValidationMessage(usedKey.getKey(), this.getClass(), + ValidationResult.INVALID, "an artifact key used in the model is not defined")); + } + } else { + // AxReference key usage, check the key exists + if (!referenceKeySet.contains(usedKey.getKey())) { + result.addValidationMessage(new AxValidationMessage(usedKey.getKey(), this.getClass(), + ValidationResult.INVALID, "a reference key used in the model is not defined")); + } + } + } + + return result; + } + + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + keyInformation.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",keyInformation="); + builder.append(keyInformation); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxModel.class); + + final AxModel copy = ((AxModel) copyObject); + copy.setKey(new AxArtifactKey(key)); + copy.setKeyInformation(new AxKeyInformation(keyInformation)); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + keyInformation.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxModel other = (AxModel) obj; + if (!key.equals(other.key)) { + return false; + } + return keyInformation.equals(other.keyInformation); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxModel other = (AxModel) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + return keyInformation.compareTo(other.keyInformation); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxReferenceKey.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxReferenceKey.java new file mode 100644 index 000000000..5965dd02b --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxReferenceKey.java @@ -0,0 +1,579 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * A reference key identifies entities in the system that are contained in other entities. Every contained concept in + * the system must have an {@link AxReferenceKey} to identify it. Non-contained first order concepts are identified + * using an {@link AxArtifactKey} key. + *

+ * An {@link AxReferenceKey} contains an {@link AxArtifactKey} key reference to the first order entity that contains it. + * The local name of the reference key must uniquely identify the referenced concept among those concepts contained in + * the reference key's parent. In other words, if a parent concept has more than one child, the local name in the key of + * all its children must be unique. + *

+ * If a reference key's parent is itself a reference key, then the parent's local name must be set in the reference key. + * If the parent is a first order concept, then the parent's local name in the key will be set to NULL. + *

+ * Key validation checks that the parent name and parent version fields match the {@link NAME_REGEXP} and + * {@link VERSION_REGEXP} regular expressions respectively and that the local name fields match the + * {@link LOCAL_NAME_REGEXP} regular expression. + */ +@Embeddable +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexReferenceKey", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxReferenceKey", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "parentKeyName", "parentKeyVersion", "parentLocalName", "localName" }) + +public class AxReferenceKey extends AxKey { + private static final String PARENT_KEY_NAME = "parentKeyName"; + private static final String PARENT_KEY_VERSION = "parentKeyVersion"; + private static final String PARENT_LOCAL_NAME = "parentLocalName"; + private static final String LOCAL_NAME = "localName"; + + private static final long serialVersionUID = 8932717618579392561L; + + /** Regular expression to specify the structure of local names in reference keys. */ + public static final String LOCAL_NAME_REGEXP = "[A-Za-z0-9\\-_\\.]+|^$"; + + /** Regular expression to specify the structure of IDs in reference keys. */ + public static final String REFERENCE_KEY_ID_REGEXP = + "[A-Za-z0-9\\-_]+:[0-9].[0-9].[0-9]:[A-Za-z0-9\\-_]+:[A-Za-z0-9\\-_]+"; + + private static final int PARENT_NAME_FIELD = 0; + private static final int PARENT_VERSION_FIELD = 1; + private static final int PARENT_LOCAL_NAME_FIELD = 2; + private static final int LOCAL_NAME_FIELD = 3; + + @Column(name = PARENT_KEY_NAME) + @XmlElement(required = true) + private String parentKeyName; + + @Column(name = PARENT_KEY_VERSION) + @XmlElement(required = true) + private String parentKeyVersion; + + @Column(name = PARENT_LOCAL_NAME) + @XmlElement(required = true) + private String parentLocalName; + + @Column(name = LOCAL_NAME) + @XmlElement(required = true) + private String localName; + + /** + * The default constructor creates a null reference key. + */ + public AxReferenceKey() { + this(NULL_KEY_NAME, NULL_KEY_VERSION, NULL_KEY_NAME, NULL_KEY_NAME); + } + + /** + * The Copy Constructor creates a key by copying another key. + * + * @param referenceKey the reference key to copy from + */ + public AxReferenceKey(final AxReferenceKey referenceKey) { + this(referenceKey.getParentKeyName(), referenceKey.getParentKeyVersion(), referenceKey.getParentLocalName(), + referenceKey.getLocalName()); + } + + /** + * Constructor to create a null reference key for the specified parent artifact key. + * + * @param axArtifactKey the parent artifact key of this reference key + */ + public AxReferenceKey(final AxArtifactKey axArtifactKey) { + this(axArtifactKey.getName(), axArtifactKey.getVersion(), NULL_KEY_NAME, NULL_KEY_NAME); + } + + /** + * Constructor to create a reference key for the given parent artifact key with the given local name. + * + * @param axArtifactKey the parent artifact key of this reference key + * @param localName the local name of this reference key + */ + public AxReferenceKey(final AxArtifactKey axArtifactKey, final String localName) { + this(axArtifactKey, NULL_KEY_NAME, localName); + } + + /** + * Constructor to create a reference key for the given parent reference key with the given local name. + * + * @param parentReferenceKey the parent reference key of this reference key + * @param localName the local name of this reference key + */ + public AxReferenceKey(final AxReferenceKey parentReferenceKey, final String localName) { + this(parentReferenceKey.getParentArtifactKey(), parentReferenceKey.getLocalName(), localName); + } + + /** + * Constructor to create a reference key for the given parent reference key (specified by the parent reference key's + * artifact key and local name) with the given local name. + * + * @param axArtifactKey the artifact key of the parent reference key of this reference key + * @param parentLocalName the local name of the parent reference key of this reference key + * @param localName the local name of this reference key + */ + public AxReferenceKey(final AxArtifactKey axArtifactKey, final String parentLocalName, final String localName) { + this(axArtifactKey.getName(), axArtifactKey.getVersion(), parentLocalName, localName); + } + + /** + * Constructor to create a reference key for the given parent artifact key (specified by the parent artifact key's + * name and version) with the given local name. + * + * @param parentKeyName the name of the parent artifact key of this reference key + * @param parentKeyVersion the version of the parent artifact key of this reference key + * @param localName the local name of this reference key + */ + public AxReferenceKey(final String parentKeyName, final String parentKeyVersion, final String localName) { + this(parentKeyName, parentKeyVersion, NULL_KEY_NAME, localName); + } + + /** + * Constructor to create a reference key for the given parent key (specified by the parent key's name, version nad + * local name) with the given local name. + * + * @param parentKeyName the parent key name of this reference key + * @param parentKeyVersion the parent key version of this reference key + * @param parentLocalName the parent local name of this reference key + * @param localName the local name of this reference key + */ + public AxReferenceKey(final String parentKeyName, final String parentKeyVersion, final String parentLocalName, + final String localName) { + super(); + this.parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); + this.parentKeyVersion = + Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); + this.parentLocalName = + Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); + this.localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); + } + + /** + * Constructor to create a key from the specified key ID. + * + * @param id the key ID in a format that respects the {@link KEY_ID_REGEXP} + */ + public AxReferenceKey(final String id) { + final String conditionedId = Assertions.validateStringParameter("id", id, REFERENCE_KEY_ID_REGEXP); + + // Split on colon, if the id passes the regular expression test above + // it'll have just three colons separating the parent name, + // parent version, parent local name, and and local name + // No need for range checks or size checks on the array + final String[] nameVersionNameArray = conditionedId.split(":"); + + // Initiate the new key + parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, nameVersionNameArray[PARENT_NAME_FIELD], + NAME_REGEXP); + parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, + nameVersionNameArray[PARENT_VERSION_FIELD], VERSION_REGEXP); + parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, + nameVersionNameArray[PARENT_LOCAL_NAME_FIELD], LOCAL_NAME_REGEXP); + localName = Assertions.validateStringParameter(LOCAL_NAME, nameVersionNameArray[LOCAL_NAME_FIELD], + LOCAL_NAME_REGEXP); + } + + /** + * Get a null reference key. + * + * @return a null reference key + */ + public static AxReferenceKey getNullKey() { + return new AxReferenceKey(AxKey.NULL_KEY_NAME, AxKey.NULL_KEY_VERSION, AxKey.NULL_KEY_NAME, + AxKey.NULL_KEY_NAME); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxReferenceKey getKey() { + return this; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = new ArrayList<>(); + keyList.add(getKey()); + return keyList; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxKey#getID() + */ + @Override + public String getID() { + return parentKeyName + ':' + parentKeyVersion + ':' + parentLocalName + ':' + localName; + } + + /** + * Gets the parent artifact key of this reference key. + * + * @return the parent artifact key of this reference key + */ + public AxArtifactKey getParentArtifactKey() { + return new AxArtifactKey(parentKeyName, parentKeyVersion); + } + + /** + * Gets the parent reference key of this reference key. + * + * @return the parent reference key of this reference key + */ + public AxReferenceKey getParentReferenceKey() { + return new AxReferenceKey(parentKeyName, parentKeyVersion, parentLocalName); + } + + /** + * Sets the parent artifact key of this reference key. + * + * @param parentKey the parent artifact key of this reference key + */ + public void setParentArtifactKey(final AxArtifactKey parentKey) { + Assertions.argumentNotNull(parentKey, "parentKey may not be null"); + + parentKeyName = parentKey.getName(); + parentKeyVersion = parentKey.getVersion(); + parentLocalName = NULL_KEY_NAME; + } + + /** + * Sets the parent reference key of this reference key. + * + * @param parentKey the parent reference key of this reference key + */ + public void setParentReferenceKey(final AxReferenceKey parentKey) { + Assertions.argumentNotNull(parentKey, "parentKey may not be null"); + + parentKeyName = parentKey.getParentKeyName(); + parentKeyVersion = parentKey.getParentKeyVersion(); + parentLocalName = parentKey.getLocalName(); + } + + /** + * Gets the parent key name of this reference key. + * + * @return the parent key name of this reference key + */ + public String getParentKeyName() { + return parentKeyName; + } + + /** + * Sets the parent key name of this reference key. + * + * @param parentKeyName the parent key name of this reference key + */ + public void setParentKeyName(final String parentKeyName) { + this.parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); + } + + /** + * Gets the parent key version of this reference key. + * + * @return the parent key version of this reference key + */ + public String getParentKeyVersion() { + return parentKeyVersion; + } + + /** + * Sets the parent key version of this reference key. + * + * @param parentKeyVersion the parent key version of this reference key + */ + public void setParentKeyVersion(final String parentKeyVersion) { + this.parentKeyVersion = + Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); + } + + /** + * Gets the parent local name of this reference key. + * + * @return the parent local name of this reference key + */ + public String getParentLocalName() { + return parentLocalName; + } + + /** + * Sets the parent local name of this reference key. + * + * @param parentLocalName the parent local name of this reference key + */ + public void setParentLocalName(final String parentLocalName) { + this.parentLocalName = + Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); + } + + /** + * Gets the local name of this reference key. + * + * @return the local name of this reference key + */ + public String getLocalName() { + return localName; + } + + /** + * Sets the local name of this reference key. + * + * @param localName the local name of this reference key + */ + public void setLocalName(final String localName) { + this.localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxKey#getCompatibility(org.onap.policy.apex.model.basicmodel. + * concepts.AxKey) + */ + @Override + public AxKey.Compatibility getCompatibility(final AxKey otherKey) { + if (!(otherKey instanceof AxReferenceKey)) { + return Compatibility.DIFFERENT; + } + final AxReferenceKey otherReferenceKey = (AxReferenceKey) otherKey; + + return this.getParentArtifactKey().getCompatibility(otherReferenceKey.getParentArtifactKey()); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxKey#isCompatible(org.onap.policy.apex.model.basicmodel.concepts. + * AxKey) + */ + @Override + public boolean isCompatible(final AxKey otherKey) { + if (!(otherKey instanceof AxReferenceKey)) { + return false; + } + final AxReferenceKey otherReferenceKey = (AxReferenceKey) otherKey; + + return this.getParentArtifactKey().isCompatible(otherReferenceKey.getParentArtifactKey()); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult result) { + try { + Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, + "parentKeyName invalid-" + e.getMessage())); + } + + try { + Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, + "parentKeyVersion invalid-" + e.getMessage())); + } + + try { + Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, + "parentLocalName invalid-" + e.getMessage())); + } + + try { + Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(this, this.getClass(), ValidationResult.INVALID, + "localName invalid-" + e.getMessage())); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); + parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP); + parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP); + localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("parentKeyName="); + builder.append(parentKeyName); + builder.append(",parentKeyVersion="); + builder.append(parentKeyVersion); + builder.append(",parentLocalName="); + builder.append(parentLocalName); + builder.append(",localName="); + builder.append(localName); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxReferenceKey.class); + + final AxReferenceKey copy = ((AxReferenceKey) copyObject); + copy.setParentKeyName(parentKeyName); + copy.setParentKeyVersion(parentKeyVersion); + copy.setLocalName(localName); + copy.setParentLocalName(parentLocalName); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + parentKeyName.hashCode(); + result = prime * result + parentKeyVersion.hashCode(); + result = prime * result + parentLocalName.hashCode(); + result = prime * result + localName.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang. Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("comparison object may not be null"); + } + + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxReferenceKey other = (AxReferenceKey) obj; + + if (!parentKeyName.equals(other.parentKeyName)) { + return false; + } + if (!parentKeyVersion.equals(other.parentKeyVersion)) { + return false; + } + if (!parentLocalName.equals(other.parentLocalName)) { + return false; + } + return localName.equals(other.localName); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + Assertions.argumentNotNull(otherObj, "comparison object may not be null"); + + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxReferenceKey other = (AxReferenceKey) otherObj; + if (!parentKeyName.equals(other.parentKeyName)) { + return parentKeyName.compareTo(other.parentKeyName); + } + if (!parentKeyVersion.equals(other.parentKeyVersion)) { + return parentKeyVersion.compareTo(other.parentKeyVersion); + } + if (!parentLocalName.equals(other.parentLocalName)) { + return parentLocalName.compareTo(other.parentLocalName); + } + return localName.compareTo(other.localName); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationMessage.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationMessage.java new file mode 100644 index 000000000..7ca0b2f3c --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationMessage.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * A validation message is created for each validation observation observed during validation of a concept. The message + * holds the key and the class of the concept on which the observation was made as well as the type of observation and a + * message describing the observation. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class AxValidationMessage { + private final AxKey observedKey; + private ValidationResult validationResult = ValidationResult.VALID; + private final String observedClass; + private final String message; + + /** + * Create an validation observation with the given fields. + * + * @param observedKey the key of the class on which the validation observation was made + * @param observedClass the class on which the validation observation was made + * @param validationResult the type of observation made + * @param message a message describing the observation + */ + public AxValidationMessage(final AxKey observedKey, final Class observedClass, + final ValidationResult validationResult, final String message) { + Assertions.argumentNotNull(observedKey, "observedKey may not be null"); + Assertions.argumentNotNull(observedClass, "observedClass may not be null"); + Assertions.argumentNotNull(validationResult, "validationResult may not be null"); + Assertions.argumentNotNull(message, "message may not be null"); + + this.observedKey = observedKey; + this.observedClass = observedClass.getCanonicalName(); + this.validationResult = validationResult; + this.message = message; + } + + /** + * Gets the key of the observation. + * + * @return the key of the observation + */ + public AxKey getObservedKey() { + return observedKey; + } + + /** + * Gets the observed class. + * + * @return the observed class + */ + public String getObservedClass() { + return observedClass; + } + + /** + * Gets the type of observation made. + * + * @return the type of observation made + */ + public ValidationResult getValidationResult() { + return validationResult; + } + + /** + * Get a description of the observation. + * + * @return the observation description + */ + public String getMessage() { + return message; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return observedKey.toString() + ':' + observedClass + ':' + validationResult.name() + ':' + message; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationResult.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationResult.java new file mode 100644 index 000000000..664cf9500 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxValidationResult.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.LinkedList; +import java.util.List; + +/** + * This class records the result of a validation and holds all validatino observation messages. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class AxValidationResult { + /** + * The ValidationResult enumeration describes the severity of a validation result. + */ + public enum ValidationResult { + /** No problems or observations were detected during validation. */ + VALID, + /** + * Observations were made on a concept (such as blank descriptions) of a nature that will not affect the use of + * the concept. + */ + OBSERVATION, + /** + * Warnings were made on a concept (such as defined but unused concepts) of a nature that may affect the use of + * the concept. + */ + WARNING, + /** + * Errors were detected on a concept (such as referenced but undefined concepts) of a nature that will affect + * the use of the concept. + */ + INVALID + } + + // The actual verification result + private ValidationResult validationResult = ValidationResult.VALID; + + // Messages collected during the verification process + private final List messageList = new LinkedList<>(); + + /** + * Check if a validation reported a valid concept, returns true if the model is usable (that is, even if the model + * has warnings or observations). + * + * @return true, if the concept is reported as valid and can be used + */ + public boolean isValid() { + return validationResult != ValidationResult.INVALID; + } + + /** + * Check if a validation reported a concept with no errors or warnings, returns true if the model is OK to use. + * + * @return true, if the concept has no warnings or errors + */ + public boolean isOK() { + return validationResult == ValidationResult.VALID || validationResult == ValidationResult.OBSERVATION; + } + + /** + * Gets the validation result. + * + * @return the validation result on a concept + */ + public ValidationResult getValidationResult() { + return validationResult; + } + + /** + * Gets the list of validation results on the concept. + * + * @return the list of validaiton results + */ + public List getMessageList() { + return messageList; + } + + /** + * Adds a validation message to the validation result, used by validate() implementations on {@link AxConcept} + * subclasses to report validaiton observations. + * + * @param validationMessage the validation message + */ + public void addValidationMessage(final AxValidationMessage validationMessage) { + messageList.add(validationMessage); + + // Check if the incoming message has a more sever status than the + // current one on the overall validation result, + // if so, the overall result goes to that level + if (validationMessage.getValidationResult().ordinal() > validationResult.ordinal()) { + validationResult = validationMessage.getValidationResult(); + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + + switch (validationResult) { + case VALID: + + builder.append("***validation of model successful***"); + return builder.toString(); + case OBSERVATION: + + builder.append("\n***observations noted during validation of model***\n"); + break; + case WARNING: + + builder.append("\n***warnings issued during validation of model***\n"); + break; + case INVALID: + builder.append("\n***validation of model failed***\n"); + break; + default: + break; + } + + for (final AxValidationMessage message : messageList) { + builder.append(message); + builder.append("\n"); + } + + builder.append("********************************"); + return builder.toString(); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/package-info.java new file mode 100644 index 000000000..294a66496 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/package-info.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * This package contains the fundamental concepts for all APEX models. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +@XmlSchema(namespace = "http://www.onap.org/policy/apex-pdp", elementFormDefault = XmlNsForm.QUALIFIED, + xmlns = { @XmlNs(namespaceURI = "http://www.onap.org/policy/apex-pdp", prefix = "") }) + +package org.onap.policy.apex.model.basicmodel.concepts; + +import javax.xml.bind.annotation.XmlNs; +import javax.xml.bind.annotation.XmlNsForm; +import javax.xml.bind.annotation.XmlSchema; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDao.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDao.java new file mode 100644 index 000000000..461f3f113 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDao.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao; + +import java.util.Collection; +import java.util.List; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; + +/** + * The Interface ApexDao describes the DAO interface for reading and writing Apex {@link AxConcept} concepts to and from + * databases using JDBC. + * + * @author Sergey Sachkov + * @author liam.fallon@ericsson.com + */ +public interface ApexDao { + + /** + * Initialize the Apex DAO with the given parameters. + * + * @param daoParameters parameters to use to access the database + * @throws ApexException on initialization errors + */ + void init(DAOParameters daoParameters) throws ApexException; + + /** + * Close the Apex DAO. + */ + void close(); + + /** + * Creates an Apex concept on the database. + * + * @param the type of the object to create, a subclass of {@link AxConcept} + * @param obj the object to create + */ + void create(T obj); + + /** + * Delete an Apex concept on the database. + * + * @param the type of the object to delete, a subclass of {@link AxConcept} + * @param obj the object to delete + */ + void delete(T obj); + + /** + * Delete an Apex concept on the database. + * + * @param the type of the object to delete, a subclass of {@link AxConcept} + * @param aClass the class of the object to delete, a subclass of {@link AxConcept} + * @param key the key of the object to delete + */ + void delete(Class aClass, AxArtifactKey key); + + /** + * Delete an Apex concept on the database. + * + * @param the type of the object to delete, a subclass of {@link AxConcept} + * @param aClass the class of the object to delete, a subclass of {@link AxConcept} + * @param key the key of the object to delete + */ + void delete(Class aClass, AxReferenceKey key); + + /** + * Create a collection of objects in the database. + * + * @param the type of the object to create, a subclass of {@link AxConcept} + * @param objs the objects to create + */ + void create(Collection objs); + + /** + * Delete a collection of objects in the database. + * + * @param the type of the objects to delete, a subclass of {@link AxConcept} + * @param objs the objects to delete + */ + void delete(Collection objs); + + /** + * Delete a collection of objects in the database referred to by artifact key. + * + * @param the type of the objects to delete, a subclass of {@link AxConcept} + * @param aClass the class of the objects to delete, a subclass of {@link AxConcept} + * @param keys the keys of the objects to delete + * @return the number of objects deleted + */ + int deleteByArtifactKey(Class aClass, Collection keys); + + /** + * Delete a collection of objects in the database referred to by reference key. + * + * @param the type of the objects to delete, a subclass of {@link AxConcept} + * @param aClass the class of the objects to delete, a subclass of {@link AxConcept} + * @param keys the keys of the objects to delete + * @return the number of objects deleted + */ + int deleteByReferenceKey(Class aClass, Collection keys); + + /** + * Delete all objects of a given class in the database. + * + * @param the type of the objects to delete, a subclass of {@link AxConcept} + * @param aClass the class of the objects to delete, a subclass of {@link AxConcept} + */ + void deleteAll(Class aClass); + + /** + * Get an object from the database, referred to by artifact key. + * + * @param the type of the object to get, a subclass of {@link AxConcept} + * @param aClass the class of the object to get, a subclass of {@link AxConcept} + * @param key the key of the object to get + * @return the object that was retrieved from the database + */ + T get(Class aClass, AxArtifactKey key); + + /** + * Get an object from the database, referred to by reference key. + * + * @param the type of the object to get, a subclass of {@link AxConcept} + * @param aClass the class of the object to get, a subclass of {@link AxConcept} + * @param key the key of the object to get + * @return the object that was retrieved from the database or null if the object was not retrieved + */ + T get(Class aClass, AxReferenceKey key); + + /** + * Get all the objects in the database of a given type. + * + * @param the type of the objects to get, a subclass of {@link AxConcept} + * @param aClass the class of the objects to get, a subclass of {@link AxConcept} + * @return the objects or null if no objects were retrieved + */ + List getAll(Class aClass); + + /** + * Get all the objects in the database of the given type with the given parent artifact key. + * + * @param the type of the objects to get, a subclass of {@link AxConcept} + * @param aClass the class of the objects to get, a subclass of {@link AxConcept} + * @param parentKey the parent key of the concepts to get + * @return the all + */ + List getAll(Class aClass, AxArtifactKey parentKey); + + /** + * Get a concept from the database with the given artifact key. + * + * @param the type of the object to get, a subclass of {@link AxConcept} + * @param aClass the class of the object to get, a subclass of {@link AxConcept} + * @param artifactID the artifact key of the concept to get + * @return the concept that matches the key or null if the concept is not retrieved + */ + T getArtifact(Class aClass, AxArtifactKey artifactID); + + /** + * Get a concept from the database with the given reference key. + * + * @param the type of the object to get, a subclass of {@link AxConcept} + * @param aClass the class of the object to get, a subclass of {@link AxConcept} + * @param artifactID the artifact key of the concept to get + * @return the concept that matches the key or null if the concept is not retrieved + */ + T getArtifact(Class aClass, AxReferenceKey artifactID); + + /** + * Get the number of instances of a concept that exist in the database. + * + * @param the type of the object to get, a subclass of {@link AxConcept} + * @param aClass the class of the object to get, a subclass of {@link AxConcept} + * @return the number of instances of the concept in the database + */ + long size(Class aClass); + + /** + * Update a concept in the database. + * + * @param the type of the object to get, a subclass of {@link AxConcept} + * @param obj the object to update + * @return the updated object + */ + T update(T obj); +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDaoFactory.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDaoFactory.java new file mode 100644 index 000000000..50724d2d7 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/ApexDaoFactory.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.utilities.Assertions; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This factory class returns an Apex DAO for the configured persistence mechanism. The factory uses the plugin class + * specified in {@link DAOParameters} to instantiate a DAO instance. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexDaoFactory { + // Get a reference to the logger + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexDaoFactory.class); + + /** + * Return an Apex DAO for the required APEX DAO plugin class. + * + * @param daoParameters parameters to use to read the database configuration information + * @return the Apex DAO + * @throws ApexException on invalid JPA plugins + */ + public ApexDao createApexDao(final DAOParameters daoParameters) throws ApexException { + Assertions.argumentNotNull(daoParameters, ApexException.class, "Parameter \"daoParameters\" may not be null"); + + // Get the class for the DAO using reflection + Object apexDaoObject = null; + try { + apexDaoObject = Class.forName(daoParameters.getPluginClass()).newInstance(); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { + LOGGER.error("Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e); + throw new ApexException( + "Apex DAO class not found for DAO plugin \"" + daoParameters.getPluginClass() + "\"", e); + } + + // Check the class is an Apex DAO + if (!(apexDaoObject instanceof ApexDao)) { + LOGGER.error("Specified Apex DAO plugin class \"" + daoParameters.getPluginClass() + + "\" does not implement the ApexDao interface"); + throw new ApexException("Specified Apex DAO plugin class \"" + daoParameters.getPluginClass() + + "\" does not implement the ApexDao interface"); + } + + return (ApexDao) apexDaoObject; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/DAOParameters.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/DAOParameters.java new file mode 100644 index 000000000..5a44d18a8 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/DAOParameters.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao; + +import java.util.Properties; + +/** + * This class is a POJO that holds properties for Apex DAOs. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class DAOParameters { + /** The default Apex DAO plugin class. */ + public static final String DEFAULT_PLUGIN_CLASS = "org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"; + + private String pluginClass = DEFAULT_PLUGIN_CLASS; + private String persistenceUnit; + + private Properties jdbcProperties = new Properties(); + + /** + * Gets the DAO plugin class, this is the DAO class to use and it must implement the {@link ApexDao} interface. + * + * @return the DAO plugin class + */ + public String getPluginClass() { + return pluginClass; + } + + /** + * Sets the DAO plugin class, a class that implements the {@link ApexDao} interface. + * + * @param daoPluginClass the DAO plugin class + */ + public void setPluginClass(final String daoPluginClass) { + pluginClass = daoPluginClass; + } + + /** + * Gets the persistence unit for the DAO. The persistence unit defines the JDBC properties the DAO will use. The + * persistence unit must defined in the {@code META-INF/persistence.xml} resource file + * + * @return the persistence unit to use for JDBC access + */ + public String getPersistenceUnit() { + return persistenceUnit; + } + + /** + * Sets the persistence unit for the DAO. The persistence unit defines the JDBC properties the DAO will use. The + * persistence unit must defined in the {@code META-INF/persistence.xml} resource file + * + * @param daoPersistenceUnit the persistence unit to use for JDBC access + */ + public void setPersistenceUnit(final String daoPersistenceUnit) { + persistenceUnit = daoPersistenceUnit; + } + + /** + * Gets the JDBC properties. + * + * @return the JDBC properties + */ + public Properties getJdbcProperties() { + return jdbcProperties; + } + + /** + * Sets the JDBC properties. + * + * @param jdbcProperties the JDBC properties + */ + public void setJdbcProperties(final Properties jdbcProperties) { + this.jdbcProperties = jdbcProperties; + } + + /** + * Gets a single JDBC property. + * + * @param key the key of the property + * @return the JDBC property + */ + public String getJdbcProperty(final String key) { + return jdbcProperties.getProperty(key); + } + + /** + * Sets a single JDBC property. + * + * @param key the key of the property + * @param value the value of the JDBC property + */ + public void setJdbcProperty(final String key, final String value) { + jdbcProperties.setProperty(key, value); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "DAOParameters [pluginClass=" + pluginClass + ", persistenceUnit=" + persistenceUnit + + ", jdbcProperties=" + jdbcProperties + "]"; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/CDATAConditioner.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/CDATAConditioner.java new file mode 100644 index 000000000..9e840da2c --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/CDATAConditioner.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao.converters; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import javax.xml.bind.annotation.adapters.XmlAdapter; + +/** + * The Class CDATAConditioner converts a CDATA String to and from database format by removing spaces at the ends of + * lines and platform-specific new line endings. + * + * @author John Keeney (John.Keeney@ericsson.com) + */ +@Converter +public class CDATAConditioner extends XmlAdapter implements AttributeConverter { + + private static final String NL = "\n"; + + /* + * (non-Javadoc) + * + * @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object) + */ + @Override + public String convertToDatabaseColumn(final String raw) { + return clean(raw); + } + + /* + * (non-Javadoc) + * + * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object) + */ + @Override + public String convertToEntityAttribute(final String db) { + return clean(db); + } + + /* + * (non-Javadoc) + * + * @see javax.xml.bind.annotation.adapters.XmlAdapter + */ + @Override + public String unmarshal(final String v) throws Exception { + return this.convertToEntityAttribute(v); + } + + /* + * (non-Javadoc) + * + * @see javax.xml.bind.annotation.adapters.XmlAdapter + */ + @Override + public String marshal(final String v) throws Exception { + return this.convertToDatabaseColumn(v); + } + + /** + * Clean. + * + * @param in the in + * @return the string + */ + public static final String clean(final String in) { + if (in == null) { + return null; + } else { + return in.replaceAll("\\s+$", "").replaceAll("\\r?\\n", NL); + } + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/UUID2String.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/UUID2String.java new file mode 100644 index 000000000..f26dfc2de --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/UUID2String.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao.converters; + +import java.util.UUID; + +import javax.persistence.AttributeConverter; +import javax.persistence.Converter; +import javax.xml.bind.annotation.adapters.XmlAdapter; + +/** + * The Class UUIDConverter converts a UUID to and from database format. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +@Converter +public class UUID2String extends XmlAdapter implements AttributeConverter { + + /* + * (non-Javadoc) + * + * @see javax.persistence.AttributeConverter#convertToDatabaseColumn(java.lang.Object) + */ + @Override + public String convertToDatabaseColumn(final UUID uuid) { + String returnString; + if (uuid == null) { + returnString = ""; + } + else { + returnString = uuid.toString(); + } + return returnString; + } + + /* + * (non-Javadoc) + * + * @see javax.persistence.AttributeConverter#convertToEntityAttribute(java.lang.Object) + */ + @Override + public UUID convertToEntityAttribute(final String uuidString) { + return UUID.fromString(uuidString); + } + + /* + * (non-Javadoc) + * + * @see javax.xml.bind.annotation.adapters.XmlAdapter + */ + @Override + public UUID unmarshal(final String v) throws Exception { + return this.convertToEntityAttribute(v); + } + + /* + * (non-Javadoc) + * + * @see javax.xml.bind.annotation.adapters.XmlAdapter + */ + @Override + public String marshal(final UUID v) throws Exception { + return this.convertToDatabaseColumn(v); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/package-info.java new file mode 100644 index 000000000..f1e9a3ba7 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/converters/package-info.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains converters used by APEX EclipseLink marshaling and unmarshaling of + * {@link org.onap.policy.apex.model.basicmodel.concepts.AxConcept} instances to and from files and databases. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +package org.onap.policy.apex.model.basicmodel.dao.converters; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java new file mode 100644 index 000000000..228362bce --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/DefaultApexDao.java @@ -0,0 +1,520 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao.impl; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.dao.ApexDao; +import org.onap.policy.apex.model.basicmodel.dao.DAOParameters; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * The Class DefaultApexDao is an JPA implementation of the {@link ApexDao} class for Apex concepts ({@link AxConcept}). + * It uses the default JPA implementation in the javax {@link Persistence} class. + * + * + * @author Sergey Sachkov (sergey.sachkov@ericsson.com) + */ +public class DefaultApexDao implements ApexDao { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(DefaultApexDao.class); + + private static final String SELECT_C_FROM = "SELECT c FROM "; + private static final String AND_C_KEY_LOCAL_NAME = "' AND c.key.localName='"; + private static final String AND_C_KEY_PARENT_KEY_VERSION = "' AND c.key.parentKeyVersion='"; + private static final String C_WHERE_C_KEY_PARENT_KEY_NAME = " c WHERE c.key.parentKeyName='"; + private static final String AND_C_KEY_VERSION = "' AND c.key.version='"; + private static final String C_WHERE_C_KEY_NAME = " c WHERE c.key.name='"; + private static final String DELETE_FROM = "DELETE FROM "; + + // Entity manager for JPA + private EntityManagerFactory emf = null; + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.dao.ApexDao#init(org.onap.policy.apex.model.basicmodel.dao.DAOParameters) + */ + @Override + public void init(final DAOParameters daoParameters) throws ApexException { + if (daoParameters == null || daoParameters.getPersistenceUnit() == null) { + LOGGER.error("Apex persistence unit parameter not set"); + throw new ApexException("Apex persistence unit parameter not set"); + } + + LOGGER.debug("Creating Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" . . ."); + try { + emf = Persistence.createEntityManagerFactory(daoParameters.getPersistenceUnit(), + daoParameters.getJdbcProperties()); + } catch (final Exception e) { + LOGGER.warn("Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed", e); + throw new ApexException( + "Creation of Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\" failed", e); + } + LOGGER.debug("Created Apex persistence unit \"" + daoParameters.getPersistenceUnit() + "\""); + } + + /** + * Gets the entity manager for this DAO. + * + * @return the entity manager + */ + protected final synchronized EntityManager getEntityManager() { + if (emf == null) { + LOGGER.warn("Apex DAO has not been initialized"); + throw new ApexRuntimeException("Apex DAO has not been initialized"); + } + + return emf.createEntityManager(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#close() + */ + @Override + public final void close() { + if (emf != null) { + emf.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#create(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public void create(final T obj) { + if (obj == null) { + return; + } + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + mg.merge(obj); + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#delete(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public void delete(final T obj) { + if (obj == null) { + return; + } + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + mg.remove(mg.contains(obj) ? obj : mg.merge(obj)); + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#delete(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey) + */ + @Override + public void delete(final Class aClass, final AxArtifactKey key) { + if (key == null) { + return; + } + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName() + AND_C_KEY_VERSION + + key.getVersion() + "'", aClass).executeUpdate(); + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#delete(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey) + */ + @Override + public void delete(final Class aClass, final AxReferenceKey key) { + if (key == null) { + return; + } + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + key.getParentKeyName() + + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion() + AND_C_KEY_LOCAL_NAME + + key.getLocalName() + "'", aClass).executeUpdate(); + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#create(java.util.Collection) + */ + @Override + public void create(final Collection objs) { + if (objs == null || objs.isEmpty()) { + return; + } + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + for (final T t : objs) { + mg.merge(t); + } + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#delete(java.util.Collection) + */ + @Override + public void delete(final Collection objs) { + if (objs == null || objs.isEmpty()) { + return; + } + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + for (final T t : objs) { + mg.remove(mg.contains(t) ? t : mg.merge(t)); + } + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#deleteByArtifactKey(java.lang.Class, java.util.Collection) + */ + @Override + public int deleteByArtifactKey(final Class aClass, final Collection keys) { + if (keys == null || keys.isEmpty()) { + return 0; + } + int deletedCount = 0; + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + for (final AxArtifactKey key : keys) { + deletedCount += mg.createQuery(DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName() + + AND_C_KEY_VERSION + key.getVersion() + "'", aClass).executeUpdate(); + } + mg.getTransaction().commit(); + } finally { + mg.close(); + } + return deletedCount; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#deleteByReferenceKey(java.lang.Class, + * java.util.Collection) + */ + @Override + public int deleteByReferenceKey(final Class aClass, + final Collection keys) { + if (keys == null || keys.isEmpty()) { + return 0; + } + int deletedCount = 0; + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + for (final AxReferenceKey key : keys) { + deletedCount += + mg.createQuery( + DELETE_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + + key.getParentKeyVersion() + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", + aClass).executeUpdate(); + } + mg.getTransaction().commit(); + } finally { + mg.close(); + } + return deletedCount; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#deleteAll(java.lang.Class) + */ + @Override + public void deleteAll(final Class aClass) { + final EntityManager mg = getEntityManager(); + try { + mg.getTransaction().begin(); + mg.createQuery(DELETE_FROM + aClass.getSimpleName() + " c ", aClass).executeUpdate(); + mg.getTransaction().commit(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#get(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey) + */ + @Override + public T get(final Class aClass, final AxArtifactKey key) { + if (aClass == null) { + return null; + } + final EntityManager mg = getEntityManager(); + try { + final T t = mg.find(aClass, key); + if (t != null) { + // This clone is created to force the JPA DAO to recurse down through the object + try { + final T clonedT = aClass.newInstance(); + t.copyTo(clonedT); + return clonedT; + } catch (final Exception e) { + LOGGER.warn("Could not clone object of class \"" + aClass.getCanonicalName() + "\"", e); + return null; + } + } else { + return null; + } + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#get(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey) + */ + @Override + public T get(final Class aClass, final AxReferenceKey key) { + if (aClass == null) { + return null; + } + final EntityManager mg = getEntityManager(); + try { + final T t = mg.find(aClass, key); + if (t != null) { + try { + final T clonedT = aClass.newInstance(); + t.copyTo(clonedT); + return clonedT; + } catch (final Exception e) { + LOGGER.warn("Could not clone object of class \"" + aClass.getCanonicalName() + "\"", e); + return null; + } + } else { + return null; + } + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#getAll(java.lang.Class) + */ + @Override + public List getAll(final Class aClass) { + if (aClass == null) { + return Collections.emptyList(); + } + final EntityManager mg = getEntityManager(); + try { + return mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + " c", aClass).getResultList(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#getAll(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey) + */ + @Override + public List getAll(final Class aClass, final AxArtifactKey parentKey) { + if (aClass == null) { + return Collections.emptyList(); + } + final EntityManager mg = getEntityManager(); + try { + return mg + .createQuery(SELECT_C_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + + parentKey.getName() + AND_C_KEY_PARENT_KEY_VERSION + parentKey.getVersion() + "'", aClass) + .getResultList(); + } finally { + mg.close(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#getArtifact(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey) + */ + @Override + public T getArtifact(final Class aClass, final AxArtifactKey key) { + if (aClass == null || key == null) { + return null; + } + final EntityManager mg = getEntityManager(); + List ret; + try { + ret = mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_NAME + key.getName() + + AND_C_KEY_VERSION + key.getVersion() + "'", aClass).getResultList(); + } finally { + mg.close(); + } + if (ret == null || ret.isEmpty()) { + return null; + } + if (ret.size() > 1) { + throw new IllegalArgumentException("More than one result was returned for search for " + aClass + + " with key " + key.getID() + ": " + ret); + } + return ret.get(0); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#getArtifact(java.lang.Class, + * org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey) + */ + @Override + public T getArtifact(final Class aClass, final AxReferenceKey key) { + if (aClass == null || key == null) { + return null; + } + final EntityManager mg = getEntityManager(); + List ret; + try { + ret = mg.createQuery(SELECT_C_FROM + aClass.getSimpleName() + C_WHERE_C_KEY_PARENT_KEY_NAME + + key.getParentKeyName() + AND_C_KEY_PARENT_KEY_VERSION + key.getParentKeyVersion() + + AND_C_KEY_LOCAL_NAME + key.getLocalName() + "'", aClass).getResultList(); + } finally { + mg.close(); + } + if (ret == null || ret.isEmpty()) { + return null; + } + if (ret.size() > 1) { + throw new IllegalArgumentException("More than one result was returned for search for " + aClass + + " with key " + key.getID() + ": " + ret); + } + return ret.get(0); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#update(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public T update(final T obj) { + final EntityManager mg = getEntityManager(); + T ret; + try { + mg.getTransaction().begin(); + ret = mg.merge(obj); + mg.flush(); + mg.getTransaction().commit(); + } finally { + mg.close(); + } + return ret; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.dao.ApexDao#size(java.lang.Class) + */ + @Override + public long size(final Class aClass) { + if (aClass == null) { + return 0; + } + final EntityManager mg = getEntityManager(); + long size = 0; + try { + size = mg.createQuery("SELECT COUNT(c) FROM " + aClass.getSimpleName() + " c", Long.class) + .getSingleResult(); + } finally { + mg.close(); + } + return size; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/package-info.java new file mode 100644 index 000000000..12e854f26 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/impl/package-info.java @@ -0,0 +1,26 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains a default DAO implementation for APEX {@link org.onap.policy.apex.model.basicmodel.concepts.AxConcept} classes that uses javax persistence. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.model.basicmodel.dao.impl; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/package-info.java new file mode 100644 index 000000000..fe551b87a --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/dao/package-info.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Defines and implements the Data Access Object (DAO) that allows Apex + * {@link org.onap.policy.apex.model.basicmodel.concepts.AxConcept} concepts to be read from and written to databases over + * JDBC. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +package org.onap.policy.apex.model.basicmodel.dao; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelCreator.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelCreator.java new file mode 100644 index 000000000..7b6d830e9 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelCreator.java @@ -0,0 +1,39 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; + +/** + * This interface is implemented by factories that create Apex models. It is mainly used by unit test classes that generate Apex models for test purposes. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of Apex model to create, must be a sub class of {@link AxModel} + */ +public interface ApexModelCreator { + + /** + * Gets the model created by the model creator. + * + * @return the model created by the model creator + */ + M getModel(); +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelException.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelException.java new file mode 100644 index 000000000..8964a5bc2 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelException.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; + +/** + * This exception is invoked if an exception occurs in model handling. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexModelException extends ApexException { + private static final long serialVersionUID = -4245694568321686450L; + + /** + * Instantiates a new apex model handling exception. + * + * @param message the message + */ + public ApexModelException(final String message) { + super(message); + } + + /** + * Instantiates a new apex model handling exception. + * + * @param message the message + * @param e the e + */ + public ApexModelException(final String message, final Exception e) { + super(message, e); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelFileWriter.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelFileWriter.java new file mode 100644 index 000000000..2312b88db --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelFileWriter.java @@ -0,0 +1,139 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.File; +import java.io.FileOutputStream; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class writes an Apex model to a file. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of Apex model to write to file, must be a sub class of {@link AxModel} + */ +public class ApexModelFileWriter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelFileWriter.class); + + // Should models being written to files be valid + private boolean validateFlag; + + /** + * Constructor, set the validation flag. + * + * @param validateFlag indicates if validation be performed prior to output + */ + public ApexModelFileWriter(final boolean validateFlag) { + this.validateFlag = validateFlag; + } + + /** + * Write a model to an XML file. + * + * @param model The model to write + * @param rootModelClass The concept class + * @param modelFileName The name of the file to write to + * @throws ApexException thrown on errors + */ + public void apexModelWriteXMLFile(final M model, final Class rootModelClass, final String modelFileName) + throws ApexException { + LOGGER.debug("running apexModelWriteXMLFile . . ."); + + final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); + modelWriter.setValidateFlag(validateFlag); + modelWriter.getCDataFieldSet().add("description"); + modelWriter.getCDataFieldSet().add("logic"); + modelWriter.getCDataFieldSet().add("uiLogic"); + + writeModelFile(model, modelWriter, modelFileName); + + LOGGER.debug("ran apexModelWriteXMLFile"); + } + + /** + * Write a model to an JSON file. + * + * @param model The model to write + * @param rootModelClass The concept class + * @param modelFileName The name of the file to write to + * @throws ApexException thrown on errors + */ + public void apexModelWriteJSONFile(final M model, final Class rootModelClass, final String modelFileName) + throws ApexException { + LOGGER.debug("running apexModelWriteJSONFile . . ."); + + final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); + modelWriter.setJsonOutput(true); + modelWriter.setValidateFlag(validateFlag); + + writeModelFile(model, modelWriter, modelFileName); + + LOGGER.debug("ran apexModelWriteJSONFile"); + } + + /** + * Checks if the validation flag is set. + * + * @return true, the validation flag is set + */ + public boolean isValidateFlag() { + return validateFlag; + } + + /** + * Sets the validate flag. + * + * @param validateFlag the validate flag value + */ + public void setValidateFlag(final boolean validateFlag) { + this.validateFlag = validateFlag; + } + + /** + * Write a model to a file using a model writer. + * + * @param model The model to write + * @param modelWriter the model writer to use to write the model to the file + * @param modelFileName the file name of the file to write to + * @throws ApexException on exceptions writing the model + */ + private void writeModelFile(final M model, final ApexModelWriter modelWriter, final String modelFileName) throws ApexException { + final File modelFile = new File(modelFileName); + if (!modelFile.getParentFile().exists() && !modelFile.getParentFile().mkdirs()) { + LOGGER.warn("could not create directory " + modelFile.getParentFile()); + throw new ApexException("could not create directory " + modelFile.getParentFile()); + } + + try { + final FileOutputStream fileOutputStream = new FileOutputStream(modelFile); + modelWriter.write(model, fileOutputStream); + fileOutputStream.close(); + } + catch (final Exception e) { + LOGGER.warn("error processing file " + modelFile.getAbsolutePath(), e); + throw new ApexException("error processing file " + modelFile.getAbsolutePath(), e); + } + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java new file mode 100644 index 000000000..b19255a5b --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelReader.java @@ -0,0 +1,279 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.net.URL; +import java.util.regex.Pattern; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.eclipse.persistence.jaxb.JAXBContextFactory; +import org.eclipse.persistence.jaxb.MarshallerProperties; +import org.eclipse.persistence.oxm.MediaType; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; +import org.onap.policy.apex.model.utilities.ResourceUtils; +import org.onap.policy.apex.model.utilities.TextFileUtils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class reads an Apex concept from an XML file into a Java Apex Concept {@link AxConcept}. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of Apex concept to read, must be a sub class of {@link AxConcept} + */ +public class ApexModelReader { + // Get a reference to the logger + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelReader.class); + + // Regular expressions for checking input types + private static final String XML_INPUT_TYPE_REGEXP = "^\\s*<\\?xml.*>\\s*"; // (starts with + private static final String JSON_INPUT_TYPE_REGEXP = "^\\s*[\\(\\{\\[][\\s+\\S]*[\\)\\}\\]]"; // starts with some kind of bracket [ or ( + // or {, then has something, then has + // and has a close bracket + + //  The root class of the concept we are reading + private final Class rootConceptClass; + + // The unmarshaller for the Apex concepts + private Unmarshaller unmarshaller = null; + + // All read concepts are validated after reading if this flag is set + private boolean validateFlag = true; + + /** + * Constructor, initiates the reader with validation on. + * + * @param rootConceptClass the root concept class for concept reading + * @throws ApexModelException the apex concept reader exception + */ + public ApexModelReader(final Class rootConceptClass) throws ApexModelException { + // Save the root concept class + this.rootConceptClass = rootConceptClass; + + try { + final JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {rootConceptClass}, null); + + // Set up the unmarshaller to carry out validation + unmarshaller = jaxbContext.createUnmarshaller(); + unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); + } + catch (final JAXBException e) { + LOGGER.error("Unable to set JAXB context", e); + throw new ApexModelException("Unable to set JAXB context", e); + } + } + + /** + * Constructor, initiates the reader. + * + * @param rootConceptClass the root concept class for concept reading + * @param validate whether to perform validation by default + * @throws ApexModelException the apex concept reader exception + */ + public ApexModelReader(final Class rootConceptClass, final boolean validate) throws ApexModelException { + this(rootConceptClass); + this.validateFlag = validate; + } + + /** + * Set the schema to use for reading XML files. + * + * @param schemaFileName the schema file to use + * @throws ApexModelException if the schema cannot be set + */ + public void setSchema(final String schemaFileName) throws ApexModelException { + // Has a schema been set + if (schemaFileName != null) { + try { + // Set the concept schema + final URL schemaURL = ResourceUtils.getURLResource(schemaFileName); + final Schema apexConceptSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaURL); + unmarshaller.setSchema(apexConceptSchema); + } + catch (final Exception e) { + LOGGER.error("Unable to load schema ", e); + throw new ApexModelException("Unable to load schema", e); + } + } + else { + // Clear the schema + unmarshaller.setSchema(null); + } + } + + /** + * This method checks the specified Apex concept XML file and reads it into an Apex concept. + * + * @param apexConceptStream the apex concept stream + * @return the Apex concept + * @throws ApexModelException on reading exceptions + */ + public C read(final InputStream apexConceptStream) throws ApexModelException { + Assertions.argumentNotNull(apexConceptStream, "concept stream may not be null"); + + return read(new BufferedReader(new InputStreamReader(apexConceptStream))); + } + + /** + * This method reads the specified Apex reader into an Apex concept. + * + * @param apexConceptReader the apex concept reader + * @return the Apex concept + * @throws ApexModelException on reading exceptions + */ + public C read(final BufferedReader apexConceptReader) throws ApexModelException { + Assertions.argumentNotNull(apexConceptReader, "concept reader may not be null"); + + LOGGER.entry("reading Apex concept into a String . . ."); + + // Get the Apex concept as a string + String apexConceptString = null; + try { + apexConceptString = TextFileUtils.getReaderAsString(apexConceptReader).trim(); + } + catch (final IOException e) { + throw new ApexModelException("Unable to read Apex concept ", e); + } + + return read(apexConceptString); + } + + /** + * This method reads the specified Apex string into an Apex concept. + * + * @param apexConceptString the apex concept as a string + * @return the Apex concept + * @throws ApexModelException on reading exceptions + */ + public C read(final String apexConceptString) throws ApexModelException { + Assertions.argumentNotNull(apexConceptString, "concept string may not be null"); + + LOGGER.entry("reading Apex concept from string . . ."); + + final String apexString = apexConceptString.trim(); + + // Set the type of input for this stream + setInputType(apexString); + + // The Apex Concept + C apexConcept = null; + + // Use JAXB to read and verify the Apex concept XML file + try { + // Load the configuration file + final StreamSource source = new StreamSource(new StringReader(apexString)); + final JAXBElement rootElement = unmarshaller.unmarshal(source, rootConceptClass); + apexConcept = rootElement.getValue(); + } + catch (final JAXBException e) { + throw new ApexModelException("Unable to unmarshal Apex concept ", e); + } + + LOGGER.debug("reading of Apex concept {} completed"); + + // Check if the concept should be validated + if (validateFlag) { + // Validate the configuration file + final AxValidationResult validationResult = apexConcept.validate(new AxValidationResult()); + LOGGER.debug(validationResult.toString()); + if (validationResult.isValid()) { + return apexConcept; + } + else { + LOGGER.error("Apex concept validation failed" + validationResult.toString()); + throw new ApexModelException("Apex concept validation failed" + validationResult.toString()); + } + } + else { + // No validation check + return apexConcept; + } + } + + /** + * Gets the value of the validation flag. + * + * @return the validation flag value + */ + public boolean getValidateFlag() { + return validateFlag; + } + + /** + * Sets the validation flag. + * + * @param validateFlag the validation flag value + */ + public void setValidateFlag(final boolean validateFlag) { + this.validateFlag = validateFlag; + } + + /** + * Set the type of input for the concept reader. + * + * @param apexConceptString The stream with + * @throws ApexModelException on errors setting input type + */ + private void setInputType(final String apexConceptString) throws ApexModelException { + // Check the input type + if (Pattern.compile(JSON_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) { + //is json + try { + unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); + unmarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true); + } + catch (final Exception e) { + LOGGER.warn("JAXB error setting marshaller for JSON Input", e); + throw new ApexModelException("JAXB error setting marshaller for JSON Input", e); + } + } + else if (Pattern.compile(XML_INPUT_TYPE_REGEXP).matcher(apexConceptString).find()) { + //is xml + try { + unmarshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML); + } + catch (final Exception e) { + LOGGER.warn("JAXB error setting marshaller for XML Input", e); + throw new ApexModelException("JAXB error setting marshaller for XML Input", e); + } + } + else { + LOGGER.warn("format of input for Apex concept is neither JSON nor XML"); + throw new ApexModelException("format of input for Apex concept is neither JSON nor XML"); + } + } + +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelSaver.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelSaver.java new file mode 100644 index 000000000..16ea1f3fa --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelSaver.java @@ -0,0 +1,95 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.File; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.utilities.Assertions; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class is used to save Apex models to file in XML or JSON format. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of Apex model to save to file, must be a sub class of {@link AxModel} + */ +public class ApexModelSaver { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelSaver.class); + + // The class of the model and the model to write to disk + private final Class rootModelClass; + private final M model; + + // The path into which to write the models + private final String writePath; + + /** + * Constructor, specifies the type of the Apex model (a sub class of {@link AxModel}), the model to write, and the path of a directory to which to write the + * model. + * + * @param rootModelClass the class of the model, a sub class of {@link AxModel} + * @param model the model to write, an instance of a sub class of {@link AxModel} + * @param writePath the directory to which models will be written. The name of the written model will be the Model Name for its key with the suffix + * {@code .xml} or {@code .json}. + */ + public ApexModelSaver(final Class rootModelClass, final M model, final String writePath) { + Assertions.argumentNotNull(rootModelClass, "argument rootModelClass may not be null"); + Assertions.argumentNotNull(model, "argument model may not be null"); + Assertions.argumentNotNull(writePath, "writePath rootModelClass may not be null"); + + this.rootModelClass = rootModelClass; + this.model = model; + this.writePath = writePath; + } + + /** + * Write an Apex model to a file in XML format. The model will be written to {@code } + * + * @throws ApexException on errors writing the Apex model + */ + public void apexModelWriteXML() throws ApexException { + LOGGER.debug("running apexModelWriteXML . . ."); + + // Write the file to disk + final File xmlFile = new File(writePath + File.separatorChar + model.getKey().getName() + ".xml"); + new ApexModelFileWriter(true).apexModelWriteXMLFile(model, rootModelClass, xmlFile.getPath()); + + LOGGER.debug("ran apexModelWriteXML"); + } + + /** + * Write an Apex model to a file in JSON format. The model will be written to {@code } + * + * @throws ApexException on errors writing the Apex model + */ + public void apexModelWriteJSON() throws ApexException { + LOGGER.debug("running apexModelWriteJSON . . ."); + + // Write the file to disk + final File jsonFile = new File(writePath + File.separatorChar + model.getKey().getName() + ".json"); + new ApexModelFileWriter(true).apexModelWriteJSONFile(model, rootModelClass, jsonFile.getPath()); + + LOGGER.debug("ran apexModelWriteJSON"); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelStringWriter.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelStringWriter.java new file mode 100644 index 000000000..3d2e50b38 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelStringWriter.java @@ -0,0 +1,149 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.ByteArrayOutputStream; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.utilities.Assertions; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class writes an Apex concept to a string. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the type of Apex concept to write to a string, must be a sub class of {@link AxConcept} + */ +public class ApexModelStringWriter { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelStringWriter.class); + + // Should concepts being written to files be valid + private boolean validateFlag; + + /** + * Constructor, set the validation flag. + * + * @param validateFlag Should validation be performed prior to output + */ + public ApexModelStringWriter(final boolean validateFlag) { + this.validateFlag = validateFlag; + } + + /** + * Write a concept to a string. + * + * @param concept The concept to write + * @param rootConceptClass The concept class + * @param jsonFlag writes JSON if true, and a generic string if false + * @return The string with the concept + * @throws ApexException thrown on errors + */ + public String writeString(final C concept, final Class rootConceptClass, final boolean jsonFlag) throws ApexException { + Assertions.argumentNotNull(concept, "concept may not be null"); + + if (jsonFlag) { + return writeJSONString(concept, rootConceptClass); + } + else { + return concept.toString(); + } + } + + /** + * Write a concept to an XML string. + * + * @param concept The concept to write + * @param rootConceptClass The concept class + * @return The string with the concept + * @throws ApexException thrown on errors + */ + public String writeXMLString(final C concept, final Class rootConceptClass) throws ApexException { + LOGGER.debug("running writeXMLString . . ."); + + final ApexModelWriter conceptWriter = new ApexModelWriter<>(rootConceptClass); + conceptWriter.setValidateFlag(validateFlag); + conceptWriter.getCDataFieldSet().add("description"); + conceptWriter.getCDataFieldSet().add("logic"); + conceptWriter.getCDataFieldSet().add("uiLogic"); + + final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); + try { + conceptWriter.write(concept, baOutputStream); + baOutputStream.close(); + } + catch (final Exception e) { + LOGGER.warn("error writing XML string", e); + throw new ApexException("error writing XML string", e); + } + + LOGGER.debug("ran writeXMLString"); + return baOutputStream.toString(); + } + + /** + * Write a concept to a JSON string. + * + * @param concept The concept to write + * @param rootConceptClass The concept class + * @return The string with the concept + * @throws ApexException thrown on errors + */ + public String writeJSONString(final C concept, final Class rootConceptClass) throws ApexException { + LOGGER.debug("running writeJSONString . . ."); + + final ApexModelWriter conceptWriter = new ApexModelWriter<>(rootConceptClass); + conceptWriter.setJsonOutput(true); + conceptWriter.setValidateFlag(validateFlag); + + final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); + try { + conceptWriter.write(concept, baOutputStream); + baOutputStream.close(); + } + catch (final Exception e) { + LOGGER.warn("error writing JSON string", e); + throw new ApexException("error writing JSON string", e); + } + + LOGGER.debug("ran writeJSONString"); + return baOutputStream.toString(); + } + + /** + * Checks if is validate flag. + * + * @return true, if checks if is validate flag + */ + public boolean isValidateFlag() { + return validateFlag; + } + + /** + * Sets the validate flag. + * + * @param validateFlag the validate flag + */ + public void setValidateFlag(final boolean validateFlag) { + this.validateFlag = validateFlag; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java new file mode 100644 index 000000000..180c2447a --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexModelWriter.java @@ -0,0 +1,278 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.Set; +import java.util.TreeSet; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +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.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.eclipse.persistence.jaxb.JAXBContextFactory; +import org.eclipse.persistence.jaxb.MarshallerProperties; +import org.eclipse.persistence.oxm.MediaType; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; +import org.w3c.dom.Document; + +/** + * This class writes an Apex concept to an XML file or JSON file from a Java Apex Concept. + * + * @author John Keeney (john.keeney@ericsson.com) + * @param the type of Apex concept to write, must be a sub class of {@link AxConcept} + */ +public class ApexModelWriter { + private static final String CONCEPT_MAY_NOT_BE_NULL = "concept may not be null"; + private static final String CONCEPT_WRITER_MAY_NOT_BE_NULL = "concept writer may not be null"; + private static final String CONCEPT_STREAM_MAY_NOT_BE_NULL = "concept stream may not be null"; + + // Get a reference to the logger + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexModelWriter.class); + + // Writing as JSON or XML + private boolean jsonOutput = false; + + // The list of fields to output as CDATA + private final Set cDataFieldSet = new TreeSet<>(); + + // The Marshaller for the Apex concepts + private Marshaller marshaller = null; + + // All written concepts are validated before writing if this flag is set + private boolean validateFlag = true; + + /** + * Constructor, initiates the writer. + * + * @param rootConceptClass the root concept class for concept reading + * @throws ApexModelException the apex concept writer exception + */ + public ApexModelWriter(final Class rootConceptClass) throws ApexModelException { + // Set up Eclipselink for XML and JSON output + System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory"); + + try { + final JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] {rootConceptClass}, null); + + // Set up the unmarshaller to carry out validation + marshaller = jaxbContext.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + marshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler()); + } + catch (final JAXBException e) { + LOGGER.error("JAXB marshaller creation exception", e); + throw new ApexModelException("JAXB marshaller creation exception", e); + } + } + + /** + * The set of fields to be output as CDATA. + * + * @return the set of fields + */ + public Set getCDataFieldSet() { + return cDataFieldSet; + } + + /** + * Return true if JSON output enabled, XML output if false. + * + * @return true for JSON output + */ + public boolean isJsonOutput() { + return jsonOutput; + } + + /** + * Set the value of JSON output, true for JSON output, false for XML output. + * + * @param jsonOutput true for JSON output + * @throws ApexModelException on errors setting output type + */ + public void setJsonOutput(final boolean jsonOutput) throws ApexModelException { + this.jsonOutput = jsonOutput; + + // Set up output specific parameters + if (this.jsonOutput) { + try { + marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON); + marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true); + } + catch (final Exception e) { + LOGGER.warn("JAXB error setting marshaller for JSON output", e); + throw new ApexModelException("JAXB error setting marshaller for JSON output", e); + } + } + else { + try { + marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_XML); + } + catch (final Exception e) { + LOGGER.warn("JAXB error setting marshaller for XML output", e); + throw new ApexModelException("JAXB error setting marshaller for XML output", e); + } + } + } + + /** + * This method validates the Apex concept then writes it into a stream. + * + * @param concept the concept to write + * @param apexConceptStream the stream to write to + * @throws ApexModelException on validation or writing exceptions + */ + public void write(final C concept, final OutputStream apexConceptStream) throws ApexModelException { + Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); + Assertions.argumentNotNull(apexConceptStream, CONCEPT_STREAM_MAY_NOT_BE_NULL); + + this.write(concept, new OutputStreamWriter(apexConceptStream)); + } + + /** + * This method validates the Apex concept then writes it into a writer. + * + * @param concept the concept to write + * @param apexConceptWriter the writer to write to + * @throws ApexModelException on validation or writing exceptions + */ + public void write(final C concept, final Writer apexConceptWriter) throws ApexModelException { + Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); + Assertions.argumentNotNull(apexConceptWriter, CONCEPT_WRITER_MAY_NOT_BE_NULL); + + // Check if we should validate the concept + if (validateFlag) { + // Validate the concept first + final AxValidationResult validationResult = concept.validate(new AxValidationResult()); + LOGGER.debug(validationResult.toString()); + if (!validationResult.isValid()) { + LOGGER.warn(validationResult.toString()); + throw new ApexModelException("Apex concept xml (" + concept.getKey().getID() + ") validation failed"); + } + } + + if (jsonOutput) { + writeJSON(concept, apexConceptWriter); + } + else { + writeXML(concept, apexConceptWriter); + } + } + + /** + * This method writes the Apex concept into a writer in XML format. + * + * @param concept the concept to write + * @param apexConceptWriter the writer to write to + * @throws ApexModelException on validation or writing exceptions + */ + private void writeXML(final C concept, final Writer apexConceptWriter) throws ApexModelException { + Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); + + LOGGER.debug("writing Apex concept XML . . ."); + + try { + // Write the concept into a DOM document, then transform to add CDATA fields and pretty print, then write out the result + final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); + final Document document = docBuilderFactory.newDocumentBuilder().newDocument(); + + // Marshal the concept into the empty document. + marshaller.marshal(concept, document); + + // Transform the DOM to the output stream + final TransformerFactory transformerFactory = TransformerFactory.newInstance(); + final Transformer domTransformer = transformerFactory.newTransformer(); + + // Pretty print + try { + domTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); + // May fail if not using XALAN XSLT engine. But not in any way vital + domTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + } + catch (final Exception ignore) { + // We ignore exceptions here and catch errors below + } + + // Convert the cDataFieldSet into a space delimited string + domTransformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cDataFieldSet.toString().replaceAll("[\\[\\]\\,]", " ")); + domTransformer.transform(new DOMSource(document), new StreamResult(apexConceptWriter)); + } + catch (JAXBException | TransformerException | ParserConfigurationException e) { + LOGGER.warn("Unable to marshal Apex concept XML", e); + throw new ApexModelException("Unable to marshal Apex concept XML", e); + } + LOGGER.debug("wrote Apex concept XML"); + } + + /** + * This method writes the Apex concept into a writer in JSON format. + * + * @param concept the concept to write + * @param apexConceptWriter the writer to write to + * @throws ApexModelException on validation or writing exceptions + */ + private void writeJSON(final C concept, final Writer apexConceptWriter) throws ApexModelException { + Assertions.argumentNotNull(concept, CONCEPT_MAY_NOT_BE_NULL); + + LOGGER.debug("writing Apex concept JSON . . ."); + + try { + marshaller.marshal(concept, apexConceptWriter); + } + catch (final JAXBException e) { + LOGGER.warn("Unable to marshal Apex concept JSON", e); + throw new ApexModelException("Unable to marshal Apex concept JSON", e); + } + LOGGER.debug("wrote Apex concept JSON"); + } + + /** + * Gets the validation flag value. + * + * @return the validation flag value + */ + public boolean getValidateFlag() { + return validateFlag; + } + + /** + * Sets the validation flag. + * + * @param validateFlag the validation flag value + */ + public void setValidateFlag(final boolean validateFlag) { + this.validateFlag = validateFlag; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexSchemaGenerator.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexSchemaGenerator.java new file mode 100644 index 000000000..6e17ab94d --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/handling/ApexSchemaGenerator.java @@ -0,0 +1,166 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.File; +import java.io.IOException; +import java.io.PrintStream; +import java.io.StringWriter; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.SchemaOutputResolver; +import javax.xml.transform.Result; +import javax.xml.transform.stream.StreamResult; + +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class generates the XML model schema from the given Apex concept classes. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ApexSchemaGenerator { + // Get a reference to the logger + private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexSchemaGenerator.class); + + /** + * A Main method to allow schema generation from the command line or from maven or scripts. + * + * @param args the command line arguments, usage is {@code ApexSchemaGenerator apex-root-class [schema-file-name]} + */ + public static void main(final String[] args) { + PrintStream printStream = null; + + if (args.length == 1) { + printStream = System.out; + } + else if (args.length == 2) { + final File schemaFile = new File(args[1]); + + try { + schemaFile.getParentFile().mkdirs(); + printStream = new PrintStream(schemaFile); + } + catch (final Exception e) { + LOGGER.error("error on Apex schema output", e); + return; + } + } + else { + LOGGER.error("usage: ApexSchemaGenerator apex-root-class [schema-file-name]"); + return; + } + + // Get the schema + final String schema = new ApexSchemaGenerator().generate(args[0]); + + // Output the schema + printStream.println(schema); + + printStream.close(); + } + + /** + * Generates the XML schema (XSD) for the Apex model described using JAXB annotations. + * + * @param rootClassName the name of the root class for schema generation + * @return The schema + */ + public String generate(final String rootClassName) { + JAXBContext jaxbContext; + try { + jaxbContext = JAXBContext.newInstance(Class.forName(rootClassName)); + } + catch (final ClassNotFoundException e) { + LOGGER.error("could not create JAXB context, root class " + rootClassName + " not found", e); + return null; + } + catch (final JAXBException e) { + LOGGER.error("could not create JAXB context", e); + return null; + } + + final ApexSchemaOutputResolver sor = new ApexSchemaOutputResolver(); + try { + jaxbContext.generateSchema(sor); + } + catch (final IOException e) { + LOGGER.error("error generating the Apex schema (XSD) file", e); + return null; + } + + String schemaString = sor.getSchema(); + schemaString = fixForUnqualifiedBug(schemaString); + + return schemaString; + } + + /** + * There is a bug in schema generation that does not specify the elements from Java Maps as being unqualified. This method "hacks" those + * elements in the schema to fix this, the elements being {@code entry}, {@code key}, and {@code value} + * + * @param schemaString The schema in which elements should be fixed + * @return the string + */ + private String fixForUnqualifiedBug(final String schemaString) { + // Fix the "entry" element + String newSchemaString = schemaString.replaceAll("", + ""); + + // Fix the "key" element + newSchemaString = newSchemaString.replaceAll(" getParameterClass() { + try { + return (Class) Class.forName(parameterClassName); + } + catch (final ClassNotFoundException e) { + throw new ApexRuntimeException("class not found for parameter class name \"" + parameterClassName + "\""); + } + } + + /** + * Gets the parameter class name. + * + * @return the parameter class name + */ + public final String getParameterClassName() { + return parameterClassName; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AbstractParameters [parameterClassName=" + parameterClassName + "]"; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ModelService.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ModelService.java new file mode 100644 index 000000000..d1ecc6031 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ModelService.java @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; + +/** + * The model service makes Apex models available to all classes in a JVM. + * + * The reason for having a model service is to avoid having to pass concept and model definitions down long call chains in modules such as the Apex engine and + * editor. The model service makes the model and concept definitions available statically. + * + * Note that the use of the model service means that only a single Apex model of a particular type may exist in Apex (particularly the engine) at any time. Of + * course the model in a JVM can be changed at any time provided all users of the model are stopped and restrted in an orderly manner. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public abstract class ModelService { + // The map holding the models + private static Map, AxConcept> modelMap = new ConcurrentHashMap<>(); + + /** + * This class is an abstract static class that cannot be extended. + */ + private ModelService() { + } + + /** + * Register a model with the model service. + * + * @param the generic type + * @param modelClass the class of the model, used to index the model + * @param model The model + */ + public static void registerModel(final Class modelClass, final M model) { + modelMap.put(modelClass, model); + } + + /** + * Remove a model from the model service. + * + * @param the generic type + * @param modelClass the class of the model, used to index the model + */ + public static void deregisterModel(final Class modelClass) { + modelMap.remove(modelClass); + } + + /** + * Get a model from the model service. + * + * @param the generic type + * @param modelClass the class of the model, used to index the model + * @return The model + */ + @SuppressWarnings("unchecked") + public static M getModel(final Class modelClass) { + final M model = (M) modelMap.get(modelClass); + + if (model == null) { + throw new ApexRuntimeException("Model for " + modelClass.getCanonicalName() + " not found in model service"); + } + + return model; + } + + /** + * Check if a model is defined on the model service. + * + * @param the generic type + * @param modelClass the class of the model, used to index the model + * @return true if the model is defined + */ + public static boolean existsModel(final Class modelClass) { + return modelMap.get(modelClass) != null; + } + + /** + * Clear all models in the model service. + */ + public static void clear() { + modelMap.clear(); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ParameterService.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ParameterService.java new file mode 100644 index 000000000..062213093 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/ParameterService.java @@ -0,0 +1,116 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; + +/** + * The parameter service makes Apex parameters available to all classes in a JVM. + * + * The reason for having a parameter service is to avoid having to pass parameters down long call chains in modules such as the Apex engine and editor. The + * parameter service makes parameters available statically. + * + * The parameter service must be used with care because changing a parameter set anywhere in a JVM will affect all users of those parameters anywhere in the + * JVM. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public abstract class ParameterService { + // The map holding the parameters + private static Map, AbstractParameters> parameterMap = new ConcurrentHashMap<>(); + + /** + * This class is an abstract static class that cannot be extended. + */ + private ParameterService() { + } + + /** + * Register parameters with the parameter service. + * + * @param

the generic type + * @param parametersClass the class of the parameter, used to index the parameter + * @param parameters the parameters + */ + public static

void registerParameters(final Class

parametersClass, final P parameters) { + parameterMap.put(parametersClass, parameters); + } + + /** + * Remove parameters from the parameter service. + * + * @param

the generic type + * @param parametersClass the class of the parameter, used to index the parameter + */ + public static

void deregisterParameters(final Class

parametersClass) { + parameterMap.remove(parametersClass); + } + + /** + * Get parameters from the parameter service. + * + * @param

the generic type + * @param parametersClass the class of the parameter, used to index the parameter + * @return The parameter + */ + @SuppressWarnings("unchecked") + public static

P getParameters(final Class

parametersClass) { + final P parameter = (P) parameterMap.get(parametersClass); + + if (parameter == null) { + throw new ApexRuntimeException("Parameters for " + parametersClass.getCanonicalName() + " not found in parameter service"); + } + + return parameter; + } + + /** + * Check if parameters is defined on the parameter service. + * + * @param

the generic type + * @param parametersClass the class of the parameter, used to index the parameter + * @return true if the parameter is defined + */ + public static

boolean existsParameters(final Class

parametersClass) { + return parameterMap.get(parametersClass) != null; + } + + /** + * Get all the entries in the parameters map. + * + * @return The entries + */ + public static Set, AbstractParameters>> getAll() { + return parameterMap.entrySet(); + } + + /** + * Clear all parameters in the parameter service. + */ + public static void clear() { + parameterMap.clear(); + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/package-info.java new file mode 100644 index 000000000..a27e45d1a --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/service/package-info.java @@ -0,0 +1,26 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains the static services in Apex that make models and parameters available to all objects in the JVM. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.model.basicmodel.service; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModel.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModel.java new file mode 100644 index 000000000..04b64207d --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModel.java @@ -0,0 +1,332 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.net.URL; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.ApexDao; +import org.onap.policy.apex.model.basicmodel.dao.ApexDaoFactory; +import org.onap.policy.apex.model.basicmodel.dao.DAOParameters; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelFileWriter; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter; +import org.onap.policy.apex.model.utilities.ResourceUtils; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This class tests reading and writing of Apex models to file and to a database using JPA. It also tests validation of Apex models. This class is designed for + * use in unit tests in modules that define Apex models. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the generic type + */ +public class TestApexModel { + private static final String MODEL_IS_INVALID = "model is invalid "; + private static final String ERROR_PROCESSING_FILE = "error processing file "; + private static final String TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE = "test model does not equal model read from XML file "; + private static final String ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL = "error creating temporary file for Apex model"; + + private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexModel.class); + + // The root model class that specifies the root to import and export from + private final Class rootModelClass; + + // The class that provides the model + private TestApexModelCreator modelCreator = null; + + /** + * Constructor, defines the subclass of {@link AxModel} that is being tested and the {@link TestApexModelCreator} object that is used to generate Apex + * models. + * + * @param rootModelClass the Apex model class, a sub class of {@link AxModel} + * @param modelCreator the @link TestApexModelCreator} that will generate Apex models of various types for testing + */ + public TestApexModel(final Class rootModelClass, final TestApexModelCreator modelCreator) { + this.rootModelClass = rootModelClass; + this.modelCreator = modelCreator; + } + + /** + * Get a test Apex model using the model creator. + * + * @return the test Apex model + */ + public final M getModel() { + return modelCreator.getModel(); + } + + /** + * Test write and read in XML format. + * + * @throws ApexException on write/read errors + */ + public final void testApexModelWriteReadXML() throws ApexException { + LOGGER.debug("running testApexModelWriteReadXML . . ."); + + final M model = modelCreator.getModel(); + + // Write the file to disk + File xmlFile; + + try { + xmlFile = File.createTempFile("ApexModel", ".xml"); + xmlFile.deleteOnExit(); + } + catch (final Exception e) { + LOGGER.warn(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); + throw new ApexException(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); + } + new ApexModelFileWriter(true).apexModelWriteXMLFile(model, rootModelClass, xmlFile.getPath()); + + // Read the file from disk + final ApexModelReader modelReader = new ApexModelReader<>(rootModelClass); + + try { + final URL apexModelURL = ResourceUtils.getLocalFile(xmlFile.getAbsolutePath()); + final M fileModel = modelReader.read(apexModelURL.openStream()); + if (!model.equals(fileModel)) { + LOGGER.warn(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + xmlFile.getAbsolutePath()); + throw new ApexException(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + xmlFile.getAbsolutePath()); + } + } + catch (final Exception e) { + LOGGER.warn(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e); + throw new ApexException(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e); + } + + final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); + modelWriter.getCDataFieldSet().add("description"); + modelWriter.getCDataFieldSet().add("logic"); + modelWriter.getCDataFieldSet().add("uiLogic"); + + final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); + modelWriter.write(model, baOutputStream); + final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray()); + final M byteArrayModel = modelReader.read(baInputStream); + if (!model.equals(byteArrayModel)) { + LOGGER.warn("test model does not equal XML marshalled and unmarshalled model"); + throw new ApexException("test model does not equal XML marshalled and unmarshalled model"); + } + + LOGGER.debug("ran testApexModelWriteReadXML"); + } + + /** + * Test write and read in JSON format. + * + * @throws ApexException on write/read errors + */ + public final void testApexModelWriteReadJSON() throws ApexException { + LOGGER.debug("running testApexModelWriteReadJSON . . ."); + + final M model = modelCreator.getModel(); + + // Write the file to disk + File jsonFile; + try { + jsonFile = File.createTempFile("ApexModel", ".xml"); + jsonFile.deleteOnExit(); + } + catch (final Exception e) { + LOGGER.warn(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); + throw new ApexException(ERROR_CREATING_TEMPORARY_FILE_FOR_APEX_MODEL, e); + } + new ApexModelFileWriter(true).apexModelWriteJSONFile(model, rootModelClass, jsonFile.getPath()); + + // Read the file from disk + final ApexModelReader modelReader = new ApexModelReader<>(rootModelClass); + + try { + final URL apexModelURL = ResourceUtils.getLocalFile(jsonFile.getAbsolutePath()); + final M fileModel = modelReader.read(apexModelURL.openStream()); + if (!model.equals(fileModel)) { + LOGGER.warn(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + jsonFile.getAbsolutePath()); + throw new ApexException(TEST_MODEL_DOES_NOT_EQUAL_MODEL_READ_FROM_XML_FILE + jsonFile.getAbsolutePath()); + } + } + catch (final Exception e) { + LOGGER.warn(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e); + throw new ApexException(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e); + } + + final ApexModelWriter modelWriter = new ApexModelWriter<>(rootModelClass); + modelWriter.setJsonOutput(true); + + final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream(); + modelWriter.write(model, baOutputStream); + final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray()); + final M byteArrayModel = modelReader.read(baInputStream); + if (!model.equals(byteArrayModel)) { + LOGGER.warn("test model does not equal JSON marshalled and unmarshalled model"); + throw new ApexException("test model does not equal JSON marshalled and unmarshalled model"); + } + + LOGGER.debug("ran testApexModelWriteReadJSON"); + } + + /** + * Test write and read of an Apex model to database using JPA. + * + * @param daoParameters the DAO parameters to use for JPA/JDBC + * @throws ApexException thrown on errors writing or reading the model to database + */ + public final void testApexModelWriteReadJPA(final DAOParameters daoParameters) throws ApexException { + LOGGER.debug("running testApexModelWriteReadJPA . . ."); + + final M model = modelCreator.getModel(); + + final ApexDao apexDao = new ApexDaoFactory().createApexDao(daoParameters); + apexDao.init(daoParameters); + + apexDao.create(model); + final M dbJPAModel = apexDao.get(rootModelClass, model.getKey()); + apexDao.close(); + + if (!model.equals(dbJPAModel)) { + LOGGER.warn("test model does not equal model written and read using generic JPA"); + throw new ApexException("test model does not equal model written and read using generic JPA"); + } + + LOGGER.debug("ran testApexModelWriteReadJPA"); + } + + /** + * Test that an Apex model is valid. + * + * @return the result of the validation + * @throws ApexException thrown on errors validating the Apex model + */ + public final AxValidationResult testApexModelValid() throws ApexException { + LOGGER.debug("running testApexModelVaid . . ."); + + final M model = modelCreator.getModel(); + final AxValidationResult result = model.validate(new AxValidationResult()); + + if (!result.isValid()) { + LOGGER.warn(MODEL_IS_INVALID + result.toString()); + throw new ApexException(MODEL_IS_INVALID + result.toString()); + } + + LOGGER.debug("ran testApexModelVaid"); + return result; + } + + /** + * Test that an Apex model is structured incorrectly. + * + * @return the result of the validation + * @throws ApexException thrown on errors validating the Apex model + */ + public final AxValidationResult testApexModelVaidateMalstructured() throws ApexException { + LOGGER.debug("running testApexModelVaidateMalstructured . . ."); + + final M model = modelCreator.getMalstructuredModel(); + final AxValidationResult result = model.validate(new AxValidationResult()); + + if (result.isValid()) { + LOGGER.warn("model should not be valid " + result.toString()); + throw new ApexException("should not be valid " + result.toString()); + } + + LOGGER.debug("ran testApexModelVaidateMalstructured"); + return result; + } + + /** + * Test that an Apex model has observations. + * + * @return the result of the validation + * @throws ApexException thrown on errors validating the Apex model + */ + public final AxValidationResult testApexModelVaidateObservation() throws ApexException { + LOGGER.debug("running testApexModelVaidateObservation . . ."); + + final M model = modelCreator.getObservationModel(); + final AxValidationResult result = model.validate(new AxValidationResult()); + + if (!result.isValid()) { + LOGGER.warn(MODEL_IS_INVALID + result.toString()); + throw new ApexException(MODEL_IS_INVALID + result.toString()); + } + + if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.OBSERVATION)) { + LOGGER.warn("model should have observations"); + throw new ApexException("model should have observations"); + } + + LOGGER.debug("ran testApexModelVaidateObservation"); + return result; + } + + /** + * Test that an Apex model has warnings. + * + * @return the result of the validation + * @throws ApexException thrown on errors validating the Apex model + */ + public final AxValidationResult testApexModelVaidateWarning() throws ApexException { + LOGGER.debug("running testApexModelVaidateWarning . . ."); + + final M model = modelCreator.getWarningModel(); + final AxValidationResult result = model.validate(new AxValidationResult()); + + if (!result.isValid()) { + LOGGER.warn(MODEL_IS_INVALID + result.toString()); + throw new ApexException(MODEL_IS_INVALID + result.toString()); + } + + if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.WARNING)) { + LOGGER.warn("model should have warnings"); + throw new ApexException("model should have warnings"); + } + + LOGGER.debug("ran testApexModelVaidateWarning"); + return result; + } + + /** + * Test that an Apex model is invalid. + * + * @return the result of the validation + * @throws ApexException thrown on errors validating the Apex model + */ + public final AxValidationResult testApexModelVaidateInvalidModel() throws ApexException { + LOGGER.debug("running testApexModelVaidateInvalidModel . . ."); + + final M model = modelCreator.getInvalidModel(); + final AxValidationResult result = model.validate(new AxValidationResult()); + + if (result.isValid()) { + LOGGER.warn("model should not be valid " + result.toString()); + throw new ApexException("should not be valid " + result.toString()); + } + + LOGGER.debug("ran testApexModelVaidateInvalidModel"); + return result; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModelCreator.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModelCreator.java new file mode 100644 index 000000000..980748926 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModelCreator.java @@ -0,0 +1,62 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.test; + +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelCreator; + +/** + * The Interface TestApexModelCreator is used to create models for Apex model tests. It is mainly used by unit tests for Apex domain models so that + * developers can write test Java programs to create models. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + * @param the generic type + */ +public interface TestApexModelCreator extends ApexModelCreator { + + /** + * Gets the malstructured model. + * + * @return the malstructured model + */ + M getMalstructuredModel(); + + /** + * Gets the observation model. + * + * @return the observation model + */ + M getObservationModel(); + + /** + * Gets the warning model. + * + * @return the warning model + */ + M getWarningModel(); + + /** + * Gets the invalid model. + * + * @return the invalid model + */ + M getInvalidModel(); +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/package-info.java new file mode 100644 index 000000000..9bbdd1cce --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/package-info.java @@ -0,0 +1,26 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains utility classes that allow testing of validation and reads and writes on APEX models to files and databases. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.model.basicmodel.test; diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java new file mode 100644 index 000000000..28f0cf7af --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/AxReferenceKeyAdapter.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.xml; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlAdapter; + +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; + +/** + * This class manages marshaling and unmarshaling of Apex {@link AxReferenceKey} concepts using JAXB. The local name in + * reference keys must have specific handling. + */ +@XmlAccessorType(XmlAccessType.PROPERTY) +@XmlType(namespace = "http://www.onap.org/policy/apex-pdp") +public class AxReferenceKeyAdapter extends XmlAdapter implements Serializable { + + private static final long serialVersionUID = -3480405083900107029L; + + /* + * (non-Javadoc) + * + * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object) + */ + @Override + public final String marshal(final AxReferenceKey key) throws Exception { + return key.getLocalName(); + } + + /* + * (non-Javadoc) + * + * @see javax.xml.bind.annotation.adapters.XmlAdapter#unmarshal(java.lang.Object) + */ + @Override + public final AxReferenceKey unmarshal(final String key) throws Exception { + final AxReferenceKey axReferenceKey = new AxReferenceKey(); + axReferenceKey.setLocalName(key); + return axReferenceKey; + } +} diff --git a/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/package-info.java b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/package-info.java new file mode 100644 index 000000000..290209d89 --- /dev/null +++ b/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/xml/package-info.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains utility classes for managing marshaling and unmarshaling of APEX models using JAXB. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +@XmlSchema(namespace = "http://www.onap.org/policy/apex-pdp", elementFormDefault = XmlNsForm.QUALIFIED, + xmlns = { @XmlNs(namespaceURI = "http://www.onap.org/policy/apex-pdp", prefix = "") }) + +package org.onap.policy.apex.model.basicmodel.xml; + +import javax.xml.bind.annotation.XmlNs; +import javax.xml.bind.annotation.XmlNsForm; +import javax.xml.bind.annotation.XmlSchema; diff --git a/model/basic-model/src/main/resources/xml/example.xsd b/model/basic-model/src/main/resources/xml/example.xsd index 9f253f29c..75ecdc323 100644 --- a/model/basic-model/src/main/resources/xml/example.xsd +++ b/model/basic-model/src/main/resources/xml/example.xsd @@ -18,7 +18,7 @@ SPDX-License-Identifier: Apache-2.0 ============LICENSE_END========================================================= --> - + diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/AxKeyTest.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/AxKeyTest.java deleted file mode 100644 index a454aaf92..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/AxKeyTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -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.fail; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxKey.Compatibility; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class AxKeyTest { - - @Test - public void testArtifactKey() { - AxArtifactKey aKey0 = new AxArtifactKey(); - AxArtifactKey aKey1 = new AxArtifactKey("name", "0.0.1"); - AxArtifactKey aKey2 = new AxArtifactKey(aKey1); - AxArtifactKey aKey3 = new AxArtifactKey(aKey1.getID()); - AxArtifactKey aKey4 = new AxArtifactKey(aKey1); - AxArtifactKey aKey5 = new AxArtifactKey(aKey1); - AxArtifactKey aKey6 = new AxArtifactKey(aKey1); - - try { - new AxArtifactKey("some bad key id"); - fail("This test should throw an exception"); - } - catch (IllegalArgumentException e) { - assertEquals("parameter \"id\": value \"some bad key id\", does not match regular expression \"[A-Za-z0-9\\-_\\.]+:[0-9].[0-9].[0-9]\"", e.getMessage()); - } - - assertEquals(AxArtifactKey.getNullKey(), aKey0); - assertEquals(aKey1, aKey2); - assertEquals(aKey1, aKey3); - - assertEquals(aKey2, aKey1.getKey()); - assertEquals(1, aKey1.getKeys().size()); - - aKey0.setName("zero"); - aKey0.setVersion("0.0.2"); - aKey3.setVersion("0.0.2"); - aKey4.setVersion("0.1.2"); - aKey5.setVersion("1.2.2"); - aKey6.setVersion("3"); - - assertEquals(Compatibility.DIFFERENT, aKey0.getCompatibility(new AxReferenceKey())); - assertEquals(Compatibility.DIFFERENT, aKey0.getCompatibility(aKey1)); - assertEquals(Compatibility.IDENTICAL, aKey2.getCompatibility(aKey1)); - assertEquals(Compatibility.PATCH, aKey3.getCompatibility(aKey1)); - assertEquals(Compatibility.MINOR, aKey4.getCompatibility(aKey1)); - assertEquals(Compatibility.MAJOR, aKey5.getCompatibility(aKey1)); - assertEquals(Compatibility.MAJOR, aKey6.getCompatibility(aKey1)); - - assertTrue(aKey1.isCompatible(aKey2)); - assertTrue(aKey1.isCompatible(aKey3)); - assertTrue(aKey1.isCompatible(aKey4)); - assertFalse(aKey1.isCompatible(aKey0)); - assertFalse(aKey1.isCompatible(aKey5)); - assertFalse(aKey1.isCompatible(new AxReferenceKey())); - - assertEquals(AxValidationResult.ValidationResult.VALID, aKey0.validate(new AxValidationResult()).getValidationResult()); - assertEquals(AxValidationResult.ValidationResult.VALID, aKey1.validate(new AxValidationResult()).getValidationResult()); - assertEquals(AxValidationResult.ValidationResult.VALID, aKey2.validate(new AxValidationResult()).getValidationResult()); - assertEquals(AxValidationResult.ValidationResult.VALID, aKey3.validate(new AxValidationResult()).getValidationResult()); - assertEquals(AxValidationResult.ValidationResult.VALID, aKey4.validate(new AxValidationResult()).getValidationResult()); - assertEquals(AxValidationResult.ValidationResult.VALID, aKey5.validate(new AxValidationResult()).getValidationResult()); - assertEquals(AxValidationResult.ValidationResult.VALID, aKey6.validate(new AxValidationResult()).getValidationResult()); - - aKey0.clean(); - assertNotNull(aKey0.toString()); - - AxArtifactKey aKey7 = new AxArtifactKey(aKey1); - assertEquals(150332875, aKey7.hashCode()); - assertEquals(0, aKey7.compareTo(aKey1)); - assertEquals(-12, aKey7.compareTo(aKey0)); - - try { - aKey0.compareTo(null); - } - catch (IllegalArgumentException e) { - assertEquals("comparison object may not be null", e.getMessage()); - } - - assertEquals(0, aKey0.compareTo(aKey0)); - assertEquals(353602977, aKey0.compareTo(new AxReferenceKey())); - - assertFalse(aKey0.equals(null)); - assertTrue(aKey0.equals(aKey0)); - assertFalse(((AxKey)aKey0).equals(new AxReferenceKey())); - } - -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxKeyInfo.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxKeyInfo.java deleted file mode 100644 index 6af662bdf..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxKeyInfo.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.UUID; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestAxKeyInfo { - - @Test - public void testAxKeyInfo() { - assertNotNull(new AxKeyInfo()); - assertNotNull(new AxKeyInfo(new AxArtifactKey())); - assertNotNull(new AxKeyInfo(new AxArtifactKey(), UUID.randomUUID(), "Key description")); - - AxKeyInfo testKeyInfo = new AxKeyInfo(); - testKeyInfo.setKey((new AxArtifactKey("PN", "0.0.1"))); - assertEquals("PN:0.0.1", testKeyInfo.getKey().getID()); - - AxArtifactKey key = new AxArtifactKey("key", "0.0.1"); - testKeyInfo.setKey(key); - assertEquals(key, testKeyInfo.getKey()); - - UUID uuid = UUID.randomUUID(); - testKeyInfo.setUuid(uuid); - assertEquals(uuid, testKeyInfo.getUUID()); - testKeyInfo.setDescription("Key Description"); - assertEquals("Key Description", testKeyInfo.getDescription()); - - AxKeyInfo clonedReferenceKey = new AxKeyInfo(testKeyInfo); - assertTrue(clonedReferenceKey.toString().startsWith("AxKeyInfo:(artifactId=AxArtifactKey:(name=key,version=0.0.1),uuid=")); - - assertFalse(testKeyInfo.hashCode() == 0); - - assertTrue(testKeyInfo.equals(testKeyInfo)); - assertTrue(testKeyInfo.equals(clonedReferenceKey)); - assertFalse(testKeyInfo.equals(null)); - assertFalse(testKeyInfo.equals(new AxArtifactKey())); - assertFalse(testKeyInfo.equals(new AxKeyInfo(new AxArtifactKey()))); - assertFalse(testKeyInfo.equals(new AxKeyInfo(key, UUID.randomUUID(), "Some Description"))); - assertFalse(testKeyInfo.equals(new AxKeyInfo(key, uuid, "Some Description"))); - assertTrue(testKeyInfo.equals(new AxKeyInfo(key, uuid, "Key Description"))); - - assertEquals(0, testKeyInfo.compareTo(testKeyInfo)); - assertEquals(0, testKeyInfo.compareTo(clonedReferenceKey)); - assertNotEquals(0, testKeyInfo.compareTo(null)); - assertNotEquals(0, testKeyInfo.compareTo(new AxArtifactKey())); - assertNotEquals(0, testKeyInfo.compareTo(new AxKeyInfo(new AxArtifactKey()))); - assertNotEquals(0, testKeyInfo.compareTo(new AxKeyInfo(key, UUID.randomUUID(), "Some Description"))); - assertNotEquals(0, testKeyInfo.compareTo(new AxKeyInfo(key, uuid, "Some Description"))); - assertEquals(0, testKeyInfo.compareTo(new AxKeyInfo(key, uuid, "Key Description"))); - - assertNotNull(testKeyInfo.getKeys()); - - AxValidationResult result = new AxValidationResult(); - result = testKeyInfo.validate(result); - assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); - - testKeyInfo.setDescription(""); - result = testKeyInfo.validate(result); - assertEquals(AxValidationResult.ValidationResult.OBSERVATION, result.getValidationResult()); - - testKeyInfo.setUuid(new UUID(0, 0)); - result = testKeyInfo.validate(result); - assertEquals(AxValidationResult.ValidationResult.WARNING, result.getValidationResult()); - - testKeyInfo.setKey(AxArtifactKey.getNullKey()); - result = testKeyInfo.validate(result); - assertEquals(AxValidationResult.ValidationResult.INVALID, result.getValidationResult()); - - assertNotNull(AxKeyInfo.generateReproducibleUUID(null)); - assertNotNull(AxKeyInfo.generateReproducibleUUID("SeedString")); - - testKeyInfo.clean(); - assertNotNull(testKeyInfo); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxReferenceKey.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxReferenceKey.java deleted file mode 100644 index 7ec3cbbbf..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestAxReferenceKey.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestAxReferenceKey { - - @Test - public void testAxReferenceKey() { - assertNotNull(new AxReferenceKey()); - assertNotNull(new AxReferenceKey(new AxArtifactKey())); - assertNotNull(new AxReferenceKey(new AxArtifactKey(), "LocalName")); - assertNotNull(new AxReferenceKey(new AxReferenceKey())); - assertNotNull(new AxReferenceKey(new AxReferenceKey(), "LocalName")); - assertNotNull(new AxReferenceKey(new AxArtifactKey(), "ParentLocalName", "LocalName")); - assertNotNull(new AxReferenceKey("ParentKeyName", "0.0.1", "LocalName")); - assertNotNull(new AxReferenceKey("ParentKeyName", "0.0.1", "ParentLocalName", "LocalName")); - assertNotNull(new AxReferenceKey("ParentKeyName:0.0.1:ParentLocalName:LocalName")); - assertEquals(AxReferenceKey.getNullKey().getKey(), AxReferenceKey.getNullKey()); - assertEquals("NULL:0.0.0:NULL:NULL", AxReferenceKey.getNullKey().getID()); - - AxReferenceKey testReferenceKey = new AxReferenceKey(); - testReferenceKey.setParentArtifactKey(new AxArtifactKey("PN", "0.0.1")); - assertEquals("PN:0.0.1", testReferenceKey.getParentArtifactKey().getID()); - - testReferenceKey.setParentReferenceKey(new AxReferenceKey("PN", "0.0.1", "LN")); - assertEquals("PN:0.0.1:NULL:LN", testReferenceKey.getParentReferenceKey().getID()); - - testReferenceKey.setParentKeyName("NPKN"); - assertEquals("NPKN", testReferenceKey.getParentKeyName()); - - testReferenceKey.setParentKeyVersion("0.0.1"); - assertEquals("0.0.1", testReferenceKey.getParentKeyVersion()); - - testReferenceKey.setParentLocalName("NPKLN"); - assertEquals("NPKLN", testReferenceKey.getParentLocalName()); - - testReferenceKey.setLocalName("NLN"); - assertEquals("NLN", testReferenceKey.getLocalName()); - - assertFalse(testReferenceKey.isCompatible(AxArtifactKey.getNullKey())); - assertFalse(testReferenceKey.isCompatible(AxReferenceKey.getNullKey())); - assertTrue(testReferenceKey.isCompatible(testReferenceKey)); - - assertEquals(AxKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(AxArtifactKey.getNullKey())); - assertEquals(AxKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(AxReferenceKey.getNullKey())); - assertEquals(AxKey.Compatibility.IDENTICAL, testReferenceKey.getCompatibility(testReferenceKey)); - - AxValidationResult result = new AxValidationResult(); - result = testReferenceKey.validate(result); - assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); - - testReferenceKey.clean(); - - AxReferenceKey clonedReferenceKey = new AxReferenceKey(testReferenceKey); - assertEquals("AxReferenceKey:(parentKeyName=NPKN,parentKeyVersion=0.0.1,parentLocalName=NPKLN,localName=NLN)", clonedReferenceKey.toString()); - - assertFalse(testReferenceKey.hashCode() == 0); - - assertTrue(testReferenceKey.equals(testReferenceKey)); - assertTrue(testReferenceKey.equals(clonedReferenceKey)); - assertFalse(testReferenceKey.equals("Hello")); - assertFalse(testReferenceKey.equals(new AxReferenceKey("PKN", "0.0.2", "PLN", "LN"))); - assertFalse(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.2", "PLN", "LN"))); - assertFalse(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.1", "PLN", "LN"))); - assertFalse(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.1", "NPLN", "LN"))); - assertTrue(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN"))); - - assertEquals(0, testReferenceKey.compareTo(testReferenceKey)); - assertEquals(0, testReferenceKey.compareTo(clonedReferenceKey)); - assertNotEquals(0, testReferenceKey.compareTo(new AxArtifactKey())); - assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("PKN", "0.0.2", "PLN", "LN"))); - assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.2", "PLN", "LN"))); - assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "PLN", "LN"))); - assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "NPLN", "LN"))); - assertEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN"))); - - assertNotNull(testReferenceKey.getKeys()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestEntity.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestEntity.java deleted file mode 100644 index 3e821f7c5..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestEntity.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import java.util.Arrays; -import java.util.List; - -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.xml.AxReferenceKeyAdapter; - -@Entity -@Table(name = "TestEntity") - -public class TestEntity extends AxConcept { - private static final long serialVersionUID = -2962570563281067894L; - - @EmbeddedId() - @XmlElement(name = "key", required = true) - @XmlJavaTypeAdapter(AxReferenceKeyAdapter.class) - protected AxReferenceKey key; - - private double doubleValue; - - public TestEntity() { - this.key = new AxReferenceKey(); - this.doubleValue = 0; - } - - public TestEntity(Double doubleValue) { - this.key = new AxReferenceKey(); - this.doubleValue = doubleValue; - } - - public TestEntity(AxReferenceKey key, Double doubleValue) { - this.key = key; - this.doubleValue = doubleValue; - } - - public AxReferenceKey getKey() { - return key; - } - - public List getKeys() { - return Arrays.asList((AxKey) getKey()); - } - - public void setKey(AxReferenceKey key) { - this.key = key; - } - - public boolean checkSetKey() { - return (this.key != null); - } - - public double getDoubleValue() { - return doubleValue; - } - - public void setDoubleValue(double doubleValue) { - this.doubleValue = doubleValue; - } - - @Override - public AxValidationResult validate(AxValidationResult result) { - return key.validate(result); - } - - @Override - public void clean() { - key.clean(); - } - - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append("doubleValue="); - builder.append(doubleValue); - return builder.toString(); - } - - @Override - public AxConcept copyTo(AxConcept target) { - final Object copyObject = ((target == null) ? new TestEntity(): target); - if (copyObject instanceof TestEntity) { - final TestEntity copy = ((TestEntity) copyObject); - if (this.checkSetKey()) { - copy.setKey(new AxReferenceKey(key)); - } - else { - copy.key = null; - } - copy.doubleValue = doubleValue; - return copy; - } - else { - return null; - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((key == null) ? 0 : key.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) - return false; - if (this == obj) - return true; - if (getClass() != obj.getClass()) - return false; - TestEntity other = (TestEntity) obj; - if (key == null) { - if (other.key != null) - return false; - } - else - if (!key.equals(other.key)) - return false; - if (doubleValue != other.doubleValue) - return false; - return true; - } - - @Override - public int compareTo(AxConcept otherObj) { - if (otherObj == null) - return -1; - if (this == otherObj) - return 0; - TestEntity other = (TestEntity) otherObj; - if (key == null) { - if (other.key != null) - return 1; - } - else - if (!key.equals(other.key)) - return key.compareTo(other.key); - if (doubleValue != other.doubleValue) - return new Double(doubleValue).compareTo(other.doubleValue); - - return 0; - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestExceptions.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestExceptions.java deleted file mode 100644 index 1d37cd8ed..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestExceptions.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexConceptException; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.ApexRuntimeException; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestExceptions { - - @Test - public void test() { - assertNotNull(new ApexException("Message")); - assertNotNull(new ApexException("Message", new AxArtifactKey())); - assertNotNull(new ApexException("Message", new IOException())); - assertNotNull(new ApexException("Message", new IOException(), new AxArtifactKey())); - - AxArtifactKey key = new AxArtifactKey(); - ApexException ae = new ApexException("Message", new IOException("IO exception message"), key); - assertEquals("Message\ncaused by: Message\ncaused by: IO exception message", ae.getCascadedMessage()); - assertEquals(key, ae.getObject()); - - assertNotNull(new ApexRuntimeException("Message")); - assertNotNull(new ApexRuntimeException("Message", new AxArtifactKey())); - assertNotNull(new ApexRuntimeException("Message", new IOException())); - assertNotNull(new ApexRuntimeException("Message", new IOException(), new AxArtifactKey())); - - AxArtifactKey rKey = new AxArtifactKey(); - ApexRuntimeException re = new ApexRuntimeException("Runtime Message", new IOException("IO runtime exception message"), rKey); - assertEquals("Runtime Message\ncaused by: Runtime Message\ncaused by: IO runtime exception message", re.getCascadedMessage()); - assertEquals(key, re.getObject()); - - assertNotNull(new ApexConceptException("Message")); - assertNotNull(new ApexConceptException("Message", new IOException())); - - AxArtifactKey cKey = new AxArtifactKey(); - ApexException ace = new ApexException("Concept Message", new IOException("IO concept exception message"), cKey); - assertEquals("Concept Message\ncaused by: Concept Message\ncaused by: IO concept exception message", ace.getCascadedMessage()); - assertEquals(cKey, ace.getObject()); - } - -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestValidation.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestValidation.java deleted file mode 100644 index e8eff5230..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/TestValidation.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -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 org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationMessage; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestValidation { - - @Test - public void test() { - AxValidationResult result = new AxValidationResult(); - AxReferenceKey refKey = new AxReferenceKey("PK", "0.0.1", "PLN", "LN"); - result = refKey.validate(result); - - assertNotNull(result); - assertTrue(result.isOK()); - assertTrue(result.isValid()); - assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); - assertNotNull(result.getMessageList()); - - AxValidationMessage vMess0 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.VALID, "Some message"); - result.addValidationMessage(vMess0); - - assertTrue(result.isOK()); - assertTrue(result.isValid()); - assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); - assertNotNull(result.getMessageList()); - assertNotNull("hello", result.toString()); - - AxValidationMessage vMess1 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.OBSERVATION, "Some message"); - result.addValidationMessage(vMess1); - - assertTrue(result.isOK()); - assertTrue(result.isValid()); - assertEquals(AxValidationResult.ValidationResult.OBSERVATION, result.getValidationResult()); - assertNotNull(result.getMessageList()); - assertNotNull("hello", result.toString()); - - AxValidationMessage vMess2 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.WARNING, "Some message"); - result.addValidationMessage(vMess2); - - assertFalse(result.isOK()); - assertTrue(result.isValid()); - assertEquals(AxValidationResult.ValidationResult.WARNING, result.getValidationResult()); - assertNotNull(result.getMessageList()); - assertNotNull("hello", result.toString()); - - AxValidationMessage vMess3 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.INVALID, "Some message"); - result.addValidationMessage(vMess3); - - assertFalse(result.isOK()); - assertFalse(result.isValid()); - assertEquals(AxValidationResult.ValidationResult.INVALID, result.getValidationResult()); - assertNotNull(result.getMessageList()); - assertNotNull("hello", result.toString()); - - assertEquals(AxValidationResult.ValidationResult.INVALID, result.getMessageList().get(3).getValidationResult()); - assertEquals("Some message", result.getMessageList().get(3).getMessage()); - assertEquals(AxArtifactKey.class.getCanonicalName(), result.getMessageList().get(3).getObservedClass()); - assertEquals(AxArtifactKey.getNullKey(), result.getMessageList().get(3).getObservedKey()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/testKeyUse.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/testKeyUse.java deleted file mode 100644 index ca1e5c191..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/concepts/testKeyUse.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyUse; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxKey.Compatibility; - -public class testKeyUse { - - @Test - public void test() { - assertNotNull(new AxKeyUse()); - assertNotNull(new AxKeyUse(new AxArtifactKey())); - assertNotNull(new AxKeyUse(new AxReferenceKey())); - - AxArtifactKey key = new AxArtifactKey("Key", "0.0.1"); - AxKeyUse keyUse = new AxKeyUse(); - keyUse.setKey(key); - assertEquals(key, keyUse.getKey()); - assertEquals("Key:0.0.1", keyUse.getID()); - assertEquals(key, keyUse.getKeys().get(0)); - - assertEquals(Compatibility.IDENTICAL, keyUse.getCompatibility(key)); - assertTrue(keyUse.isCompatible(key)); - - keyUse.clean(); - assertNotNull(keyUse); - - AxValidationResult result = new AxValidationResult(); - result = keyUse.validate(result); - assertNotNull(result); - - assertNotEquals(0, keyUse.hashCode()); - - AxKeyUse clonedKeyUse = new AxKeyUse(keyUse); - assertEquals("AxKeyUse:(usedKey=AxArtifactKey:(name=Key,version=0.0.1))", clonedKeyUse.toString()); - - assertFalse(keyUse.hashCode() == 0); - - assertTrue(keyUse.equals(keyUse)); - assertTrue(keyUse.equals(clonedKeyUse)); - assertFalse(keyUse.equals("Hello")); - assertTrue(keyUse.equals(new AxKeyUse(key))); - - assertEquals(0, keyUse.compareTo(keyUse)); - assertEquals(0, keyUse.compareTo(clonedKeyUse)); - assertNotEquals(0, keyUse.compareTo(new AxArtifactKey())); - assertEquals(0, keyUse.compareTo(new AxKeyUse(key))); - - AxKeyUse keyUseNull = new AxKeyUse(AxArtifactKey.getNullKey()); - AxValidationResult resultNull = new AxValidationResult(); - assertEquals(false, keyUseNull.validate(resultNull).isValid()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/EntityTest.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/EntityTest.java deleted file mode 100644 index 87779848e..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/EntityTest.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.UUID; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.TestEntity; -import org.onap.apex.model.basicmodel.dao.ApexDao; -import org.onap.apex.model.basicmodel.dao.ApexDaoFactory; -import org.onap.apex.model.basicmodel.dao.DAOParameters; - -/** - * JUnit test class - */ -public class EntityTest { - private Connection connection; - private ApexDao apexDao; - - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testEntityTestSanity() throws ApexException { - final DAOParameters daoParameters = new DAOParameters(); - - apexDao = new ApexDaoFactory().createApexDao(daoParameters); - - try { - apexDao.init(null); - fail("Test should throw an exception here"); - } - catch (final Exception e) { - assertEquals("Apex persistence unit parameter not set", e.getMessage()); - } - - try { - apexDao.init(daoParameters); - fail("Test should throw an exception here"); - } - catch (final Exception e) { - assertEquals("Apex persistence unit parameter not set", e.getMessage()); - } - - daoParameters.setPluginClass("somewhere.over.the.rainbow"); - daoParameters.setPersistenceUnit("Dorothy"); - try { - apexDao.init(daoParameters); - fail("Test should throw an exception here"); - } - catch (final Exception e) { - assertEquals("Creation of Apex persistence unit \"Dorothy\" failed", e.getMessage()); - } - try { - apexDao.create(new AxArtifactKey()); - fail("Test should throw an exception here"); - } - catch (final Exception e) { - assertEquals("Apex DAO has not been initialized", e.getMessage()); - } - apexDao.close(); - } - - @Test - public void testEntityTestAllOpsJPA() throws ApexException { - final DAOParameters daoParameters = new DAOParameters(); - daoParameters.setPluginClass("org.onap.apex.model.basicmodel.dao.impl.DefaultApexDao"); - daoParameters.setPersistenceUnit("DAOTest"); - - apexDao = new ApexDaoFactory().createApexDao(daoParameters); - apexDao.init(daoParameters); - - testAllOps(); - apexDao.close(); - } - - @Test - public void testEntityTestBadVals() throws ApexException { - final DAOParameters daoParameters = new DAOParameters(); - daoParameters.setPluginClass("org.onap.apex.model.basicmodel.dao.impl.DefaultApexDao"); - daoParameters.setPersistenceUnit("DAOTest"); - - apexDao = new ApexDaoFactory().createApexDao(daoParameters); - apexDao.init(daoParameters); - - final AxArtifactKey nullKey = null; - final AxReferenceKey nullRefKey = null; - final List nullKeyList = null; - final List emptyKeyList = new ArrayList<>(); - final List nullRKeyList = null; - final List emptyRKeyList = new ArrayList<>(); - - apexDao.create(nullKey); - apexDao.create(nullKeyList); - apexDao.create(emptyKeyList); - - apexDao.delete(nullKey); - apexDao.delete(nullKeyList); - apexDao.delete(emptyKeyList); - apexDao.delete(AxArtifactKey.class, nullKey); - apexDao.delete(AxReferenceKey.class, nullRefKey); - apexDao.deleteByArtifactKey(AxArtifactKey.class, nullKeyList); - apexDao.deleteByArtifactKey(AxArtifactKey.class, emptyKeyList); - apexDao.deleteByReferenceKey(AxReferenceKey.class, nullRKeyList); - apexDao.deleteByReferenceKey(AxReferenceKey.class, emptyRKeyList); - - apexDao.get(null, nullKey); - apexDao.get(null, nullRefKey); - apexDao.getAll(null); - apexDao.getAll(null, nullKey); - apexDao.getArtifact(null, nullKey); - apexDao.getArtifact(AxArtifactKey.class, nullKey); - apexDao.getArtifact(null, nullRefKey); - apexDao.getArtifact(AxReferenceKey.class, nullRefKey); - apexDao.size(null); - - apexDao.close(); - } - - private void testAllOps(){ - final AxArtifactKey aKey0 = new AxArtifactKey("A-KEY0", "0.0.1"); - final AxArtifactKey aKey1 = new AxArtifactKey("A-KEY1", "0.0.1"); - final AxArtifactKey aKey2 = new AxArtifactKey("A-KEY2", "0.0.1"); - final AxKeyInfo keyInfo0 = new AxKeyInfo(aKey0, UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0"); - final AxKeyInfo keyInfo1 = new AxKeyInfo(aKey1, UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1"); - final AxKeyInfo keyInfo2 = new AxKeyInfo(aKey2, UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2"); - - apexDao.create(keyInfo0); - - final AxKeyInfo keyInfoBack0 = apexDao.get(AxKeyInfo.class, aKey0); - assertTrue(keyInfo0.equals(keyInfoBack0)); - - final AxKeyInfo keyInfoBackNull = apexDao.get(AxKeyInfo.class, AxArtifactKey.getNullKey()); - assertNull(keyInfoBackNull); - - final AxKeyInfo keyInfoBack1 = apexDao.getArtifact(AxKeyInfo.class, aKey0); - assertTrue(keyInfoBack0.equals(keyInfoBack1)); - - final AxKeyInfo keyInfoBack2 = apexDao.getArtifact(AxKeyInfo.class, new AxArtifactKey("A-KEY3", "0.0.1")); - assertNull(keyInfoBack2); - - final Set keyInfoSetIn = new TreeSet(); - keyInfoSetIn.add(keyInfo1); - keyInfoSetIn.add(keyInfo2); - - apexDao.create(keyInfoSetIn); - - Set keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - - keyInfoSetIn.add(keyInfo0); - assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); - - apexDao.delete(keyInfo1); - keyInfoSetIn.remove(keyInfo1); - keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); - - apexDao.delete(keyInfoSetIn); - keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - assertEquals(0, keyInfoSetOut.size()); - - keyInfoSetIn.add(keyInfo0); - keyInfoSetIn.add(keyInfo1); - keyInfoSetIn.add(keyInfo0); - apexDao.create(keyInfoSetIn); - keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); - - apexDao.delete(AxKeyInfo.class, aKey0); - keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - assertEquals(2, keyInfoSetOut.size()); - assertEquals(2, apexDao.size(AxKeyInfo.class)); - - final Set keySetIn = new TreeSet(); - keySetIn.add(aKey1); - keySetIn.add(aKey2); - - final int deletedCount = apexDao.deleteByArtifactKey(AxKeyInfo.class, keySetIn); - assertEquals(2, deletedCount); - - keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - assertEquals(0, keyInfoSetOut.size()); - - keyInfoSetIn.add(keyInfo0); - keyInfoSetIn.add(keyInfo1); - keyInfoSetIn.add(keyInfo0); - apexDao.create(keyInfoSetIn); - keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); - assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); - - apexDao.deleteAll(AxKeyInfo.class); - assertEquals(0, apexDao.size(AxKeyInfo.class)); - - final AxArtifactKey owner0Key = new AxArtifactKey("Owner0", "0.0.1"); - final AxArtifactKey owner1Key = new AxArtifactKey("Owner1", "0.0.1"); - final AxArtifactKey owner2Key = new AxArtifactKey("Owner2", "0.0.1"); - final AxArtifactKey owner3Key = new AxArtifactKey("Owner3", "0.0.1"); - final AxArtifactKey owner4Key = new AxArtifactKey("Owner4", "0.0.1"); - final AxArtifactKey owner5Key = new AxArtifactKey("Owner5", "0.0.1"); - - apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity0"), 100.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity1"), 101.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity2"), 102.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity3"), 103.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity4"), 104.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner1Key, "Entity5"), 105.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner1Key, "Entity6"), 106.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner1Key, "Entity7"), 107.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner2Key, "Entity8"), 108.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner2Key, "Entity9"), 109.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner3Key, "EntityA"), 110.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner4Key, "EntityB"), 111.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityC"), 112.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityD"), 113.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityE"), 114.0)); - apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityF"), 115.0)); - - TreeSet testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class)); - assertEquals(16, testEntitySetOut.size()); - - testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner0Key)); - assertEquals(5, testEntitySetOut.size()); - - testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner1Key)); - assertEquals(3, testEntitySetOut.size()); - - testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner2Key)); - assertEquals(2, testEntitySetOut.size()); - - testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner3Key)); - assertEquals(1, testEntitySetOut.size()); - - testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner4Key)); - assertEquals(1, testEntitySetOut.size()); - - testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner5Key)); - assertEquals(4, testEntitySetOut.size()); - - assertNotNull(apexDao.get(TestEntity.class, new AxReferenceKey(owner0Key, "Entity0"))); - assertNotNull(apexDao.getArtifact(TestEntity.class, new AxReferenceKey(owner0Key, "Entity0"))); - assertNull(apexDao.get(TestEntity.class, new AxReferenceKey(owner0Key, "Entity1000"))); - assertNull(apexDao.getArtifact(TestEntity.class, new AxReferenceKey(owner0Key, "Entity1000"))); - apexDao.delete(TestEntity.class, new AxReferenceKey(owner0Key, "Entity0")); - - final Set rKeySetIn = new TreeSet(); - rKeySetIn.add(new AxReferenceKey(owner4Key, "EntityB")); - rKeySetIn.add(new AxReferenceKey(owner5Key, "EntityD")); - - final int deletedRCount = apexDao.deleteByReferenceKey(TestEntity.class, rKeySetIn); - assertEquals(2, deletedRCount); - - apexDao.update(new TestEntity(new AxReferenceKey(owner5Key, "EntityF"), 120.0)); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/TestDaoMisc.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/TestDaoMisc.java deleted file mode 100644 index 9109bc24b..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/dao/TestDaoMisc.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.dao; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.util.Properties; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.dao.ApexDaoFactory; -import org.onap.apex.model.basicmodel.dao.DAOParameters; -import org.onap.apex.model.basicmodel.dao.converters.CDATAConditioner; -import org.onap.apex.model.basicmodel.dao.converters.UUID2String; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestDaoMisc { - - @Test - public void testUUID2StringMopUp() { - UUID2String uuid2String = new UUID2String(); - assertEquals("", uuid2String.convertToDatabaseColumn(null)); - } - - @Test - public void testCDataConditionerMopUp() { - assertNull(CDATAConditioner.clean(null)); - } - - @Test - public void testDaoFactory() { - DAOParameters daoParameters = new DAOParameters(); - - daoParameters.setPluginClass("somewhere.over.the.rainbow"); - try { - new ApexDaoFactory().createApexDao(daoParameters); - fail("test shold throw an exception here"); - } - catch (Exception e) { - assertEquals("Apex DAO class not found for DAO plugin \"somewhere.over.the.rainbow\"", e.getMessage()); - } - - daoParameters.setPluginClass("java.lang.String"); - try { - new ApexDaoFactory().createApexDao(daoParameters); - fail("test shold throw an exception here"); - } - catch (Exception e) { - assertEquals("Specified Apex DAO plugin class \"java.lang.String\" does not implement the ApexDao interface", e.getMessage()); - } - } - - @Test - public void testDaoParameters() { - DAOParameters pars = new DAOParameters(); - pars.setJdbcProperties(new Properties()); - assertEquals(0, pars.getJdbcProperties().size()); - - pars.setJdbcProperty("name", "Dorothy"); - assertEquals("Dorothy", pars.getJdbcProperty("name")); - - pars.setPersistenceUnit("Kansas"); - assertEquals("Kansas", pars.getPersistenceUnit()); - - pars.setPluginClass("somewhere.over.the.rainbow"); - assertEquals("somewhere.over.the.rainbow", pars.getPluginClass()); - - assertEquals("DAOParameters [pluginClass=somewhere.over.the.rainbow, persistenceUnit=Kansas, jdbcProperties={name=Dorothy}]", pars.toString()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/AxModelWithReferences.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/AxModelWithReferences.java deleted file mode 100644 index e08b4482c..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/AxModelWithReferences.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.util.ArrayList; -import java.util.List; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; - -public class AxModelWithReferences extends AxModel { - private static final long serialVersionUID = -8194956638511120008L; - - private List extraKeyList = new ArrayList<>(); - - public AxModelWithReferences(final AxArtifactKey key) { - super(key); - } - - @Override - public List getKeys() { - List keys = super.getKeys(); - keys.addAll(extraKeyList); - - return keys; - } - - public List getExtraKeyList() { - return extraKeyList; - } - - public void setReferenceKeyList() { - List keys = super.getKeys(); - - for (AxKey key: keys) { - AxArtifactKey aKey = (AxArtifactKey)key; - AxReferenceKey keyRef = new AxReferenceKey(aKey, aKey.getName()); - extraKeyList.add(keyRef); - } - } - - public void addKey(final AxKey aKey) { - extraKeyList.add(aKey); - } - - public void removeKey(final AxKey aKey) { - extraKeyList.remove(aKey); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModel.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModel.java deleted file mode 100644 index e4d91b7a2..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModel.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.*; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.dao.DAOParameters; -import org.onap.apex.model.basicmodel.test.TestApexModel; - -public class TestApexBasicModel { - private Connection connection; - TestApexModel testApexModel; - - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel(AxModel.class, new TestApexBasicModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelValid() throws Exception { - AxValidationResult result = testApexModel.testApexModelValid(); - assertTrue(result.toString().equals(VALID_MODEL_STRING)); - } - - @Test - public void testApexModelVaidateObservation() throws Exception { - try { - testApexModel.testApexModelVaidateObservation(); - } - catch (ApexException e) { - assertEquals("model should have observations", e.getMessage()); - } - } - - @Test - public void testApexModelVaidateWarning() throws Exception { - AxValidationResult result = testApexModel.testApexModelVaidateWarning(); - assertTrue(result.toString().equals(WARNING_MODEL_STRING)); - } - - @Test - public void testModelVaidateInvalidModel() throws Exception { - AxValidationResult result = testApexModel.testApexModelVaidateInvalidModel(); - assertTrue(result.toString().equals(INVALID_MODEL_STRING)); - } - - @Test - public void testModelVaidateMalstructured() throws Exception { - AxValidationResult result = testApexModel.testApexModelVaidateMalstructured(); - assertTrue(result.toString().equals(INVALID_MODEL_MALSTRUCTURED_STRING)); - } - - @Test - public void testModelWriteReadXML() throws Exception { - testApexModel.testApexModelWriteReadXML(); - } - - @Test - public void testModelWriteReadJSON() throws Exception { - testApexModel.testApexModelWriteReadJSON(); - } - - @Test - public void testModelWriteReadJPA() throws Exception { - DAOParameters daoParameters = new DAOParameters(); - daoParameters.setPluginClass("org.onap.apex.model.basicmodel.dao.impl.DefaultApexDao"); - daoParameters.setPersistenceUnit("DAOTest"); - - testApexModel.testApexModelWriteReadJPA(daoParameters); - } - - // As there are no real concepts in a basic model, this is as near to a valid model as we can get - private static final String VALID_MODEL_STRING = "\n" + - "***warnings issued during validation of model***\n" + - "AxArtifactKey:(name=FloatKIKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + - "AxArtifactKey:(name=IntegerKIKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + - "********************************"; - - private static final String WARNING_MODEL_STRING = "\n" + - "***warnings issued during validation of model***\n" + - "AxArtifactKey:(name=FloatKIKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + - "AxArtifactKey:(name=IntegerKIKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + - "AxArtifactKey:(name=Unref0,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + - "AxArtifactKey:(name=Unref1,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + - "********************************"; - - private static final String INVALID_MODEL_STRING = "\n" + - "***validation of model failed***\n" + - "AxArtifactKey:(name=BasicModelKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + - "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInfo:OBSERVATION:description is blank\n" + - "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + - "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInformation:INVALID:duplicate UUID found on keyInfoMap entry AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):00000000-0000-0000-0000-000000000000\n" + - "********************************"; - - private static final String INVALID_MODEL_MALSTRUCTURED_STRING = "\n" + - "***validation of model failed***\n" + - "AxArtifactKey:(name=BasicModelKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + - "AxArtifactKey:(name=BasicModelKey,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxModel:INVALID:key information not found for key AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1)\n" + - "********************************"; -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java deleted file mode 100644 index 9d29c08f0..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java +++ /dev/null @@ -1,279 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.List; -import java.util.Set; - -import org.junit.Before; -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.concepts.AxKeyUse; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.apex.model.basicmodel.service.ModelService; -import org.onap.apex.model.basicmodel.test.TestApexModel; - -public class TestApexBasicModelConcepts { - TestApexModel testApexModel; - - @Before - public void setup() throws Exception { - testApexModel = new TestApexModel(AxModel.class, new TestApexBasicModelCreator()); - } - - @Test - public void testModelConcepts() { - AxModel model = testApexModel.getModel(); - assertNotNull(model); - model.clean(); - assertNotNull(model); - - AxValidationResult result = new AxValidationResult(); - result = model.validate(result); - assertEquals(ValidationResult.WARNING, result.getValidationResult()); - - model.register(); - assertEquals(model.getKeyInformation(), ModelService.getModel(AxKeyInformation.class)); - - AxModel clonedModel = new AxModel(model); - assertTrue(clonedModel.toString().startsWith("AxModel:(key=AxArtifactKey:(name=BasicModel")); - - assertFalse(model.hashCode() == 0); - - assertTrue(model.equals(model)); - assertTrue(model.equals(clonedModel)); - assertFalse(model.equals(null)); - assertFalse(model.equals("Hello")); - clonedModel.getKey().setVersion("0.0.2"); - assertFalse(model.equals(clonedModel)); - clonedModel.getKey().setVersion("0.0.1"); - - assertEquals(0, model.compareTo(model)); - assertNotEquals(0, model.compareTo(null)); - assertNotEquals(0, model.compareTo(new AxReferenceKey())); - assertEquals(0, model.compareTo(clonedModel)); - clonedModel.getKey().setVersion("0.0.2"); - assertNotEquals(0, model.compareTo(clonedModel)); - clonedModel.getKey().setVersion("0.0.1"); - - assertNotNull(model.getKeys()); - - model.getKeyInformation().generateKeyInfo(model); - assertNotNull(model.getKeyInformation()); - - AxKeyInformation keyI = model.getKeyInformation(); - AxKeyInformation clonedKeyI = new AxKeyInformation(keyI); - - assertFalse(keyI.equals(null)); - assertFalse(keyI.equals(new AxArtifactKey())); - assertTrue(keyI.equals(clonedKeyI)); - - clonedKeyI.setKey(new AxArtifactKey()); - assertFalse(keyI.equals(clonedKeyI)); - clonedKeyI.setKey(keyI.getKey()); - - assertEquals(0, keyI.compareTo(keyI)); - assertEquals(0, keyI.compareTo(clonedKeyI)); - assertNotEquals(0, keyI.compareTo(null)); - assertNotEquals(0, keyI.compareTo(new AxArtifactKey())); - - clonedKeyI.setKey(new AxArtifactKey()); - assertNotEquals(0, keyI.compareTo(clonedKeyI)); - clonedKeyI.setKey(keyI.getKey()); - assertEquals(0, keyI.compareTo(clonedKeyI)); - - clonedKeyI.getKeyInfoMap().clear(); - assertNotEquals(0, keyI.compareTo(clonedKeyI)); - - AxKeyInfo keyInfo = keyI.get("BasicModel"); - assertNotNull(keyInfo); - - keyInfo = keyI.get(new AxArtifactKey("BasicModel", "0.0.1")); - assertNotNull(keyInfo); - - Set keyInfoSet = keyI.getAll("BasicModel"); - assertNotNull(keyInfoSet); - - keyInfoSet = keyI.getAll("BasicModel", "0..0.1"); - assertNotNull(keyInfoSet); - - List keys = model.getKeys(); - assertNotEquals(0, keys.size()); - - keys = keyI.getKeys(); - assertNotEquals(0, keys.size()); - - model.getKeyInformation().generateKeyInfo(model); - assertNotNull(model.getKeyInformation()); - model.getKeyInformation().getKeyInfoMap().clear(); - model.getKeyInformation().generateKeyInfo(model); - assertNotNull(model.getKeyInformation()); - - clonedKeyI.setKey(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - clonedKeyI.setKey(keyI.getKey()); - - clonedKeyI.getKeyInfoMap().clear(); - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - clonedKeyI.generateKeyInfo(model); - - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - clonedKeyI.getKeyInfoMap().put(AxArtifactKey.getNullKey(), null); - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - clonedKeyI.getKeyInfoMap().clear(); - clonedKeyI.generateKeyInfo(model); - - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - clonedKeyI.getKeyInfoMap().put(new AxArtifactKey("SomeKey", "0.0.1"), null); - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - clonedKeyI.getKeyInfoMap().clear(); - clonedKeyI.generateKeyInfo(model); - - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - AxKeyInfo mk = clonedKeyI.get(new AxArtifactKey("BasicModel", "0.0.1")); - assertNotNull(mk); - mk.setKey(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - clonedKeyI.getKeyInfoMap().clear(); - clonedKeyI.generateKeyInfo(model); - - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - clonedModel.setKey(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = clonedModel.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - clonedModel.setKey(model.getKey()); - result = new AxValidationResult(); - result = clonedKeyI.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - } - - @Test - public void testModelConceptsWithReferences() { - AxModelWithReferences mwr = new TestApexBasicModelCreator().getModelWithReferences(); - assertNotNull(mwr); - mwr.getKeyInformation().getKeyInfoMap().clear(); - mwr.getKeyInformation().generateKeyInfo(mwr); - - AxValidationResult result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - // Duplicate key error - mwr.addKey(mwr.getKey()); - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - mwr.removeKey(mwr.getKey()); - - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - // Null Reference Key - mwr.addKey(AxReferenceKey.getNullKey()); - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - mwr.removeKey(AxReferenceKey.getNullKey()); - - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - // Duplicate Reference Key - AxReferenceKey rKey = new AxReferenceKey(mwr.getKey(), "LocalName"); - mwr.addKey(rKey); - mwr.addKey(rKey); - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - mwr.removeKey(rKey); - mwr.removeKey(rKey); - - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - // Key Use is legal - AxKeyUse keyU = new AxKeyUse(mwr.getKey()); - mwr.addKey(keyU); - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - mwr.removeKey(keyU); - - // Key Use on bad artifact key - AxKeyUse keyBU = new AxKeyUse(new AxArtifactKey("SomeKey", "0.0.1")); - mwr.addKey(keyBU); - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - mwr.removeKey(keyBU); - - // Key Use on bad reference key - AxKeyUse keyBRU = new AxKeyUse(new AxReferenceKey("SomeKey", "0.0.1", "Local")); - mwr.addKey(keyBRU); - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - mwr.removeKey(keyBRU); - - result = new AxValidationResult(); - result = mwr.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelCreator.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelCreator.java deleted file mode 100644 index fca6c4425..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexBasicModelCreator.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.util.UUID; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.test.TestApexModelCreator; - -public class TestApexBasicModelCreator implements TestApexModelCreator { - - @Override - public AxModel getModel() { - AxModel basicModel = new AxModel(); - - basicModel.setKey(new AxArtifactKey("BasicModel", "0.0.1")); - basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); - - basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKey(), new AxKeyInfo(basicModel.getKey())); - basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKeyInformation().getKey(), new AxKeyInfo(basicModel.getKeyInformation().getKey())); - - AxKeyInfo intKI = new AxKeyInfo(new AxArtifactKey("IntegerKIKey", "0.0.1"), UUID.randomUUID(), "IntegerKIKey description"); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI.getKey(), new AxKeyInfo(intKI.getKey())); - - AxKeyInfo floatKI = new AxKeyInfo(new AxArtifactKey("FloatKIKey", "0.0.1"), UUID.randomUUID(), "FloatKIKey description"); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI.getKey(), new AxKeyInfo(floatKI.getKey())); - - return basicModel; - } - - @Override - public final AxModel getMalstructuredModel() { - AxModel basicModel = new AxModel(); - - // Note: No Data types - basicModel.setKey(new AxArtifactKey("BasicModelKey", "0.0.1")); - basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); - - basicModel.getKeyInformation().getKeyInfoMap().put( - basicModel.getKey(), - new AxKeyInfo( - basicModel.getKey(), - UUID.fromString("00000000-0000-0000-0000-000000000000"), - "\nbasic model description\nThis is a multi line description\nwith another line of text.")); - - return basicModel; - } - - @Override - public final AxModel getObservationModel() { - AxModel basicModel = getModel(); - - // Set key information as blank - basicModel.getKeyInformation().getKeyInfoMap().get(basicModel.getKey()).setDescription(""); - - return basicModel; - } - - @Override - public final AxModel getWarningModel() { - AxModel basicModel = getModel(); - - // Add unreferenced key information - AxKeyInfo unreferencedKeyInfo0 = new AxKeyInfo(new AxArtifactKey("Unref0", "0.0.1")); - AxKeyInfo unreferencedKeyInfo1 = new AxKeyInfo(new AxArtifactKey("Unref1", "0.0.1")); - - basicModel.getKeyInformation().getKeyInfoMap().put(unreferencedKeyInfo0.getKey(), unreferencedKeyInfo0); - basicModel.getKeyInformation().getKeyInfoMap().put(unreferencedKeyInfo1.getKey(), unreferencedKeyInfo1); - - return basicModel; - } - - @Override - public final AxModel getInvalidModel() { - AxModel basicModel = new AxModel(); - - basicModel.setKey(new AxArtifactKey("BasicModelKey", "0.0.1")); - basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); - - basicModel.getKeyInformation().getKeyInfoMap().put( - basicModel.getKey(), - new AxKeyInfo( - basicModel.getKey(), - UUID.fromString("00000000-0000-0000-0000-000000000000"), - "nbasic model description\nThis is a multi line description\nwith another line of text.")); - basicModel.getKeyInformation().getKeyInfoMap().put( - basicModel.getKeyInformation().getKey(), - new AxKeyInfo( - basicModel.getKeyInformation().getKey(), - UUID.fromString("00000000-0000-0000-0000-000000000000"), - "")); - - return basicModel; - } - - public final AxModelWithReferences getModelWithReferences() { - AxModel model = getModel(); - - AxModelWithReferences modelWithReferences = new AxModelWithReferences(model.getKey()); - modelWithReferences.setKeyInformation(model.getKeyInformation()); - modelWithReferences.setReferenceKeyList(); - - return modelWithReferences; - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator0.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator0.java deleted file mode 100644 index 4b3c00226..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator0.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.test.TestApexModelCreator; - -public class TestApexTestModelCreator0 implements TestApexModelCreator { - - @Override - public AxModel getModel() { - AxModel basicModel = new AxModel(); - - basicModel.setKey(new AxArtifactKey("BasicModel", "0.0.1")); - basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); - - basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKey(), new AxKeyInfo(basicModel.getKey())); - basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKeyInformation().getKey(), new AxKeyInfo(basicModel.getKeyInformation().getKey())); - - return basicModel; - } - - @Override - public final AxModel getMalstructuredModel() { - return getModel(); - } - - @Override - public final AxModel getObservationModel() { - return getModel(); - } - - @Override - public final AxModel getWarningModel() { - return getModel(); - } - - @Override - public final AxModel getInvalidModel() { - return getModel(); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator1.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator1.java deleted file mode 100644 index e208bd850..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator1.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.util.UUID; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.test.TestApexModelCreator; - -public class TestApexTestModelCreator1 implements TestApexModelCreator { - - @Override - public AxModel getModel() { - return getInvalidModel(); - } - - @Override - public final AxModel getMalstructuredModel() { - return getInvalidModel(); - } - - @Override - public final AxModel getObservationModel() { - return getInvalidModel(); - } - - @Override - public final AxModel getWarningModel() { - return getInvalidModel(); - } - - @Override - public final AxModel getInvalidModel() { - AxModel basicModel = new AxModel(); - - basicModel.setKey(new AxArtifactKey("BasicModelKey", "0.0.1")); - basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); - - basicModel.getKeyInformation().getKeyInfoMap().put( - basicModel.getKey(), - new AxKeyInfo( - basicModel.getKey(), - UUID.fromString("00000000-0000-0000-0000-000000000000"), - "nbasic model description\nThis is a multi line description\nwith another line of text.")); - basicModel.getKeyInformation().getKeyInfoMap().put( - basicModel.getKeyInformation().getKey(), - new AxKeyInfo( - basicModel.getKeyInformation().getKey(), - UUID.fromString("00000000-0000-0000-0000-000000000000"), - "")); - - return basicModel; - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator2.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator2.java deleted file mode 100644 index 9b9eb13ac..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestApexTestModelCreator2.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.test.TestApexModelCreator; - -public class TestApexTestModelCreator2 implements TestApexModelCreator { - - @Override - public AxModel getModel() { - AxModel basicModel = new AxModel(); - - basicModel.setKey(new AxArtifactKey("BasicModel", "0.0.1")); - basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); - - basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKey(), new AxKeyInfo(basicModel.getKey())); - basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKeyInformation().getKey(), new AxKeyInfo(basicModel.getKeyInformation().getKey())); - basicModel.getKeyInformation().get("BasicModel").setDescription(""); - return basicModel; - } - - @Override - public final AxModel getMalstructuredModel() { - return getModel(); - } - - @Override - public final AxModel getObservationModel() { - return getModel(); - } - - @Override - public final AxModel getWarningModel() { - return getModel(); - } - - @Override - public final AxModel getInvalidModel() { - return getModel(); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestBasicModelTest.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestBasicModelTest.java deleted file mode 100644 index ea5433f08..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestBasicModelTest.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.test.TestApexModel; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestBasicModelTest { - - @Test - public void testNormalModelCreator() throws ApexException { - TestApexModel testApexModel = new TestApexModel(AxModel.class, new TestApexBasicModelCreator()); - - testApexModel.testApexModelValid(); - try { - testApexModel.testApexModelVaidateObservation(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertEquals("model should have observations", e.getMessage()); - } - testApexModel.testApexModelVaidateWarning(); - testApexModel.testApexModelVaidateInvalidModel(); - testApexModel.testApexModelVaidateMalstructured(); - - testApexModel.testApexModelWriteReadJSON(); - testApexModel.testApexModelWriteReadXML(); - } - - @Test - public void testModelCreator0() throws ApexException { - TestApexModel testApexModel = new TestApexModel(AxModel.class, new TestApexTestModelCreator0()); - - testApexModel.testApexModelValid(); - try { - testApexModel.testApexModelVaidateObservation(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertEquals("model should have observations", e.getMessage()); - } - try { - testApexModel.testApexModelVaidateWarning(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertEquals("model should have warnings", e.getMessage()); - } - try { - testApexModel.testApexModelVaidateInvalidModel(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertEquals("should not be valid ***validation of model successful***", e.getMessage()); - } - try { - testApexModel.testApexModelVaidateMalstructured(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertEquals("should not be valid ***validation of model successful***", e.getMessage()); - } - } - - @Test - public void testModelCreator1() throws ApexException { - TestApexModel testApexModel = new TestApexModel(AxModel.class, new TestApexTestModelCreator1()); - - try { - testApexModel.testApexModelValid(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertTrue(e.getMessage().startsWith("model is invalid")); - } - try { - testApexModel.testApexModelVaidateObservation(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertTrue(e.getMessage().startsWith("model is invalid")); - } - try { - testApexModel.testApexModelVaidateWarning(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertTrue(e.getMessage().startsWith("model is invalid")); - } - testApexModel.testApexModelVaidateInvalidModel(); - testApexModel.testApexModelVaidateMalstructured(); - } - - @Test - public void testModelCreator2() throws ApexException { - TestApexModel testApexModel = new TestApexModel(AxModel.class, new TestApexTestModelCreator2()); - - testApexModel.testApexModelValid(); - testApexModel.testApexModelVaidateObservation(); - try { - testApexModel.testApexModelVaidateWarning(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertEquals("model should have warnings", e.getMessage()); - } - } - - @Test - public void testModelCreator1XMLJSON() throws ApexException { - TestApexModel testApexModel = new TestApexModel(AxModel.class, new TestApexTestModelCreator1()); - - try { - testApexModel.testApexModelWriteReadJSON(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertTrue(e.getMessage().startsWith("error processing file")); - } - - try { - testApexModel.testApexModelWriteReadXML(); - fail("Test should throw an exception"); - } - catch (Exception e) { - assertTrue(e.getMessage().startsWith("error processing file")); - } - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestConceptGetter.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestConceptGetter.java deleted file mode 100644 index a6ff9dc0b..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestConceptGetter.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.UUID; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelFileWriter; -import org.onap.apex.model.basicmodel.handling.ApexModelReader; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestConceptGetter { - - @Test - public void testConceptGetter() throws IOException, ApexException { - AxModel basicModel = new TestApexBasicModelCreator().getModel(); - assertNotNull(basicModel); - - AxKeyInfo intKI01 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey01", "0.0.1"), UUID.randomUUID(), "IntegerKIKey01 description"); - AxKeyInfo intKI11 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey11", "0.0.1"), UUID.randomUUID(), "IntegerKIKey11 description"); - AxKeyInfo intKI21 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey21", "0.0.1"), UUID.randomUUID(), "IntegerKIKey21 description"); - AxKeyInfo intKI22 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey22", "0.0.2"), UUID.randomUUID(), "IntegerKIKey22 description"); - AxKeyInfo intKI23 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey23", "0.0.3"), UUID.randomUUID(), "IntegerKIKey23 description"); - AxKeyInfo intKI24 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey24", "0.0.4"), UUID.randomUUID(), "IntegerKIKey24 description"); - AxKeyInfo intKI25 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey25", "0.0.5"), UUID.randomUUID(), "IntegerKIKey25 description"); - AxKeyInfo intKI26 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey26", "0.0.6"), UUID.randomUUID(), "IntegerKIKey26 description"); - AxKeyInfo intKI31 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey31", "0.0.1"), UUID.randomUUID(), "IntegerKIKey31 description"); - AxKeyInfo intKI41 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey41", "0.0.1"), UUID.randomUUID(), "IntegerKIKey41 description"); - AxKeyInfo intKI51 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey51", "0.0.1"), UUID.randomUUID(), "IntegerKIKey51 description"); - AxKeyInfo intKI52 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey52", "0.0.2"), UUID.randomUUID(), "IntegerKIKey52 description"); - AxKeyInfo intKI53 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey53", "0.0.3"), UUID.randomUUID(), "IntegerKIKey53 description"); - AxKeyInfo intKI54 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey54", "0.0.4"), UUID.randomUUID(), "IntegerKIKey54 description"); - AxKeyInfo intKI61 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey61", "0.0.1"), UUID.randomUUID(), "IntegerKIKey61 description"); - AxKeyInfo intKI62 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey62", "0.0.2"), UUID.randomUUID(), "IntegerKIKey62 description"); - AxKeyInfo intKI63 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey63", "0.0.3"), UUID.randomUUID(), "IntegerKIKey63 description"); - AxKeyInfo intKI64 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey64", "0.0.4"), UUID.randomUUID(), "IntegerKIKey64 description"); - AxKeyInfo intKI71 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey71", "0.0.1"), UUID.randomUUID(), "IntegerKIKey71 description"); - AxKeyInfo intKI81 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey81", "0.0.1"), UUID.randomUUID(), "IntegerKIKey81 description"); - AxKeyInfo intKI91 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey91", "0.0.1"), UUID.randomUUID(), "IntegerKIKey91 description"); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI31.getKey(), intKI31); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI24.getKey(), intKI24); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI11.getKey(), intKI11); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI64.getKey(), intKI64); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI41.getKey(), intKI41); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI51.getKey(), intKI51); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI23.getKey(), intKI23); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI81.getKey(), intKI81); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI71.getKey(), intKI71); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI01.getKey(), intKI01); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI91.getKey(), intKI91); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI52.getKey(), intKI52); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI53.getKey(), intKI53); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI62.getKey(), intKI62); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI54.getKey(), intKI54); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI26.getKey(), intKI26); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI22.getKey(), intKI22); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI25.getKey(), intKI25); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI21.getKey(), intKI21); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI61.getKey(), intKI61); - basicModel.getKeyInformation().getKeyInfoMap().put(intKI63.getKey(), intKI63); - - AxKeyInfo floatKI01 = new AxKeyInfo(new AxArtifactKey("FloatKIKey01", "0.0.1"), UUID.randomUUID(), "IntegerKIKey01 description"); - AxKeyInfo floatKI11 = new AxKeyInfo(new AxArtifactKey("FloatKIKey11", "0.0.1"), UUID.randomUUID(), "IntegerKIKey11 description"); - AxKeyInfo floatKI21 = new AxKeyInfo(new AxArtifactKey("FloatKIKey21", "0.0.1"), UUID.randomUUID(), "IntegerKIKey21 description"); - AxKeyInfo floatKI31 = new AxKeyInfo(new AxArtifactKey("FloatKIKey31", "0.0.1"), UUID.randomUUID(), "IntegerKIKey31 description"); - AxKeyInfo floatKI41 = new AxKeyInfo(new AxArtifactKey("FloatKIKey41", "0.0.1"), UUID.randomUUID(), "IntegerKIKey41 description"); - AxKeyInfo floatKI51 = new AxKeyInfo(new AxArtifactKey("FloatKIKey51", "0.0.1"), UUID.randomUUID(), "IntegerKIKey51 description"); - AxKeyInfo floatKI61 = new AxKeyInfo(new AxArtifactKey("FloatKIKey61", "0.0.1"), UUID.randomUUID(), "IntegerKIKey61 description"); - AxKeyInfo floatKI71 = new AxKeyInfo(new AxArtifactKey("FloatKIKey71", "0.0.1"), UUID.randomUUID(), "IntegerKIKey71 description"); - AxKeyInfo floatKI81 = new AxKeyInfo(new AxArtifactKey("FloatKIKey81", "0.0.1"), UUID.randomUUID(), "IntegerKIKey81 description"); - AxKeyInfo floatKI82 = new AxKeyInfo(new AxArtifactKey("FloatKIKey82", "0.0.2"), UUID.randomUUID(), "IntegerKIKey82 description"); - AxKeyInfo floatKI83 = new AxKeyInfo(new AxArtifactKey("FloatKIKey83", "0.0.3"), UUID.randomUUID(), "IntegerKIKey83 description"); - AxKeyInfo floatKI91 = new AxKeyInfo(new AxArtifactKey("FloatKIKey91", "0.0.1"), UUID.randomUUID(), "IntegerKIKey91 description"); - AxKeyInfo floatKI92 = new AxKeyInfo(new AxArtifactKey("FloatKIKey92", "0.0.2"), UUID.randomUUID(), "IntegerKIKey92 description"); - AxKeyInfo floatKI93 = new AxKeyInfo(new AxArtifactKey("FloatKIKey93", "0.0.3"), UUID.randomUUID(), "IntegerKIKey93 description"); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI11.getKey(), floatKI11); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI83.getKey(), floatKI83); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI51.getKey(), floatKI51); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI71.getKey(), floatKI71); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI21.getKey(), floatKI21); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI81.getKey(), floatKI81); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI92.getKey(), floatKI92); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI91.getKey(), floatKI91); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI01.getKey(), floatKI01); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI82.getKey(), floatKI82); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI61.getKey(), floatKI61); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI41.getKey(), floatKI41); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI31.getKey(), floatKI31); - basicModel.getKeyInformation().getKeyInfoMap().put(floatKI93.getKey(), floatKI93); - - assertNull(basicModel.getKeyInformation().get("NonExistantKey", "0.0.6")); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey26", "0.0.6").equals(intKI26)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey62", "0.0.2").equals(intKI62)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey21", "0.0.1").equals(intKI21)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey61", "0.0.1").equals(intKI61)); - - assertNull(basicModel.getKeyInformation().get("NonExistantKey")); - - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey01").equals(intKI01)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey11").equals(intKI11)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey26").equals(intKI26)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey31").equals(intKI31)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey41").equals(intKI41)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey54").equals(intKI54)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey64").equals(intKI64)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey71").equals(intKI71)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey81").equals(intKI81)); - assertTrue(basicModel.getKeyInformation().get("IntegerKIKey91").equals(intKI91)); - - assertTrue(basicModel.getKeyInformation().get("FloatKIKey01").equals(floatKI01)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey11").equals(floatKI11)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey21").equals(floatKI21)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey31").equals(floatKI31)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey41").equals(floatKI41)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey51").equals(floatKI51)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey61").equals(floatKI61)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey71").equals(floatKI71)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey83").equals(floatKI83)); - assertTrue(basicModel.getKeyInformation().get("FloatKIKey93").equals(floatKI93)); - - - // Ensure marshalling and unmarshalling is OK - ApexModelReader modelReader = new ApexModelReader(AxModel.class); - ApexModelFileWriter modelWriter = new ApexModelFileWriter(true); - - modelReader.setValidateFlag(false); - modelWriter.setValidateFlag(false); - - File tempXMLFile = File.createTempFile("ApexModel", "xml"); - modelWriter.apexModelWriteJSONFile(basicModel, AxModel.class, tempXMLFile.getCanonicalPath()); - - FileInputStream xmlFileInputStream = new FileInputStream(tempXMLFile); - AxModel readXMLModel = modelReader.read(xmlFileInputStream); - xmlFileInputStream.close(); - assertTrue(basicModel.equals(readXMLModel)); - assertTrue(readXMLModel.getKeyInformation().get("IntegerKIKey91").equals(intKI91)); - assertNotNull(readXMLModel.getKeyInformation().get("FloatKIKey")); - tempXMLFile.delete(); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestExceptions.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestExceptions.java deleted file mode 100644 index 0dd271f98..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestExceptions.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.IOException; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.handling.ApexModelException; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestExceptions { - - @Test - public void test() { - assertNotNull(new ApexModelException("Message")); - assertNotNull(new ApexModelException("Message", new IOException())); - - ApexModelException ame = new ApexModelException("Message", new IOException("IO exception message")); - assertEquals("Message\ncaused by: Message\ncaused by: IO exception message", ame.getCascadedMessage()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelFileWriter.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelFileWriter.java deleted file mode 100644 index c2116a1d2..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelFileWriter.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelFileWriter; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestModelFileWriter { - - @Test - public void testModelFileWriter() throws IOException, ApexException { - AxModel model = new TestApexBasicModelCreator().getModel(); - - ApexModelFileWriter modelFileWriter = new ApexModelFileWriter<>(true); - - modelFileWriter.setValidateFlag(true); - assertTrue(modelFileWriter.isValidateFlag()); - - File tempFile = File.createTempFile("ApexFileWriterTest", "test"); - File tempDir = tempFile.getParentFile(); - tempFile.delete(); - - File jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/ApexFileWriterTest.json"); - File xmlTempFile = new File(tempDir.getAbsolutePath() + "/ccc/ApexFileWriterTest.xml"); - - modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); - - modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, xmlTempFile.getAbsolutePath()); - - jsonTempFile.delete(); - xmlTempFile.delete(); - new File(tempDir.getAbsolutePath() + "/aaa").delete(); - new File(tempDir.getAbsolutePath() + "/ccc").delete(); - - jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.json"); - xmlTempFile = new File(tempDir.getAbsolutePath() + "/ccc/ddd/ApexFileWriterTest.xml"); - - modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); - modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, xmlTempFile.getAbsolutePath()); - - jsonTempFile.delete(); - xmlTempFile.delete(); - - new File(tempDir.getAbsolutePath() + "/aaa/bbb").delete(); - new File(tempDir.getAbsolutePath() + "/aaa").delete(); - new File(tempDir.getAbsolutePath() + "/ccc/ddd").delete(); - new File(tempDir.getAbsolutePath() + "/ccc").delete(); - - File dirA = new File(tempDir.getAbsolutePath() + "/aaa"); - //File dirB = new File(tempDir.getAbsolutePath() + "/aaa/bbb"); - dirA.createNewFile(); - //dirB.createNewFile(); - - jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.json"); - jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.xml"); - - try { - modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); - fail("this test should throw an exception here"); - } - catch (Exception e) { - assertTrue(e.getMessage().contains("could not create directory ")); - } - - try { - modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); - fail("this test should throw an exception here"); - } - catch (Exception e) { - assertTrue(e.getMessage().contains("could not create directory ")); - } - - dirA.delete(); - - dirA = new File(tempDir.getAbsolutePath() + "/aaa"); - File fileB = new File(tempDir.getAbsolutePath() + "/aaa/bbb"); - dirA.mkdir(); - fileB.createNewFile(); - - jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.json"); - jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.xml"); - - try { - modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); - fail("this test should throw an exception here"); - } - catch (Exception e) { - assertTrue(e.getMessage().contains("error processing file ")); - } - - try { - modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); - fail("this test should throw an exception here"); - } - catch (Exception e) { - assertTrue(e.getMessage().contains("error processing file ")); - } - - fileB.delete(); - dirA.delete(); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelReader.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelReader.java deleted file mode 100644 index 134f6ff89..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelReader.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.apex.model.basicmodel.handling.ApexModelWriter; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestModelReader { - - @Test - public void testModelReader() throws IOException, ApexException { - AxModel model = new TestApexBasicModelCreator().getModel(); - AxModel invalidModel = new TestApexBasicModelCreator().getInvalidModel(); - - ApexModelWriter modelWriter = new ApexModelWriter(AxModel.class); - modelWriter.setValidateFlag(true); - modelWriter.setJsonOutput(true); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - modelWriter.write(model, baos); - - ByteArrayOutputStream baosInvalid = new ByteArrayOutputStream(); - modelWriter.setValidateFlag(false); - modelWriter.write(invalidModel, baosInvalid); - - ApexModelReader modelReader = new ApexModelReader(AxModel.class, true); - - modelReader.setValidateFlag(true); - assertTrue(modelReader.getValidateFlag()); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - AxModel readModel = modelReader.read(bais); - assertEquals(model, readModel); - - ByteArrayInputStream baisInvalid = new ByteArrayInputStream(baosInvalid.toByteArray()); - try { - modelReader.read(baisInvalid); - fail("test should throw an exceptino here"); - } - catch (Exception e) { - assertTrue(e.getMessage().startsWith("Apex concept validation failed")); - } - - modelReader.setValidateFlag(false); - assertFalse(modelReader.getValidateFlag()); - - ByteArrayInputStream bais2 = new ByteArrayInputStream(baos.toByteArray()); - AxModel readModel2 = modelReader.read(bais2); - assertEquals(model, readModel2); - - modelWriter.setJsonOutput(false); - - ByteArrayOutputStream baosXML = new ByteArrayOutputStream(); - modelWriter.write(model, baosXML); - - ByteArrayInputStream baisXML = new ByteArrayInputStream(baosXML.toByteArray()); - AxModel readModelXML = modelReader.read(baisXML); - assertEquals(model, readModelXML); - - String dummyString = "SomeDummyText"; - ByteArrayInputStream baisDummy = new ByteArrayInputStream(dummyString.getBytes()); - try { - modelReader.read(baisDummy); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("format of input for Apex concept is neither JSON nor XML", e.getMessage()); - } - - try { - ByteArrayInputStream nullBais = null; - modelReader.read(nullBais); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("concept stream may not be null", e.getMessage()); - } - - try { - FileInputStream fis = new FileInputStream(new File("somewhere/over/the/rainbow")); - modelReader.read(fis); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertTrue(e.getMessage().contains("rainbow")); - } - - File tempFile = File.createTempFile("Apex", "Dummy"); - try { - BufferedReader br = new BufferedReader(new FileReader(tempFile)); - br.close(); - modelReader.read(br); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("Unable to read Apex concept ", e.getMessage()); - } - finally { - tempFile.delete(); - } - - modelReader.setSchema(null); - - tempFile = File.createTempFile("Apex", "Dummy"); - try { - modelReader.setSchema(tempFile.getCanonicalPath()); - fail("test should throw an exception here"); - } - catch (Exception e) { - assertEquals("Unable to load schema", e.getMessage()); - } - finally { - tempFile.delete(); - } - - modelReader.setSchema("xml/example.xsd"); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelSaver.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelSaver.java deleted file mode 100644 index 182d341aa..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelSaver.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelSaver; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestModelSaver { - - @Test - public void testModelSaver() throws IOException, ApexException { - AxModel model = new TestApexBasicModelCreator().getModel(); - - Path tempPath = Files.createTempDirectory("ApexTest"); - - ApexModelSaver modelSaver = new ApexModelSaver(AxModel.class, model, tempPath.toAbsolutePath().toString()); - - modelSaver.apexModelWriteXML(); - modelSaver.apexModelWriteJSON(); - - Files.deleteIfExists(new File(tempPath.toAbsolutePath() + "/BasicModel.json").toPath()); - Files.deleteIfExists(new File(tempPath.toAbsolutePath() + "/BasicModel.xml").toPath()); - Files.deleteIfExists(tempPath); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelStringWriter.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelStringWriter.java deleted file mode 100644 index 2f4fcd2c7..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelStringWriter.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.IOException; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelStringWriter; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestModelStringWriter { - - @Test - public void testModelStringWriter() throws IOException, ApexException { - AxModel basicModel = new TestApexBasicModelCreator().getModel(); - assertNotNull(basicModel); - - AxKeyInfo intKI = basicModel.getKeyInformation().get("IntegerKIKey"); - AxKeyInfo floatKI = basicModel.getKeyInformation().get("FloatKIKey"); - - // Ensure marshalling is OK - ApexModelStringWriter stringWriter = new ApexModelStringWriter(true); - - assertNotNull(stringWriter.writeJSONString(intKI, AxKeyInfo.class)); - assertNotNull(stringWriter.writeJSONString(floatKI, AxKeyInfo.class)); - - assertNotNull(stringWriter.writeString(intKI, AxKeyInfo.class, true)); - assertNotNull(stringWriter.writeString(floatKI, AxKeyInfo.class, true)); - - assertNotNull(stringWriter.writeString(intKI, AxKeyInfo.class, false)); - assertNotNull(stringWriter.writeString(floatKI, AxKeyInfo.class, false)); - - assertNotNull(stringWriter.writeXMLString(intKI, AxKeyInfo.class)); - assertNotNull(stringWriter.writeXMLString(floatKI, AxKeyInfo.class)); - - try { - stringWriter.writeString(null, AxKeyInfo.class, true); - fail("test should thrown an exception here"); - } - catch (Exception e) { - assertEquals("concept may not be null", e.getMessage()); - } - - try { - stringWriter.writeString(null, AxKeyInfo.class, false); - fail("test should thrown an exception here"); - } - catch (Exception e) { - assertEquals("concept may not be null", e.getMessage()); - } - - try { - stringWriter.writeJSONString(null, AxKeyInfo.class); - fail("test should thrown an exception here"); - } - catch (Exception e) { - assertEquals("error writing JSON string", e.getMessage()); - } - - try { - stringWriter.writeXMLString(null, AxKeyInfo.class); - fail("test should thrown an exception here"); - } - catch (Exception e) { - assertEquals("error writing XML string", e.getMessage()); - } - - stringWriter.setValidateFlag(true); - assertTrue(stringWriter.isValidateFlag()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelWriter.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelWriter.java deleted file mode 100644 index a21c148b6..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestModelWriter.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.ApexException; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.handling.ApexModelWriter; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestModelWriter { - - @Test - public void testModelWriter() throws IOException, ApexException { - AxModel model = new TestApexBasicModelCreator().getModel(); - - ApexModelWriter modelWriter = new ApexModelWriter(AxModel.class); - - modelWriter.setValidateFlag(true); - assertTrue(modelWriter.getValidateFlag()); - assertEquals(0, modelWriter.getCDataFieldSet().size()); - - assertFalse(modelWriter.isJsonOutput()); - modelWriter.setJsonOutput(true); - assertTrue(modelWriter.isJsonOutput()); - modelWriter.setJsonOutput(false); - assertFalse(modelWriter.isJsonOutput()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - modelWriter.write(model, baos); - modelWriter.setJsonOutput(true); - modelWriter.write(model, baos); - modelWriter.setJsonOutput(false); - - modelWriter.setValidateFlag(false); - modelWriter.write(model, baos); - modelWriter.setJsonOutput(true); - modelWriter.write(model, baos); - modelWriter.setJsonOutput(false); - - modelWriter.setValidateFlag(true); - model.getKeyInformation().getKeyInfoMap().clear(); - try { - modelWriter.write(model, baos); - fail("Test should throw an exception here"); - } - catch (Exception e) { - assertEquals("Apex concept xml (BasicModel:0.0.1) validation failed", e.getMessage()); - } - model.getKeyInformation().generateKeyInfo(model); - - try { - modelWriter.write(null, baos); - fail("Test should throw an exception here"); - } - catch (Exception e) { - assertEquals("concept may not be null", e.getMessage()); - } - - try { - ByteArrayOutputStream nullBaos = null; - modelWriter.write(model, nullBaos); - fail("Test should throw an exception here"); - } - catch (Exception e) { - assertEquals("concept stream may not be null", e.getMessage()); - } - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestSchemaGenerator.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestSchemaGenerator.java deleted file mode 100644 index 2e10b51b6..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/handling/TestSchemaGenerator.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.handling; - -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileDescriptor; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintStream; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.handling.ApexSchemaGenerator; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestSchemaGenerator { - - @Test - public void test() throws IOException { - final ByteArrayOutputStream baos0 = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos0)); - - final String[] args0 = {}; - ApexSchemaGenerator.main(args0); - assertTrue(baos0.toString().contains("usage: ApexSchemaGenerator apex-root-class [schema-file-name]")); - System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); - - final ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos1)); - - final String[] args1 = {"hello", "goodbye", "here"}; - ApexSchemaGenerator.main(args1); - assertTrue(baos1.toString().contains("usage: ApexSchemaGenerator apex-root-class [schema-file-name]")); - System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); - - final ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos2)); - - final String[] args2 = {"hello", "goodbye"}; - ApexSchemaGenerator.main(args2); - assertTrue(baos2.toString().contains("error on Apex schema output")); - System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); - - final ByteArrayOutputStream baos3 = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos3)); - - final String[] args3 = {"hello"}; - ApexSchemaGenerator.main(args3); - assertTrue(baos3.toString().contains("could not create JAXB context, root class hello not found")); - System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); - - final ByteArrayOutputStream baos4 = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos4)); - - final String[] args4 = {"org.onap.apex.model.basicmodel.concepts.AxModel"}; - ApexSchemaGenerator.main(args4); - assertTrue(baos4.toString().contains("targetNamespace=\"http://www.ericsson.com/apex\"")); - System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); - - final ByteArrayOutputStream baos5 = new ByteArrayOutputStream(); - System.setOut(new PrintStream(baos5)); - - final File tempFile = File.createTempFile("ApexSchemaGeneratorTest", "xsd"); - final String[] args5 = {"org.onap.apex.model.basicmodel.concepts.AxModel", tempFile.getCanonicalPath()}; - - ApexSchemaGenerator.main(args5); - assertTrue(tempFile.length() > 100); - System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); - tempFile.delete(); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/IllegalParameters.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/IllegalParameters.java deleted file mode 100644 index 3cb4808bf..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/IllegalParameters.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -import org.onap.apex.model.basicmodel.service.AbstractParameters; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class IllegalParameters extends AbstractParameters { - public IllegalParameters() { - super("somewhere.over.the.rainbow"); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/LegalParameters.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/LegalParameters.java deleted file mode 100644 index 2bab6fd2a..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/LegalParameters.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -import org.onap.apex.model.basicmodel.service.AbstractParameters; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class LegalParameters extends AbstractParameters { - public LegalParameters() { - super(LegalParameters.class.getCanonicalName()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestAbstractParameters.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestAbstractParameters.java deleted file mode 100644 index e9a0e2f0a..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestAbstractParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import org.junit.Test; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestAbstractParameters { - - @Test - public void testAbstractParameters() { - final LegalParameters parameters = new LegalParameters(); - assertNotNull(parameters); - assertEquals("AbstractParameters [parameterClassName=org.onap.apex.model.basicmodel.service.LegalParameters]", parameters.toString()); - - assertEquals(LegalParameters.class, parameters.getParameterClass()); - assertEquals("org.onap.apex.model.basicmodel.service.LegalParameters", parameters.getParameterClassName()); - - try { - new IllegalParameters(); - fail("test should throw an exception here"); - } - catch (final Exception e) { - assertEquals("class \"somewhere.over.the.rainbow\" not found or not an instance of \"org.onap.apex.model.basicmodel.service.IllegalParameters\"", e.getMessage()); - } - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestModelService.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestModelService.java deleted file mode 100644 index 51af9baaf..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestModelService.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -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 org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.handling.TestApexBasicModelCreator; -import org.onap.apex.model.basicmodel.service.ModelService; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestModelService { - - @Test - public void testModelService() { - ModelService.clear(); - - assertFalse(ModelService.existsModel(AxKeyInformation.class)); - try { - ModelService.getModel(AxKeyInformation.class); - } - catch (Exception e) { - assertEquals("Model for org.onap.apex.model.basicmodel.concepts.AxKeyInformation not found in model service", e.getMessage()); - } - - ModelService.registerModel(AxKeyInformation.class, new TestApexBasicModelCreator().getModel().getKeyInformation()); - assertTrue(ModelService.existsModel(AxKeyInformation.class)); - assertNotNull(ModelService.getModel(AxKeyInformation.class)); - - ModelService.deregisterModel(AxKeyInformation.class); - - assertFalse(ModelService.existsModel(AxKeyInformation.class)); - try { - ModelService.getModel(AxKeyInformation.class); - } - catch (Exception e) { - assertEquals("Model for org.onap.apex.model.basicmodel.concepts.AxKeyInformation not found in model service", e.getMessage()); - } - - ModelService.registerModel(AxKeyInformation.class, new TestApexBasicModelCreator().getModel().getKeyInformation()); - assertTrue(ModelService.existsModel(AxKeyInformation.class)); - assertNotNull(ModelService.getModel(AxKeyInformation.class)); - - ModelService.clear(); - assertFalse(ModelService.existsModel(AxKeyInformation.class)); - try { - ModelService.getModel(AxKeyInformation.class); - } - catch (Exception e) { - assertEquals("Model for org.onap.apex.model.basicmodel.concepts.AxKeyInformation not found in model service", e.getMessage()); - } - - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestParameterService.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestParameterService.java deleted file mode 100644 index ff2a9c876..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/service/TestParameterService.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.service; - -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 org.junit.Test; -import org.onap.apex.model.basicmodel.service.ParameterService; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestParameterService { - - @Test - public void testParameterService() { - ParameterService.clear(); - - assertFalse(ParameterService.existsParameters(LegalParameters.class)); - try { - ParameterService.getParameters(LegalParameters.class); - } - catch (final Exception e) { - assertEquals("Parameters for org.onap.apex.model.basicmodel.service.LegalParameters not found in parameter service", e.getMessage()); - } - - ParameterService.registerParameters(LegalParameters.class, new LegalParameters()); - assertTrue(ParameterService.existsParameters(LegalParameters.class)); - assertNotNull(ParameterService.getParameters(LegalParameters.class)); - - ParameterService.deregisterParameters(LegalParameters.class); - - assertFalse(ParameterService.existsParameters(LegalParameters.class)); - try { - ParameterService.getParameters(LegalParameters.class); - } - catch (final Exception e) { - assertEquals("Parameters for org.onap.apex.model.basicmodel.service.LegalParameters not found in parameter service", e.getMessage()); - } - - ParameterService.registerParameters(LegalParameters.class, new LegalParameters()); - assertTrue(ParameterService.existsParameters(LegalParameters.class)); - assertNotNull(ParameterService.getParameters(LegalParameters.class)); - - assertNotNull(ParameterService.getAll()); - ParameterService.clear(); - assertFalse(ParameterService.existsParameters(LegalParameters.class)); - try { - ParameterService.getParameters(LegalParameters.class); - } - catch (final Exception e) { - assertEquals("Parameters for org.onap.apex.model.basicmodel.service.LegalParameters not found in parameter service", e.getMessage()); - } - - } -} diff --git a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java b/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java deleted file mode 100644 index b723439b5..000000000 --- a/model/basic-model/src/test/java/org/onap/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.basicmodel.xml; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxReferenceKey; -import org.onap.apex.model.basicmodel.xml.AxReferenceKeyAdapter; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestAxReferenceKeyAdapter { - - @Test - public void test() throws Exception { - AxReferenceKeyAdapter arka = new AxReferenceKeyAdapter(); - assertNotNull(arka); - - AxReferenceKey rKey = new AxReferenceKey("Name", "0.0.1", "PLN", "LN"); - - String rKeyString = arka.marshal(rKey); - assertEquals("LN", rKeyString); - assertEquals(rKey.getLocalName(),arka.unmarshal(rKeyString).getLocalName()); - } -} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyTest.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyTest.java new file mode 100644 index 000000000..6ac46b14e --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyTest.java @@ -0,0 +1,119 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +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.fail; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey.Compatibility; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class AxKeyTest { + + @Test + public void testArtifactKey() { + AxArtifactKey aKey0 = new AxArtifactKey(); + AxArtifactKey aKey1 = new AxArtifactKey("name", "0.0.1"); + AxArtifactKey aKey2 = new AxArtifactKey(aKey1); + AxArtifactKey aKey3 = new AxArtifactKey(aKey1.getID()); + AxArtifactKey aKey4 = new AxArtifactKey(aKey1); + AxArtifactKey aKey5 = new AxArtifactKey(aKey1); + AxArtifactKey aKey6 = new AxArtifactKey(aKey1); + + try { + new AxArtifactKey("some bad key id"); + fail("This test should throw an exception"); + } + catch (IllegalArgumentException e) { + assertEquals("parameter \"id\": value \"some bad key id\", does not match regular expression \"[A-Za-z0-9\\-_\\.]+:[0-9].[0-9].[0-9]\"", e.getMessage()); + } + + assertEquals(AxArtifactKey.getNullKey(), aKey0); + assertEquals(aKey1, aKey2); + assertEquals(aKey1, aKey3); + + assertEquals(aKey2, aKey1.getKey()); + assertEquals(1, aKey1.getKeys().size()); + + aKey0.setName("zero"); + aKey0.setVersion("0.0.2"); + aKey3.setVersion("0.0.2"); + aKey4.setVersion("0.1.2"); + aKey5.setVersion("1.2.2"); + aKey6.setVersion("3"); + + assertEquals(Compatibility.DIFFERENT, aKey0.getCompatibility(new AxReferenceKey())); + assertEquals(Compatibility.DIFFERENT, aKey0.getCompatibility(aKey1)); + assertEquals(Compatibility.IDENTICAL, aKey2.getCompatibility(aKey1)); + assertEquals(Compatibility.PATCH, aKey3.getCompatibility(aKey1)); + assertEquals(Compatibility.MINOR, aKey4.getCompatibility(aKey1)); + assertEquals(Compatibility.MAJOR, aKey5.getCompatibility(aKey1)); + assertEquals(Compatibility.MAJOR, aKey6.getCompatibility(aKey1)); + + assertTrue(aKey1.isCompatible(aKey2)); + assertTrue(aKey1.isCompatible(aKey3)); + assertTrue(aKey1.isCompatible(aKey4)); + assertFalse(aKey1.isCompatible(aKey0)); + assertFalse(aKey1.isCompatible(aKey5)); + assertFalse(aKey1.isCompatible(new AxReferenceKey())); + + assertEquals(AxValidationResult.ValidationResult.VALID, aKey0.validate(new AxValidationResult()).getValidationResult()); + assertEquals(AxValidationResult.ValidationResult.VALID, aKey1.validate(new AxValidationResult()).getValidationResult()); + assertEquals(AxValidationResult.ValidationResult.VALID, aKey2.validate(new AxValidationResult()).getValidationResult()); + assertEquals(AxValidationResult.ValidationResult.VALID, aKey3.validate(new AxValidationResult()).getValidationResult()); + assertEquals(AxValidationResult.ValidationResult.VALID, aKey4.validate(new AxValidationResult()).getValidationResult()); + assertEquals(AxValidationResult.ValidationResult.VALID, aKey5.validate(new AxValidationResult()).getValidationResult()); + assertEquals(AxValidationResult.ValidationResult.VALID, aKey6.validate(new AxValidationResult()).getValidationResult()); + + aKey0.clean(); + assertNotNull(aKey0.toString()); + + AxArtifactKey aKey7 = new AxArtifactKey(aKey1); + assertEquals(150332875, aKey7.hashCode()); + assertEquals(0, aKey7.compareTo(aKey1)); + assertEquals(-12, aKey7.compareTo(aKey0)); + + try { + aKey0.compareTo(null); + } + catch (IllegalArgumentException e) { + assertEquals("comparison object may not be null", e.getMessage()); + } + + assertEquals(0, aKey0.compareTo(aKey0)); + assertEquals(353602977, aKey0.compareTo(new AxReferenceKey())); + + assertFalse(aKey0.equals(null)); + assertTrue(aKey0.equals(aKey0)); + assertFalse(((AxKey)aKey0).equals(new AxReferenceKey())); + } + +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxKeyInfo.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxKeyInfo.java new file mode 100644 index 000000000..8368634bf --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxKeyInfo.java @@ -0,0 +1,108 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.UUID; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestAxKeyInfo { + + @Test + public void testAxKeyInfo() { + assertNotNull(new AxKeyInfo()); + assertNotNull(new AxKeyInfo(new AxArtifactKey())); + assertNotNull(new AxKeyInfo(new AxArtifactKey(), UUID.randomUUID(), "Key description")); + + AxKeyInfo testKeyInfo = new AxKeyInfo(); + testKeyInfo.setKey((new AxArtifactKey("PN", "0.0.1"))); + assertEquals("PN:0.0.1", testKeyInfo.getKey().getID()); + + AxArtifactKey key = new AxArtifactKey("key", "0.0.1"); + testKeyInfo.setKey(key); + assertEquals(key, testKeyInfo.getKey()); + + UUID uuid = UUID.randomUUID(); + testKeyInfo.setUuid(uuid); + assertEquals(uuid, testKeyInfo.getUUID()); + testKeyInfo.setDescription("Key Description"); + assertEquals("Key Description", testKeyInfo.getDescription()); + + AxKeyInfo clonedReferenceKey = new AxKeyInfo(testKeyInfo); + assertTrue(clonedReferenceKey.toString().startsWith("AxKeyInfo:(artifactId=AxArtifactKey:(name=key,version=0.0.1),uuid=")); + + assertFalse(testKeyInfo.hashCode() == 0); + + assertTrue(testKeyInfo.equals(testKeyInfo)); + assertTrue(testKeyInfo.equals(clonedReferenceKey)); + assertFalse(testKeyInfo.equals(null)); + assertFalse(testKeyInfo.equals(new AxArtifactKey())); + assertFalse(testKeyInfo.equals(new AxKeyInfo(new AxArtifactKey()))); + assertFalse(testKeyInfo.equals(new AxKeyInfo(key, UUID.randomUUID(), "Some Description"))); + assertFalse(testKeyInfo.equals(new AxKeyInfo(key, uuid, "Some Description"))); + assertTrue(testKeyInfo.equals(new AxKeyInfo(key, uuid, "Key Description"))); + + assertEquals(0, testKeyInfo.compareTo(testKeyInfo)); + assertEquals(0, testKeyInfo.compareTo(clonedReferenceKey)); + assertNotEquals(0, testKeyInfo.compareTo(null)); + assertNotEquals(0, testKeyInfo.compareTo(new AxArtifactKey())); + assertNotEquals(0, testKeyInfo.compareTo(new AxKeyInfo(new AxArtifactKey()))); + assertNotEquals(0, testKeyInfo.compareTo(new AxKeyInfo(key, UUID.randomUUID(), "Some Description"))); + assertNotEquals(0, testKeyInfo.compareTo(new AxKeyInfo(key, uuid, "Some Description"))); + assertEquals(0, testKeyInfo.compareTo(new AxKeyInfo(key, uuid, "Key Description"))); + + assertNotNull(testKeyInfo.getKeys()); + + AxValidationResult result = new AxValidationResult(); + result = testKeyInfo.validate(result); + assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); + + testKeyInfo.setDescription(""); + result = testKeyInfo.validate(result); + assertEquals(AxValidationResult.ValidationResult.OBSERVATION, result.getValidationResult()); + + testKeyInfo.setUuid(new UUID(0, 0)); + result = testKeyInfo.validate(result); + assertEquals(AxValidationResult.ValidationResult.WARNING, result.getValidationResult()); + + testKeyInfo.setKey(AxArtifactKey.getNullKey()); + result = testKeyInfo.validate(result); + assertEquals(AxValidationResult.ValidationResult.INVALID, result.getValidationResult()); + + assertNotNull(AxKeyInfo.generateReproducibleUUID(null)); + assertNotNull(AxKeyInfo.generateReproducibleUUID("SeedString")); + + testKeyInfo.clean(); + assertNotNull(testKeyInfo); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxReferenceKey.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxReferenceKey.java new file mode 100644 index 000000000..dbc925d66 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestAxReferenceKey.java @@ -0,0 +1,112 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestAxReferenceKey { + + @Test + public void testAxReferenceKey() { + assertNotNull(new AxReferenceKey()); + assertNotNull(new AxReferenceKey(new AxArtifactKey())); + assertNotNull(new AxReferenceKey(new AxArtifactKey(), "LocalName")); + assertNotNull(new AxReferenceKey(new AxReferenceKey())); + assertNotNull(new AxReferenceKey(new AxReferenceKey(), "LocalName")); + assertNotNull(new AxReferenceKey(new AxArtifactKey(), "ParentLocalName", "LocalName")); + assertNotNull(new AxReferenceKey("ParentKeyName", "0.0.1", "LocalName")); + assertNotNull(new AxReferenceKey("ParentKeyName", "0.0.1", "ParentLocalName", "LocalName")); + assertNotNull(new AxReferenceKey("ParentKeyName:0.0.1:ParentLocalName:LocalName")); + assertEquals(AxReferenceKey.getNullKey().getKey(), AxReferenceKey.getNullKey()); + assertEquals("NULL:0.0.0:NULL:NULL", AxReferenceKey.getNullKey().getID()); + + AxReferenceKey testReferenceKey = new AxReferenceKey(); + testReferenceKey.setParentArtifactKey(new AxArtifactKey("PN", "0.0.1")); + assertEquals("PN:0.0.1", testReferenceKey.getParentArtifactKey().getID()); + + testReferenceKey.setParentReferenceKey(new AxReferenceKey("PN", "0.0.1", "LN")); + assertEquals("PN:0.0.1:NULL:LN", testReferenceKey.getParentReferenceKey().getID()); + + testReferenceKey.setParentKeyName("NPKN"); + assertEquals("NPKN", testReferenceKey.getParentKeyName()); + + testReferenceKey.setParentKeyVersion("0.0.1"); + assertEquals("0.0.1", testReferenceKey.getParentKeyVersion()); + + testReferenceKey.setParentLocalName("NPKLN"); + assertEquals("NPKLN", testReferenceKey.getParentLocalName()); + + testReferenceKey.setLocalName("NLN"); + assertEquals("NLN", testReferenceKey.getLocalName()); + + assertFalse(testReferenceKey.isCompatible(AxArtifactKey.getNullKey())); + assertFalse(testReferenceKey.isCompatible(AxReferenceKey.getNullKey())); + assertTrue(testReferenceKey.isCompatible(testReferenceKey)); + + assertEquals(AxKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(AxArtifactKey.getNullKey())); + assertEquals(AxKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(AxReferenceKey.getNullKey())); + assertEquals(AxKey.Compatibility.IDENTICAL, testReferenceKey.getCompatibility(testReferenceKey)); + + AxValidationResult result = new AxValidationResult(); + result = testReferenceKey.validate(result); + assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); + + testReferenceKey.clean(); + + AxReferenceKey clonedReferenceKey = new AxReferenceKey(testReferenceKey); + assertEquals("AxReferenceKey:(parentKeyName=NPKN,parentKeyVersion=0.0.1,parentLocalName=NPKLN,localName=NLN)", clonedReferenceKey.toString()); + + assertFalse(testReferenceKey.hashCode() == 0); + + assertTrue(testReferenceKey.equals(testReferenceKey)); + assertTrue(testReferenceKey.equals(clonedReferenceKey)); + assertFalse(testReferenceKey.equals("Hello")); + assertFalse(testReferenceKey.equals(new AxReferenceKey("PKN", "0.0.2", "PLN", "LN"))); + assertFalse(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.2", "PLN", "LN"))); + assertFalse(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.1", "PLN", "LN"))); + assertFalse(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.1", "NPLN", "LN"))); + assertTrue(testReferenceKey.equals(new AxReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN"))); + + assertEquals(0, testReferenceKey.compareTo(testReferenceKey)); + assertEquals(0, testReferenceKey.compareTo(clonedReferenceKey)); + assertNotEquals(0, testReferenceKey.compareTo(new AxArtifactKey())); + assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("PKN", "0.0.2", "PLN", "LN"))); + assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.2", "PLN", "LN"))); + assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "PLN", "LN"))); + assertNotEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "NPLN", "LN"))); + assertEquals(0, testReferenceKey.compareTo(new AxReferenceKey("NPKN", "0.0.1", "NPKLN", "NLN"))); + + assertNotNull(testReferenceKey.getKeys()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestEntity.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestEntity.java new file mode 100644 index 000000000..6ba380bb8 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestEntity.java @@ -0,0 +1,175 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import java.util.Arrays; +import java.util.List; + +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.xml.AxReferenceKeyAdapter; + +@Entity +@Table(name = "TestEntity") + +public class TestEntity extends AxConcept { + private static final long serialVersionUID = -2962570563281067894L; + + @EmbeddedId() + @XmlElement(name = "key", required = true) + @XmlJavaTypeAdapter(AxReferenceKeyAdapter.class) + protected AxReferenceKey key; + + private double doubleValue; + + public TestEntity() { + this.key = new AxReferenceKey(); + this.doubleValue = 0; + } + + public TestEntity(Double doubleValue) { + this.key = new AxReferenceKey(); + this.doubleValue = doubleValue; + } + + public TestEntity(AxReferenceKey key, Double doubleValue) { + this.key = key; + this.doubleValue = doubleValue; + } + + public AxReferenceKey getKey() { + return key; + } + + public List getKeys() { + return Arrays.asList((AxKey) getKey()); + } + + public void setKey(AxReferenceKey key) { + this.key = key; + } + + public boolean checkSetKey() { + return (this.key != null); + } + + public double getDoubleValue() { + return doubleValue; + } + + public void setDoubleValue(double doubleValue) { + this.doubleValue = doubleValue; + } + + @Override + public AxValidationResult validate(AxValidationResult result) { + return key.validate(result); + } + + @Override + public void clean() { + key.clean(); + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("doubleValue="); + builder.append(doubleValue); + return builder.toString(); + } + + @Override + public AxConcept copyTo(AxConcept target) { + final Object copyObject = ((target == null) ? new TestEntity(): target); + if (copyObject instanceof TestEntity) { + final TestEntity copy = ((TestEntity) copyObject); + if (this.checkSetKey()) { + copy.setKey(new AxReferenceKey(key)); + } + else { + copy.key = null; + } + copy.doubleValue = doubleValue; + return copy; + } + else { + return null; + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((key == null) ? 0 : key.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (obj == null) + return false; + if (this == obj) + return true; + if (getClass() != obj.getClass()) + return false; + TestEntity other = (TestEntity) obj; + if (key == null) { + if (other.key != null) + return false; + } + else + if (!key.equals(other.key)) + return false; + if (doubleValue != other.doubleValue) + return false; + return true; + } + + @Override + public int compareTo(AxConcept otherObj) { + if (otherObj == null) + return -1; + if (this == otherObj) + return 0; + TestEntity other = (TestEntity) otherObj; + if (key == null) { + if (other.key != null) + return 1; + } + else + if (!key.equals(other.key)) + return key.compareTo(other.key); + if (doubleValue != other.doubleValue) + return new Double(doubleValue).compareTo(other.doubleValue); + + return 0; + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestExceptions.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestExceptions.java new file mode 100644 index 000000000..1fc5209b0 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestExceptions.java @@ -0,0 +1,70 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexConceptException; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestExceptions { + + @Test + public void test() { + assertNotNull(new ApexException("Message")); + assertNotNull(new ApexException("Message", new AxArtifactKey())); + assertNotNull(new ApexException("Message", new IOException())); + assertNotNull(new ApexException("Message", new IOException(), new AxArtifactKey())); + + AxArtifactKey key = new AxArtifactKey(); + ApexException ae = new ApexException("Message", new IOException("IO exception message"), key); + assertEquals("Message\ncaused by: Message\ncaused by: IO exception message", ae.getCascadedMessage()); + assertEquals(key, ae.getObject()); + + assertNotNull(new ApexRuntimeException("Message")); + assertNotNull(new ApexRuntimeException("Message", new AxArtifactKey())); + assertNotNull(new ApexRuntimeException("Message", new IOException())); + assertNotNull(new ApexRuntimeException("Message", new IOException(), new AxArtifactKey())); + + AxArtifactKey rKey = new AxArtifactKey(); + ApexRuntimeException re = new ApexRuntimeException("Runtime Message", new IOException("IO runtime exception message"), rKey); + assertEquals("Runtime Message\ncaused by: Runtime Message\ncaused by: IO runtime exception message", re.getCascadedMessage()); + assertEquals(key, re.getObject()); + + assertNotNull(new ApexConceptException("Message")); + assertNotNull(new ApexConceptException("Message", new IOException())); + + AxArtifactKey cKey = new AxArtifactKey(); + ApexException ace = new ApexException("Concept Message", new IOException("IO concept exception message"), cKey); + assertEquals("Concept Message\ncaused by: Concept Message\ncaused by: IO concept exception message", ace.getCascadedMessage()); + assertEquals(cKey, ace.getObject()); + } + +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestValidation.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestValidation.java new file mode 100644 index 000000000..93eb78b7c --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/TestValidation.java @@ -0,0 +1,93 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +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 org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestValidation { + + @Test + public void test() { + AxValidationResult result = new AxValidationResult(); + AxReferenceKey refKey = new AxReferenceKey("PK", "0.0.1", "PLN", "LN"); + result = refKey.validate(result); + + assertNotNull(result); + assertTrue(result.isOK()); + assertTrue(result.isValid()); + assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); + assertNotNull(result.getMessageList()); + + AxValidationMessage vMess0 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.VALID, "Some message"); + result.addValidationMessage(vMess0); + + assertTrue(result.isOK()); + assertTrue(result.isValid()); + assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); + assertNotNull(result.getMessageList()); + assertNotNull("hello", result.toString()); + + AxValidationMessage vMess1 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.OBSERVATION, "Some message"); + result.addValidationMessage(vMess1); + + assertTrue(result.isOK()); + assertTrue(result.isValid()); + assertEquals(AxValidationResult.ValidationResult.OBSERVATION, result.getValidationResult()); + assertNotNull(result.getMessageList()); + assertNotNull("hello", result.toString()); + + AxValidationMessage vMess2 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.WARNING, "Some message"); + result.addValidationMessage(vMess2); + + assertFalse(result.isOK()); + assertTrue(result.isValid()); + assertEquals(AxValidationResult.ValidationResult.WARNING, result.getValidationResult()); + assertNotNull(result.getMessageList()); + assertNotNull("hello", result.toString()); + + AxValidationMessage vMess3 = new AxValidationMessage(AxArtifactKey.getNullKey(), AxArtifactKey.class, ValidationResult.INVALID, "Some message"); + result.addValidationMessage(vMess3); + + assertFalse(result.isOK()); + assertFalse(result.isValid()); + assertEquals(AxValidationResult.ValidationResult.INVALID, result.getValidationResult()); + assertNotNull(result.getMessageList()); + assertNotNull("hello", result.toString()); + + assertEquals(AxValidationResult.ValidationResult.INVALID, result.getMessageList().get(3).getValidationResult()); + assertEquals("Some message", result.getMessageList().get(3).getMessage()); + assertEquals(AxArtifactKey.class.getCanonicalName(), result.getMessageList().get(3).getObservedClass()); + assertEquals(AxArtifactKey.getNullKey(), result.getMessageList().get(3).getObservedKey()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/testKeyUse.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/testKeyUse.java new file mode 100644 index 000000000..10706f36a --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/concepts/testKeyUse.java @@ -0,0 +1,82 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyUse; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey.Compatibility; + +public class testKeyUse { + + @Test + public void test() { + assertNotNull(new AxKeyUse()); + assertNotNull(new AxKeyUse(new AxArtifactKey())); + assertNotNull(new AxKeyUse(new AxReferenceKey())); + + AxArtifactKey key = new AxArtifactKey("Key", "0.0.1"); + AxKeyUse keyUse = new AxKeyUse(); + keyUse.setKey(key); + assertEquals(key, keyUse.getKey()); + assertEquals("Key:0.0.1", keyUse.getID()); + assertEquals(key, keyUse.getKeys().get(0)); + + assertEquals(Compatibility.IDENTICAL, keyUse.getCompatibility(key)); + assertTrue(keyUse.isCompatible(key)); + + keyUse.clean(); + assertNotNull(keyUse); + + AxValidationResult result = new AxValidationResult(); + result = keyUse.validate(result); + assertNotNull(result); + + assertNotEquals(0, keyUse.hashCode()); + + AxKeyUse clonedKeyUse = new AxKeyUse(keyUse); + assertEquals("AxKeyUse:(usedKey=AxArtifactKey:(name=Key,version=0.0.1))", clonedKeyUse.toString()); + + assertFalse(keyUse.hashCode() == 0); + + assertTrue(keyUse.equals(keyUse)); + assertTrue(keyUse.equals(clonedKeyUse)); + assertFalse(keyUse.equals("Hello")); + assertTrue(keyUse.equals(new AxKeyUse(key))); + + assertEquals(0, keyUse.compareTo(keyUse)); + assertEquals(0, keyUse.compareTo(clonedKeyUse)); + assertNotEquals(0, keyUse.compareTo(new AxArtifactKey())); + assertEquals(0, keyUse.compareTo(new AxKeyUse(key))); + + AxKeyUse keyUseNull = new AxKeyUse(AxArtifactKey.getNullKey()); + AxValidationResult resultNull = new AxValidationResult(); + assertEquals(false, keyUseNull.validate(resultNull).isValid()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/EntityTest.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/EntityTest.java new file mode 100644 index 000000000..e5d597375 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/EntityTest.java @@ -0,0 +1,296 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.UUID; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.TestEntity; + +/** + * JUnit test class + */ +public class EntityTest { + private Connection connection; + private ApexDao apexDao; + + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testEntityTestSanity() throws ApexException { + final DAOParameters daoParameters = new DAOParameters(); + + apexDao = new ApexDaoFactory().createApexDao(daoParameters); + + try { + apexDao.init(null); + fail("Test should throw an exception here"); + } catch (final Exception e) { + assertEquals("Apex persistence unit parameter not set", e.getMessage()); + } + + try { + apexDao.init(daoParameters); + fail("Test should throw an exception here"); + } catch (final Exception e) { + assertEquals("Apex persistence unit parameter not set", e.getMessage()); + } + + daoParameters.setPluginClass("somewhere.over.the.rainbow"); + daoParameters.setPersistenceUnit("Dorothy"); + try { + apexDao.init(daoParameters); + fail("Test should throw an exception here"); + } catch (final Exception e) { + assertEquals("Creation of Apex persistence unit \"Dorothy\" failed", e.getMessage()); + } + try { + apexDao.create(new AxArtifactKey()); + fail("Test should throw an exception here"); + } catch (final Exception e) { + assertEquals("Apex DAO has not been initialized", e.getMessage()); + } + apexDao.close(); + } + + @Test + public void testEntityTestAllOpsJPA() throws ApexException { + final DAOParameters daoParameters = new DAOParameters(); + daoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + daoParameters.setPersistenceUnit("DAOTest"); + + apexDao = new ApexDaoFactory().createApexDao(daoParameters); + apexDao.init(daoParameters); + + testAllOps(); + apexDao.close(); + } + + @Test + public void testEntityTestBadVals() throws ApexException { + final DAOParameters daoParameters = new DAOParameters(); + daoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + daoParameters.setPersistenceUnit("DAOTest"); + + apexDao = new ApexDaoFactory().createApexDao(daoParameters); + apexDao.init(daoParameters); + + final AxArtifactKey nullKey = null; + final AxReferenceKey nullRefKey = null; + final List nullKeyList = null; + final List emptyKeyList = new ArrayList<>(); + final List nullRKeyList = null; + final List emptyRKeyList = new ArrayList<>(); + + apexDao.create(nullKey); + apexDao.create(nullKeyList); + apexDao.create(emptyKeyList); + + apexDao.delete(nullKey); + apexDao.delete(nullKeyList); + apexDao.delete(emptyKeyList); + apexDao.delete(AxArtifactKey.class, nullKey); + apexDao.delete(AxReferenceKey.class, nullRefKey); + apexDao.deleteByArtifactKey(AxArtifactKey.class, nullKeyList); + apexDao.deleteByArtifactKey(AxArtifactKey.class, emptyKeyList); + apexDao.deleteByReferenceKey(AxReferenceKey.class, nullRKeyList); + apexDao.deleteByReferenceKey(AxReferenceKey.class, emptyRKeyList); + + apexDao.get(null, nullKey); + apexDao.get(null, nullRefKey); + apexDao.getAll(null); + apexDao.getAll(null, nullKey); + apexDao.getArtifact(null, nullKey); + apexDao.getArtifact(AxArtifactKey.class, nullKey); + apexDao.getArtifact(null, nullRefKey); + apexDao.getArtifact(AxReferenceKey.class, nullRefKey); + apexDao.size(null); + + apexDao.close(); + } + + private void testAllOps() { + final AxArtifactKey aKey0 = new AxArtifactKey("A-KEY0", "0.0.1"); + final AxArtifactKey aKey1 = new AxArtifactKey("A-KEY1", "0.0.1"); + final AxArtifactKey aKey2 = new AxArtifactKey("A-KEY2", "0.0.1"); + final AxKeyInfo keyInfo0 = + new AxKeyInfo(aKey0, UUID.fromString("00000000-0000-0000-0000-000000000000"), "key description 0"); + final AxKeyInfo keyInfo1 = + new AxKeyInfo(aKey1, UUID.fromString("00000000-0000-0000-0000-000000000001"), "key description 1"); + final AxKeyInfo keyInfo2 = + new AxKeyInfo(aKey2, UUID.fromString("00000000-0000-0000-0000-000000000002"), "key description 2"); + + apexDao.create(keyInfo0); + + final AxKeyInfo keyInfoBack0 = apexDao.get(AxKeyInfo.class, aKey0); + assertTrue(keyInfo0.equals(keyInfoBack0)); + + final AxKeyInfo keyInfoBackNull = apexDao.get(AxKeyInfo.class, AxArtifactKey.getNullKey()); + assertNull(keyInfoBackNull); + + final AxKeyInfo keyInfoBack1 = apexDao.getArtifact(AxKeyInfo.class, aKey0); + assertTrue(keyInfoBack0.equals(keyInfoBack1)); + + final AxKeyInfo keyInfoBack2 = apexDao.getArtifact(AxKeyInfo.class, new AxArtifactKey("A-KEY3", "0.0.1")); + assertNull(keyInfoBack2); + + final Set keyInfoSetIn = new TreeSet(); + keyInfoSetIn.add(keyInfo1); + keyInfoSetIn.add(keyInfo2); + + apexDao.create(keyInfoSetIn); + + Set keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + + keyInfoSetIn.add(keyInfo0); + assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); + + apexDao.delete(keyInfo1); + keyInfoSetIn.remove(keyInfo1); + keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); + + apexDao.delete(keyInfoSetIn); + keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + assertEquals(0, keyInfoSetOut.size()); + + keyInfoSetIn.add(keyInfo0); + keyInfoSetIn.add(keyInfo1); + keyInfoSetIn.add(keyInfo0); + apexDao.create(keyInfoSetIn); + keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); + + apexDao.delete(AxKeyInfo.class, aKey0); + keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + assertEquals(2, keyInfoSetOut.size()); + assertEquals(2, apexDao.size(AxKeyInfo.class)); + + final Set keySetIn = new TreeSet(); + keySetIn.add(aKey1); + keySetIn.add(aKey2); + + final int deletedCount = apexDao.deleteByArtifactKey(AxKeyInfo.class, keySetIn); + assertEquals(2, deletedCount); + + keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + assertEquals(0, keyInfoSetOut.size()); + + keyInfoSetIn.add(keyInfo0); + keyInfoSetIn.add(keyInfo1); + keyInfoSetIn.add(keyInfo0); + apexDao.create(keyInfoSetIn); + keyInfoSetOut = new TreeSet(apexDao.getAll(AxKeyInfo.class)); + assertTrue(keyInfoSetIn.equals(keyInfoSetOut)); + + apexDao.deleteAll(AxKeyInfo.class); + assertEquals(0, apexDao.size(AxKeyInfo.class)); + + final AxArtifactKey owner0Key = new AxArtifactKey("Owner0", "0.0.1"); + final AxArtifactKey owner1Key = new AxArtifactKey("Owner1", "0.0.1"); + final AxArtifactKey owner2Key = new AxArtifactKey("Owner2", "0.0.1"); + final AxArtifactKey owner3Key = new AxArtifactKey("Owner3", "0.0.1"); + final AxArtifactKey owner4Key = new AxArtifactKey("Owner4", "0.0.1"); + final AxArtifactKey owner5Key = new AxArtifactKey("Owner5", "0.0.1"); + + apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity0"), 100.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity1"), 101.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity2"), 102.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity3"), 103.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner0Key, "Entity4"), 104.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner1Key, "Entity5"), 105.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner1Key, "Entity6"), 106.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner1Key, "Entity7"), 107.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner2Key, "Entity8"), 108.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner2Key, "Entity9"), 109.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner3Key, "EntityA"), 110.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner4Key, "EntityB"), 111.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityC"), 112.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityD"), 113.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityE"), 114.0)); + apexDao.create(new TestEntity(new AxReferenceKey(owner5Key, "EntityF"), 115.0)); + + TreeSet testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class)); + assertEquals(16, testEntitySetOut.size()); + + testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner0Key)); + assertEquals(5, testEntitySetOut.size()); + + testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner1Key)); + assertEquals(3, testEntitySetOut.size()); + + testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner2Key)); + assertEquals(2, testEntitySetOut.size()); + + testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner3Key)); + assertEquals(1, testEntitySetOut.size()); + + testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner4Key)); + assertEquals(1, testEntitySetOut.size()); + + testEntitySetOut = new TreeSet(apexDao.getAll(TestEntity.class, owner5Key)); + assertEquals(4, testEntitySetOut.size()); + + assertNotNull(apexDao.get(TestEntity.class, new AxReferenceKey(owner0Key, "Entity0"))); + assertNotNull(apexDao.getArtifact(TestEntity.class, new AxReferenceKey(owner0Key, "Entity0"))); + assertNull(apexDao.get(TestEntity.class, new AxReferenceKey(owner0Key, "Entity1000"))); + assertNull(apexDao.getArtifact(TestEntity.class, new AxReferenceKey(owner0Key, "Entity1000"))); + apexDao.delete(TestEntity.class, new AxReferenceKey(owner0Key, "Entity0")); + + final Set rKeySetIn = new TreeSet(); + rKeySetIn.add(new AxReferenceKey(owner4Key, "EntityB")); + rKeySetIn.add(new AxReferenceKey(owner5Key, "EntityD")); + + final int deletedRCount = apexDao.deleteByReferenceKey(TestEntity.class, rKeySetIn); + assertEquals(2, deletedRCount); + + apexDao.update(new TestEntity(new AxReferenceKey(owner5Key, "EntityF"), 120.0)); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/TestDaoMisc.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/TestDaoMisc.java new file mode 100644 index 000000000..9f5b72d39 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/dao/TestDaoMisc.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.dao; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.Properties; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner; +import org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestDaoMisc { + + @Test + public void testUUID2StringMopUp() { + final UUID2String uuid2String = new UUID2String(); + assertEquals("", uuid2String.convertToDatabaseColumn(null)); + } + + @Test + public void testCDataConditionerMopUp() { + assertNull(CDATAConditioner.clean(null)); + } + + @Test + public void testDaoFactory() { + final DAOParameters daoParameters = new DAOParameters(); + + daoParameters.setPluginClass("somewhere.over.the.rainbow"); + try { + new ApexDaoFactory().createApexDao(daoParameters); + fail("test shold throw an exception here"); + } catch (final Exception e) { + assertEquals("Apex DAO class not found for DAO plugin \"somewhere.over.the.rainbow\"", e.getMessage()); + } + + daoParameters.setPluginClass("java.lang.String"); + try { + new ApexDaoFactory().createApexDao(daoParameters); + fail("test shold throw an exception here"); + } catch (final Exception e) { + assertEquals( + "Specified Apex DAO plugin class \"java.lang.String\" does not implement the ApexDao interface", + e.getMessage()); + } + } + + @Test + public void testDaoParameters() { + final DAOParameters pars = new DAOParameters(); + pars.setJdbcProperties(new Properties()); + assertEquals(0, pars.getJdbcProperties().size()); + + pars.setJdbcProperty("name", "Dorothy"); + assertEquals("Dorothy", pars.getJdbcProperty("name")); + + pars.setPersistenceUnit("Kansas"); + assertEquals("Kansas", pars.getPersistenceUnit()); + + pars.setPluginClass("somewhere.over.the.rainbow"); + assertEquals("somewhere.over.the.rainbow", pars.getPluginClass()); + + assertEquals( + "DAOParameters [pluginClass=somewhere.over.the.rainbow, persistenceUnit=Kansas, jdbcProperties={name=Dorothy}]", + pars.toString()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/AxModelWithReferences.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/AxModelWithReferences.java new file mode 100644 index 000000000..38359052b --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/AxModelWithReferences.java @@ -0,0 +1,69 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; + +public class AxModelWithReferences extends AxModel { + private static final long serialVersionUID = -8194956638511120008L; + + private List extraKeyList = new ArrayList<>(); + + public AxModelWithReferences(final AxArtifactKey key) { + super(key); + } + + @Override + public List getKeys() { + List keys = super.getKeys(); + keys.addAll(extraKeyList); + + return keys; + } + + public List getExtraKeyList() { + return extraKeyList; + } + + public void setReferenceKeyList() { + List keys = super.getKeys(); + + for (AxKey key: keys) { + AxArtifactKey aKey = (AxArtifactKey)key; + AxReferenceKey keyRef = new AxReferenceKey(aKey, aKey.getName()); + extraKeyList.add(keyRef); + } + } + + public void addKey(final AxKey aKey) { + extraKeyList.add(aKey); + } + + public void removeKey(final AxKey aKey) { + extraKeyList.remove(aKey); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModel.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModel.java new file mode 100644 index 000000000..d0423eb3a --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModel.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DAOParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; + +public class TestApexBasicModel { + private Connection connection; + TestApexModel testApexModel; + + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel(AxModel.class, new TestApexBasicModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testApexModelVaidateObservation() throws Exception { + try { + testApexModel.testApexModelVaidateObservation(); + } catch (final ApexException e) { + assertEquals("model should have observations", e.getMessage()); + } + } + + @Test + public void testApexModelVaidateWarning() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateWarning(); + assertTrue(result.toString().equals(WARNING_MODEL_STRING)); + } + + @Test + public void testModelVaidateInvalidModel() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateInvalidModel(); + assertTrue(result.toString().equals(INVALID_MODEL_STRING)); + } + + @Test + public void testModelVaidateMalstructured() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateMalstructured(); + assertTrue(result.toString().equals(INVALID_MODEL_MALSTRUCTURED_STRING)); + } + + @Test + public void testModelWriteReadXML() throws Exception { + testApexModel.testApexModelWriteReadXML(); + } + + @Test + public void testModelWriteReadJSON() throws Exception { + testApexModel.testApexModelWriteReadJSON(); + } + + @Test + public void testModelWriteReadJPA() throws Exception { + final DAOParameters daoParameters = new DAOParameters(); + daoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + daoParameters.setPersistenceUnit("DAOTest"); + + testApexModel.testApexModelWriteReadJPA(daoParameters); + } + + // As there are no real concepts in a basic model, this is as near to a valid model as we can get + private static final String VALID_MODEL_STRING = "\n" + "***warnings issued during validation of model***\n" + + "AxArtifactKey:(name=FloatKIKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + + "AxArtifactKey:(name=IntegerKIKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + + "********************************"; + + private static final String WARNING_MODEL_STRING = "\n" + "***warnings issued during validation of model***\n" + + "AxArtifactKey:(name=FloatKIKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + + "AxArtifactKey:(name=IntegerKIKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + + "AxArtifactKey:(name=Unref0,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + + "AxArtifactKey:(name=Unref1,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:WARNING:key not found for key information entry\n" + + "********************************"; + + private static final String INVALID_MODEL_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=BasicModelKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + + "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo:OBSERVATION:description is blank\n" + + "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + + "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation:INVALID:duplicate UUID found on keyInfoMap entry AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):00000000-0000-0000-0000-000000000000\n" + + "********************************"; + + private static final String INVALID_MODEL_MALSTRUCTURED_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=BasicModelKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + + "AxArtifactKey:(name=BasicModelKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxModel:INVALID:key information not found for key AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1)\n" + + "********************************"; +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java new file mode 100644 index 000000000..1ab7a2666 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelConcepts.java @@ -0,0 +1,279 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyUse; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; + +public class TestApexBasicModelConcepts { + TestApexModel testApexModel; + + @Before + public void setup() throws Exception { + testApexModel = new TestApexModel(AxModel.class, new TestApexBasicModelCreator()); + } + + @Test + public void testModelConcepts() { + final AxModel model = testApexModel.getModel(); + assertNotNull(model); + model.clean(); + assertNotNull(model); + + AxValidationResult result = new AxValidationResult(); + result = model.validate(result); + assertEquals(ValidationResult.WARNING, result.getValidationResult()); + + model.register(); + assertEquals(model.getKeyInformation(), ModelService.getModel(AxKeyInformation.class)); + + final AxModel clonedModel = new AxModel(model); + assertTrue(clonedModel.toString().startsWith("AxModel:(key=AxArtifactKey:(name=BasicModel")); + + assertFalse(model.hashCode() == 0); + + assertTrue(model.equals(model)); + assertTrue(model.equals(clonedModel)); + assertFalse(model.equals(null)); + assertFalse(model.equals("Hello")); + clonedModel.getKey().setVersion("0.0.2"); + assertFalse(model.equals(clonedModel)); + clonedModel.getKey().setVersion("0.0.1"); + + assertEquals(0, model.compareTo(model)); + assertNotEquals(0, model.compareTo(null)); + assertNotEquals(0, model.compareTo(new AxReferenceKey())); + assertEquals(0, model.compareTo(clonedModel)); + clonedModel.getKey().setVersion("0.0.2"); + assertNotEquals(0, model.compareTo(clonedModel)); + clonedModel.getKey().setVersion("0.0.1"); + + assertNotNull(model.getKeys()); + + model.getKeyInformation().generateKeyInfo(model); + assertNotNull(model.getKeyInformation()); + + final AxKeyInformation keyI = model.getKeyInformation(); + final AxKeyInformation clonedKeyI = new AxKeyInformation(keyI); + + assertFalse(keyI.equals(null)); + assertFalse(keyI.equals(new AxArtifactKey())); + assertTrue(keyI.equals(clonedKeyI)); + + clonedKeyI.setKey(new AxArtifactKey()); + assertFalse(keyI.equals(clonedKeyI)); + clonedKeyI.setKey(keyI.getKey()); + + assertEquals(0, keyI.compareTo(keyI)); + assertEquals(0, keyI.compareTo(clonedKeyI)); + assertNotEquals(0, keyI.compareTo(null)); + assertNotEquals(0, keyI.compareTo(new AxArtifactKey())); + + clonedKeyI.setKey(new AxArtifactKey()); + assertNotEquals(0, keyI.compareTo(clonedKeyI)); + clonedKeyI.setKey(keyI.getKey()); + assertEquals(0, keyI.compareTo(clonedKeyI)); + + clonedKeyI.getKeyInfoMap().clear(); + assertNotEquals(0, keyI.compareTo(clonedKeyI)); + + AxKeyInfo keyInfo = keyI.get("BasicModel"); + assertNotNull(keyInfo); + + keyInfo = keyI.get(new AxArtifactKey("BasicModel", "0.0.1")); + assertNotNull(keyInfo); + + Set keyInfoSet = keyI.getAll("BasicModel"); + assertNotNull(keyInfoSet); + + keyInfoSet = keyI.getAll("BasicModel", "0..0.1"); + assertNotNull(keyInfoSet); + + List keys = model.getKeys(); + assertNotEquals(0, keys.size()); + + keys = keyI.getKeys(); + assertNotEquals(0, keys.size()); + + model.getKeyInformation().generateKeyInfo(model); + assertNotNull(model.getKeyInformation()); + model.getKeyInformation().getKeyInfoMap().clear(); + model.getKeyInformation().generateKeyInfo(model); + assertNotNull(model.getKeyInformation()); + + clonedKeyI.setKey(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + clonedKeyI.setKey(keyI.getKey()); + + clonedKeyI.getKeyInfoMap().clear(); + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + clonedKeyI.generateKeyInfo(model); + + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + clonedKeyI.getKeyInfoMap().put(AxArtifactKey.getNullKey(), null); + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + clonedKeyI.getKeyInfoMap().clear(); + clonedKeyI.generateKeyInfo(model); + + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + clonedKeyI.getKeyInfoMap().put(new AxArtifactKey("SomeKey", "0.0.1"), null); + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + clonedKeyI.getKeyInfoMap().clear(); + clonedKeyI.generateKeyInfo(model); + + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + final AxKeyInfo mk = clonedKeyI.get(new AxArtifactKey("BasicModel", "0.0.1")); + assertNotNull(mk); + mk.setKey(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + clonedKeyI.getKeyInfoMap().clear(); + clonedKeyI.generateKeyInfo(model); + + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + clonedModel.setKey(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = clonedModel.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + clonedModel.setKey(model.getKey()); + result = new AxValidationResult(); + result = clonedKeyI.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + } + + @Test + public void testModelConceptsWithReferences() { + final AxModelWithReferences mwr = new TestApexBasicModelCreator().getModelWithReferences(); + assertNotNull(mwr); + mwr.getKeyInformation().getKeyInfoMap().clear(); + mwr.getKeyInformation().generateKeyInfo(mwr); + + AxValidationResult result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + // Duplicate key error + mwr.addKey(mwr.getKey()); + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + mwr.removeKey(mwr.getKey()); + + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + // Null Reference Key + mwr.addKey(AxReferenceKey.getNullKey()); + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + mwr.removeKey(AxReferenceKey.getNullKey()); + + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + // Duplicate Reference Key + final AxReferenceKey rKey = new AxReferenceKey(mwr.getKey(), "LocalName"); + mwr.addKey(rKey); + mwr.addKey(rKey); + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + mwr.removeKey(rKey); + mwr.removeKey(rKey); + + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + // Key Use is legal + final AxKeyUse keyU = new AxKeyUse(mwr.getKey()); + mwr.addKey(keyU); + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + mwr.removeKey(keyU); + + // Key Use on bad artifact key + final AxKeyUse keyBU = new AxKeyUse(new AxArtifactKey("SomeKey", "0.0.1")); + mwr.addKey(keyBU); + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + mwr.removeKey(keyBU); + + // Key Use on bad reference key + final AxKeyUse keyBRU = new AxKeyUse(new AxReferenceKey("SomeKey", "0.0.1", "Local")); + mwr.addKey(keyBRU); + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + mwr.removeKey(keyBRU); + + result = new AxValidationResult(); + result = mwr.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelCreator.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelCreator.java new file mode 100644 index 000000000..762c7555f --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexBasicModelCreator.java @@ -0,0 +1,126 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.util.UUID; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; + +public class TestApexBasicModelCreator implements TestApexModelCreator { + + @Override + public AxModel getModel() { + AxModel basicModel = new AxModel(); + + basicModel.setKey(new AxArtifactKey("BasicModel", "0.0.1")); + basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); + + basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKey(), new AxKeyInfo(basicModel.getKey())); + basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKeyInformation().getKey(), new AxKeyInfo(basicModel.getKeyInformation().getKey())); + + AxKeyInfo intKI = new AxKeyInfo(new AxArtifactKey("IntegerKIKey", "0.0.1"), UUID.randomUUID(), "IntegerKIKey description"); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI.getKey(), new AxKeyInfo(intKI.getKey())); + + AxKeyInfo floatKI = new AxKeyInfo(new AxArtifactKey("FloatKIKey", "0.0.1"), UUID.randomUUID(), "FloatKIKey description"); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI.getKey(), new AxKeyInfo(floatKI.getKey())); + + return basicModel; + } + + @Override + public final AxModel getMalstructuredModel() { + AxModel basicModel = new AxModel(); + + // Note: No Data types + basicModel.setKey(new AxArtifactKey("BasicModelKey", "0.0.1")); + basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); + + basicModel.getKeyInformation().getKeyInfoMap().put( + basicModel.getKey(), + new AxKeyInfo( + basicModel.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000000"), + "\nbasic model description\nThis is a multi line description\nwith another line of text.")); + + return basicModel; + } + + @Override + public final AxModel getObservationModel() { + AxModel basicModel = getModel(); + + // Set key information as blank + basicModel.getKeyInformation().getKeyInfoMap().get(basicModel.getKey()).setDescription(""); + + return basicModel; + } + + @Override + public final AxModel getWarningModel() { + AxModel basicModel = getModel(); + + // Add unreferenced key information + AxKeyInfo unreferencedKeyInfo0 = new AxKeyInfo(new AxArtifactKey("Unref0", "0.0.1")); + AxKeyInfo unreferencedKeyInfo1 = new AxKeyInfo(new AxArtifactKey("Unref1", "0.0.1")); + + basicModel.getKeyInformation().getKeyInfoMap().put(unreferencedKeyInfo0.getKey(), unreferencedKeyInfo0); + basicModel.getKeyInformation().getKeyInfoMap().put(unreferencedKeyInfo1.getKey(), unreferencedKeyInfo1); + + return basicModel; + } + + @Override + public final AxModel getInvalidModel() { + AxModel basicModel = new AxModel(); + + basicModel.setKey(new AxArtifactKey("BasicModelKey", "0.0.1")); + basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); + + basicModel.getKeyInformation().getKeyInfoMap().put( + basicModel.getKey(), + new AxKeyInfo( + basicModel.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000000"), + "nbasic model description\nThis is a multi line description\nwith another line of text.")); + basicModel.getKeyInformation().getKeyInfoMap().put( + basicModel.getKeyInformation().getKey(), + new AxKeyInfo( + basicModel.getKeyInformation().getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000000"), + "")); + + return basicModel; + } + + public final AxModelWithReferences getModelWithReferences() { + AxModel model = getModel(); + + AxModelWithReferences modelWithReferences = new AxModelWithReferences(model.getKey()); + modelWithReferences.setKeyInformation(model.getKeyInformation()); + modelWithReferences.setReferenceKeyList(); + + return modelWithReferences; + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator0.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator0.java new file mode 100644 index 000000000..ff958373e --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator0.java @@ -0,0 +1,63 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; + +public class TestApexTestModelCreator0 implements TestApexModelCreator { + + @Override + public AxModel getModel() { + AxModel basicModel = new AxModel(); + + basicModel.setKey(new AxArtifactKey("BasicModel", "0.0.1")); + basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); + + basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKey(), new AxKeyInfo(basicModel.getKey())); + basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKeyInformation().getKey(), new AxKeyInfo(basicModel.getKeyInformation().getKey())); + + return basicModel; + } + + @Override + public final AxModel getMalstructuredModel() { + return getModel(); + } + + @Override + public final AxModel getObservationModel() { + return getModel(); + } + + @Override + public final AxModel getWarningModel() { + return getModel(); + } + + @Override + public final AxModel getInvalidModel() { + return getModel(); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator1.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator1.java new file mode 100644 index 000000000..d2aa738a0 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator1.java @@ -0,0 +1,75 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.util.UUID; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; + +public class TestApexTestModelCreator1 implements TestApexModelCreator { + + @Override + public AxModel getModel() { + return getInvalidModel(); + } + + @Override + public final AxModel getMalstructuredModel() { + return getInvalidModel(); + } + + @Override + public final AxModel getObservationModel() { + return getInvalidModel(); + } + + @Override + public final AxModel getWarningModel() { + return getInvalidModel(); + } + + @Override + public final AxModel getInvalidModel() { + AxModel basicModel = new AxModel(); + + basicModel.setKey(new AxArtifactKey("BasicModelKey", "0.0.1")); + basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); + + basicModel.getKeyInformation().getKeyInfoMap().put( + basicModel.getKey(), + new AxKeyInfo( + basicModel.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000000"), + "nbasic model description\nThis is a multi line description\nwith another line of text.")); + basicModel.getKeyInformation().getKeyInfoMap().put( + basicModel.getKeyInformation().getKey(), + new AxKeyInfo( + basicModel.getKeyInformation().getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000000"), + "")); + + return basicModel; + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator2.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator2.java new file mode 100644 index 000000000..85751bf12 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestApexTestModelCreator2.java @@ -0,0 +1,63 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; + +public class TestApexTestModelCreator2 implements TestApexModelCreator { + + @Override + public AxModel getModel() { + AxModel basicModel = new AxModel(); + + basicModel.setKey(new AxArtifactKey("BasicModel", "0.0.1")); + basicModel.setKeyInformation(new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1"))); + + basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKey(), new AxKeyInfo(basicModel.getKey())); + basicModel.getKeyInformation().getKeyInfoMap().put(basicModel.getKeyInformation().getKey(), new AxKeyInfo(basicModel.getKeyInformation().getKey())); + basicModel.getKeyInformation().get("BasicModel").setDescription(""); + return basicModel; + } + + @Override + public final AxModel getMalstructuredModel() { + return getModel(); + } + + @Override + public final AxModel getObservationModel() { + return getModel(); + } + + @Override + public final AxModel getWarningModel() { + return getModel(); + } + + @Override + public final AxModel getInvalidModel() { + return getModel(); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestBasicModelTest.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestBasicModelTest.java new file mode 100644 index 000000000..9ddd3cc7e --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestBasicModelTest.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestBasicModelTest { + + @Test + public void testNormalModelCreator() throws ApexException { + final TestApexModel testApexModel = + new TestApexModel(AxModel.class, new TestApexBasicModelCreator()); + + testApexModel.testApexModelValid(); + try { + testApexModel.testApexModelVaidateObservation(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertEquals("model should have observations", e.getMessage()); + } + testApexModel.testApexModelVaidateWarning(); + testApexModel.testApexModelVaidateInvalidModel(); + testApexModel.testApexModelVaidateMalstructured(); + + testApexModel.testApexModelWriteReadJSON(); + testApexModel.testApexModelWriteReadXML(); + } + + @Test + public void testModelCreator0() throws ApexException { + final TestApexModel testApexModel = + new TestApexModel(AxModel.class, new TestApexTestModelCreator0()); + + testApexModel.testApexModelValid(); + try { + testApexModel.testApexModelVaidateObservation(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertEquals("model should have observations", e.getMessage()); + } + try { + testApexModel.testApexModelVaidateWarning(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertEquals("model should have warnings", e.getMessage()); + } + try { + testApexModel.testApexModelVaidateInvalidModel(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertEquals("should not be valid ***validation of model successful***", e.getMessage()); + } + try { + testApexModel.testApexModelVaidateMalstructured(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertEquals("should not be valid ***validation of model successful***", e.getMessage()); + } + } + + @Test + public void testModelCreator1() throws ApexException { + final TestApexModel testApexModel = + new TestApexModel(AxModel.class, new TestApexTestModelCreator1()); + + try { + testApexModel.testApexModelValid(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertTrue(e.getMessage().startsWith("model is invalid")); + } + try { + testApexModel.testApexModelVaidateObservation(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertTrue(e.getMessage().startsWith("model is invalid")); + } + try { + testApexModel.testApexModelVaidateWarning(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertTrue(e.getMessage().startsWith("model is invalid")); + } + testApexModel.testApexModelVaidateInvalidModel(); + testApexModel.testApexModelVaidateMalstructured(); + } + + @Test + public void testModelCreator2() throws ApexException { + final TestApexModel testApexModel = + new TestApexModel(AxModel.class, new TestApexTestModelCreator2()); + + testApexModel.testApexModelValid(); + testApexModel.testApexModelVaidateObservation(); + try { + testApexModel.testApexModelVaidateWarning(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertEquals("model should have warnings", e.getMessage()); + } + } + + @Test + public void testModelCreator1XMLJSON() throws ApexException { + final TestApexModel testApexModel = + new TestApexModel(AxModel.class, new TestApexTestModelCreator1()); + + try { + testApexModel.testApexModelWriteReadJSON(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertTrue(e.getMessage().startsWith("error processing file")); + } + + try { + testApexModel.testApexModelWriteReadXML(); + fail("Test should throw an exception"); + } catch (final Exception e) { + assertTrue(e.getMessage().startsWith("error processing file")); + } + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestConceptGetter.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestConceptGetter.java new file mode 100644 index 000000000..83545bf06 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestConceptGetter.java @@ -0,0 +1,171 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.UUID; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelFileWriter; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestConceptGetter { + + @Test + public void testConceptGetter() throws IOException, ApexException { + AxModel basicModel = new TestApexBasicModelCreator().getModel(); + assertNotNull(basicModel); + + AxKeyInfo intKI01 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey01", "0.0.1"), UUID.randomUUID(), "IntegerKIKey01 description"); + AxKeyInfo intKI11 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey11", "0.0.1"), UUID.randomUUID(), "IntegerKIKey11 description"); + AxKeyInfo intKI21 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey21", "0.0.1"), UUID.randomUUID(), "IntegerKIKey21 description"); + AxKeyInfo intKI22 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey22", "0.0.2"), UUID.randomUUID(), "IntegerKIKey22 description"); + AxKeyInfo intKI23 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey23", "0.0.3"), UUID.randomUUID(), "IntegerKIKey23 description"); + AxKeyInfo intKI24 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey24", "0.0.4"), UUID.randomUUID(), "IntegerKIKey24 description"); + AxKeyInfo intKI25 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey25", "0.0.5"), UUID.randomUUID(), "IntegerKIKey25 description"); + AxKeyInfo intKI26 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey26", "0.0.6"), UUID.randomUUID(), "IntegerKIKey26 description"); + AxKeyInfo intKI31 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey31", "0.0.1"), UUID.randomUUID(), "IntegerKIKey31 description"); + AxKeyInfo intKI41 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey41", "0.0.1"), UUID.randomUUID(), "IntegerKIKey41 description"); + AxKeyInfo intKI51 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey51", "0.0.1"), UUID.randomUUID(), "IntegerKIKey51 description"); + AxKeyInfo intKI52 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey52", "0.0.2"), UUID.randomUUID(), "IntegerKIKey52 description"); + AxKeyInfo intKI53 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey53", "0.0.3"), UUID.randomUUID(), "IntegerKIKey53 description"); + AxKeyInfo intKI54 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey54", "0.0.4"), UUID.randomUUID(), "IntegerKIKey54 description"); + AxKeyInfo intKI61 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey61", "0.0.1"), UUID.randomUUID(), "IntegerKIKey61 description"); + AxKeyInfo intKI62 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey62", "0.0.2"), UUID.randomUUID(), "IntegerKIKey62 description"); + AxKeyInfo intKI63 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey63", "0.0.3"), UUID.randomUUID(), "IntegerKIKey63 description"); + AxKeyInfo intKI64 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey64", "0.0.4"), UUID.randomUUID(), "IntegerKIKey64 description"); + AxKeyInfo intKI71 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey71", "0.0.1"), UUID.randomUUID(), "IntegerKIKey71 description"); + AxKeyInfo intKI81 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey81", "0.0.1"), UUID.randomUUID(), "IntegerKIKey81 description"); + AxKeyInfo intKI91 = new AxKeyInfo(new AxArtifactKey("IntegerKIKey91", "0.0.1"), UUID.randomUUID(), "IntegerKIKey91 description"); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI31.getKey(), intKI31); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI24.getKey(), intKI24); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI11.getKey(), intKI11); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI64.getKey(), intKI64); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI41.getKey(), intKI41); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI51.getKey(), intKI51); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI23.getKey(), intKI23); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI81.getKey(), intKI81); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI71.getKey(), intKI71); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI01.getKey(), intKI01); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI91.getKey(), intKI91); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI52.getKey(), intKI52); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI53.getKey(), intKI53); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI62.getKey(), intKI62); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI54.getKey(), intKI54); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI26.getKey(), intKI26); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI22.getKey(), intKI22); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI25.getKey(), intKI25); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI21.getKey(), intKI21); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI61.getKey(), intKI61); + basicModel.getKeyInformation().getKeyInfoMap().put(intKI63.getKey(), intKI63); + + AxKeyInfo floatKI01 = new AxKeyInfo(new AxArtifactKey("FloatKIKey01", "0.0.1"), UUID.randomUUID(), "IntegerKIKey01 description"); + AxKeyInfo floatKI11 = new AxKeyInfo(new AxArtifactKey("FloatKIKey11", "0.0.1"), UUID.randomUUID(), "IntegerKIKey11 description"); + AxKeyInfo floatKI21 = new AxKeyInfo(new AxArtifactKey("FloatKIKey21", "0.0.1"), UUID.randomUUID(), "IntegerKIKey21 description"); + AxKeyInfo floatKI31 = new AxKeyInfo(new AxArtifactKey("FloatKIKey31", "0.0.1"), UUID.randomUUID(), "IntegerKIKey31 description"); + AxKeyInfo floatKI41 = new AxKeyInfo(new AxArtifactKey("FloatKIKey41", "0.0.1"), UUID.randomUUID(), "IntegerKIKey41 description"); + AxKeyInfo floatKI51 = new AxKeyInfo(new AxArtifactKey("FloatKIKey51", "0.0.1"), UUID.randomUUID(), "IntegerKIKey51 description"); + AxKeyInfo floatKI61 = new AxKeyInfo(new AxArtifactKey("FloatKIKey61", "0.0.1"), UUID.randomUUID(), "IntegerKIKey61 description"); + AxKeyInfo floatKI71 = new AxKeyInfo(new AxArtifactKey("FloatKIKey71", "0.0.1"), UUID.randomUUID(), "IntegerKIKey71 description"); + AxKeyInfo floatKI81 = new AxKeyInfo(new AxArtifactKey("FloatKIKey81", "0.0.1"), UUID.randomUUID(), "IntegerKIKey81 description"); + AxKeyInfo floatKI82 = new AxKeyInfo(new AxArtifactKey("FloatKIKey82", "0.0.2"), UUID.randomUUID(), "IntegerKIKey82 description"); + AxKeyInfo floatKI83 = new AxKeyInfo(new AxArtifactKey("FloatKIKey83", "0.0.3"), UUID.randomUUID(), "IntegerKIKey83 description"); + AxKeyInfo floatKI91 = new AxKeyInfo(new AxArtifactKey("FloatKIKey91", "0.0.1"), UUID.randomUUID(), "IntegerKIKey91 description"); + AxKeyInfo floatKI92 = new AxKeyInfo(new AxArtifactKey("FloatKIKey92", "0.0.2"), UUID.randomUUID(), "IntegerKIKey92 description"); + AxKeyInfo floatKI93 = new AxKeyInfo(new AxArtifactKey("FloatKIKey93", "0.0.3"), UUID.randomUUID(), "IntegerKIKey93 description"); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI11.getKey(), floatKI11); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI83.getKey(), floatKI83); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI51.getKey(), floatKI51); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI71.getKey(), floatKI71); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI21.getKey(), floatKI21); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI81.getKey(), floatKI81); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI92.getKey(), floatKI92); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI91.getKey(), floatKI91); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI01.getKey(), floatKI01); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI82.getKey(), floatKI82); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI61.getKey(), floatKI61); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI41.getKey(), floatKI41); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI31.getKey(), floatKI31); + basicModel.getKeyInformation().getKeyInfoMap().put(floatKI93.getKey(), floatKI93); + + assertNull(basicModel.getKeyInformation().get("NonExistantKey", "0.0.6")); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey26", "0.0.6").equals(intKI26)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey62", "0.0.2").equals(intKI62)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey21", "0.0.1").equals(intKI21)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey61", "0.0.1").equals(intKI61)); + + assertNull(basicModel.getKeyInformation().get("NonExistantKey")); + + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey01").equals(intKI01)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey11").equals(intKI11)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey26").equals(intKI26)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey31").equals(intKI31)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey41").equals(intKI41)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey54").equals(intKI54)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey64").equals(intKI64)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey71").equals(intKI71)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey81").equals(intKI81)); + assertTrue(basicModel.getKeyInformation().get("IntegerKIKey91").equals(intKI91)); + + assertTrue(basicModel.getKeyInformation().get("FloatKIKey01").equals(floatKI01)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey11").equals(floatKI11)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey21").equals(floatKI21)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey31").equals(floatKI31)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey41").equals(floatKI41)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey51").equals(floatKI51)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey61").equals(floatKI61)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey71").equals(floatKI71)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey83").equals(floatKI83)); + assertTrue(basicModel.getKeyInformation().get("FloatKIKey93").equals(floatKI93)); + + + // Ensure marshalling and unmarshalling is OK + ApexModelReader modelReader = new ApexModelReader(AxModel.class); + ApexModelFileWriter modelWriter = new ApexModelFileWriter(true); + + modelReader.setValidateFlag(false); + modelWriter.setValidateFlag(false); + + File tempXMLFile = File.createTempFile("ApexModel", "xml"); + modelWriter.apexModelWriteJSONFile(basicModel, AxModel.class, tempXMLFile.getCanonicalPath()); + + FileInputStream xmlFileInputStream = new FileInputStream(tempXMLFile); + AxModel readXMLModel = modelReader.read(xmlFileInputStream); + xmlFileInputStream.close(); + assertTrue(basicModel.equals(readXMLModel)); + assertTrue(readXMLModel.getKeyInformation().get("IntegerKIKey91").equals(intKI91)); + assertNotNull(readXMLModel.getKeyInformation().get("FloatKIKey")); + tempXMLFile.delete(); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestExceptions.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestExceptions.java new file mode 100644 index 000000000..5c8922793 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestExceptions.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestExceptions { + + @Test + public void test() { + assertNotNull(new ApexModelException("Message")); + assertNotNull(new ApexModelException("Message", new IOException())); + + ApexModelException ame = new ApexModelException("Message", new IOException("IO exception message")); + assertEquals("Message\ncaused by: Message\ncaused by: IO exception message", ame.getCascadedMessage()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelFileWriter.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelFileWriter.java new file mode 100644 index 000000000..ec4d0a5a9 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelFileWriter.java @@ -0,0 +1,131 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelFileWriter; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestModelFileWriter { + + @Test + public void testModelFileWriter() throws IOException, ApexException { + AxModel model = new TestApexBasicModelCreator().getModel(); + + ApexModelFileWriter modelFileWriter = new ApexModelFileWriter<>(true); + + modelFileWriter.setValidateFlag(true); + assertTrue(modelFileWriter.isValidateFlag()); + + File tempFile = File.createTempFile("ApexFileWriterTest", "test"); + File tempDir = tempFile.getParentFile(); + tempFile.delete(); + + File jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/ApexFileWriterTest.json"); + File xmlTempFile = new File(tempDir.getAbsolutePath() + "/ccc/ApexFileWriterTest.xml"); + + modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); + + modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, xmlTempFile.getAbsolutePath()); + + jsonTempFile.delete(); + xmlTempFile.delete(); + new File(tempDir.getAbsolutePath() + "/aaa").delete(); + new File(tempDir.getAbsolutePath() + "/ccc").delete(); + + jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.json"); + xmlTempFile = new File(tempDir.getAbsolutePath() + "/ccc/ddd/ApexFileWriterTest.xml"); + + modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); + modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, xmlTempFile.getAbsolutePath()); + + jsonTempFile.delete(); + xmlTempFile.delete(); + + new File(tempDir.getAbsolutePath() + "/aaa/bbb").delete(); + new File(tempDir.getAbsolutePath() + "/aaa").delete(); + new File(tempDir.getAbsolutePath() + "/ccc/ddd").delete(); + new File(tempDir.getAbsolutePath() + "/ccc").delete(); + + File dirA = new File(tempDir.getAbsolutePath() + "/aaa"); + //File dirB = new File(tempDir.getAbsolutePath() + "/aaa/bbb"); + dirA.createNewFile(); + //dirB.createNewFile(); + + jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.json"); + jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.xml"); + + try { + modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); + fail("this test should throw an exception here"); + } + catch (Exception e) { + assertTrue(e.getMessage().contains("could not create directory ")); + } + + try { + modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); + fail("this test should throw an exception here"); + } + catch (Exception e) { + assertTrue(e.getMessage().contains("could not create directory ")); + } + + dirA.delete(); + + dirA = new File(tempDir.getAbsolutePath() + "/aaa"); + File fileB = new File(tempDir.getAbsolutePath() + "/aaa/bbb"); + dirA.mkdir(); + fileB.createNewFile(); + + jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.json"); + jsonTempFile = new File(tempDir.getAbsolutePath() + "/aaa/bbb/ApexFileWriterTest.xml"); + + try { + modelFileWriter.apexModelWriteJSONFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); + fail("this test should throw an exception here"); + } + catch (Exception e) { + assertTrue(e.getMessage().contains("error processing file ")); + } + + try { + modelFileWriter.apexModelWriteXMLFile(model, AxModel.class, jsonTempFile.getAbsolutePath()); + fail("this test should throw an exception here"); + } + catch (Exception e) { + assertTrue(e.getMessage().contains("error processing file ")); + } + + fileB.delete(); + dirA.delete(); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelReader.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelReader.java new file mode 100644 index 000000000..140817e00 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelReader.java @@ -0,0 +1,155 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestModelReader { + + @Test + public void testModelReader() throws IOException, ApexException { + AxModel model = new TestApexBasicModelCreator().getModel(); + AxModel invalidModel = new TestApexBasicModelCreator().getInvalidModel(); + + ApexModelWriter modelWriter = new ApexModelWriter(AxModel.class); + modelWriter.setValidateFlag(true); + modelWriter.setJsonOutput(true); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + modelWriter.write(model, baos); + + ByteArrayOutputStream baosInvalid = new ByteArrayOutputStream(); + modelWriter.setValidateFlag(false); + modelWriter.write(invalidModel, baosInvalid); + + ApexModelReader modelReader = new ApexModelReader(AxModel.class, true); + + modelReader.setValidateFlag(true); + assertTrue(modelReader.getValidateFlag()); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + AxModel readModel = modelReader.read(bais); + assertEquals(model, readModel); + + ByteArrayInputStream baisInvalid = new ByteArrayInputStream(baosInvalid.toByteArray()); + try { + modelReader.read(baisInvalid); + fail("test should throw an exceptino here"); + } + catch (Exception e) { + assertTrue(e.getMessage().startsWith("Apex concept validation failed")); + } + + modelReader.setValidateFlag(false); + assertFalse(modelReader.getValidateFlag()); + + ByteArrayInputStream bais2 = new ByteArrayInputStream(baos.toByteArray()); + AxModel readModel2 = modelReader.read(bais2); + assertEquals(model, readModel2); + + modelWriter.setJsonOutput(false); + + ByteArrayOutputStream baosXML = new ByteArrayOutputStream(); + modelWriter.write(model, baosXML); + + ByteArrayInputStream baisXML = new ByteArrayInputStream(baosXML.toByteArray()); + AxModel readModelXML = modelReader.read(baisXML); + assertEquals(model, readModelXML); + + String dummyString = "SomeDummyText"; + ByteArrayInputStream baisDummy = new ByteArrayInputStream(dummyString.getBytes()); + try { + modelReader.read(baisDummy); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("format of input for Apex concept is neither JSON nor XML", e.getMessage()); + } + + try { + ByteArrayInputStream nullBais = null; + modelReader.read(nullBais); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("concept stream may not be null", e.getMessage()); + } + + try { + FileInputStream fis = new FileInputStream(new File("somewhere/over/the/rainbow")); + modelReader.read(fis); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertTrue(e.getMessage().contains("rainbow")); + } + + File tempFile = File.createTempFile("Apex", "Dummy"); + try { + BufferedReader br = new BufferedReader(new FileReader(tempFile)); + br.close(); + modelReader.read(br); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("Unable to read Apex concept ", e.getMessage()); + } + finally { + tempFile.delete(); + } + + modelReader.setSchema(null); + + tempFile = File.createTempFile("Apex", "Dummy"); + try { + modelReader.setSchema(tempFile.getCanonicalPath()); + fail("test should throw an exception here"); + } + catch (Exception e) { + assertEquals("Unable to load schema", e.getMessage()); + } + finally { + tempFile.delete(); + } + + modelReader.setSchema("xml/example.xsd"); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelSaver.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelSaver.java new file mode 100644 index 000000000..08f123cba --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelSaver.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelSaver; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestModelSaver { + + @Test + public void testModelSaver() throws IOException, ApexException { + AxModel model = new TestApexBasicModelCreator().getModel(); + + Path tempPath = Files.createTempDirectory("ApexTest"); + + ApexModelSaver modelSaver = new ApexModelSaver(AxModel.class, model, tempPath.toAbsolutePath().toString()); + + modelSaver.apexModelWriteXML(); + modelSaver.apexModelWriteJSON(); + + Files.deleteIfExists(new File(tempPath.toAbsolutePath() + "/BasicModel.json").toPath()); + Files.deleteIfExists(new File(tempPath.toAbsolutePath() + "/BasicModel.xml").toPath()); + Files.deleteIfExists(tempPath); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelStringWriter.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelStringWriter.java new file mode 100644 index 000000000..d2a504676 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelStringWriter.java @@ -0,0 +1,99 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelStringWriter; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestModelStringWriter { + + @Test + public void testModelStringWriter() throws IOException, ApexException { + AxModel basicModel = new TestApexBasicModelCreator().getModel(); + assertNotNull(basicModel); + + AxKeyInfo intKI = basicModel.getKeyInformation().get("IntegerKIKey"); + AxKeyInfo floatKI = basicModel.getKeyInformation().get("FloatKIKey"); + + // Ensure marshalling is OK + ApexModelStringWriter stringWriter = new ApexModelStringWriter(true); + + assertNotNull(stringWriter.writeJSONString(intKI, AxKeyInfo.class)); + assertNotNull(stringWriter.writeJSONString(floatKI, AxKeyInfo.class)); + + assertNotNull(stringWriter.writeString(intKI, AxKeyInfo.class, true)); + assertNotNull(stringWriter.writeString(floatKI, AxKeyInfo.class, true)); + + assertNotNull(stringWriter.writeString(intKI, AxKeyInfo.class, false)); + assertNotNull(stringWriter.writeString(floatKI, AxKeyInfo.class, false)); + + assertNotNull(stringWriter.writeXMLString(intKI, AxKeyInfo.class)); + assertNotNull(stringWriter.writeXMLString(floatKI, AxKeyInfo.class)); + + try { + stringWriter.writeString(null, AxKeyInfo.class, true); + fail("test should thrown an exception here"); + } + catch (Exception e) { + assertEquals("concept may not be null", e.getMessage()); + } + + try { + stringWriter.writeString(null, AxKeyInfo.class, false); + fail("test should thrown an exception here"); + } + catch (Exception e) { + assertEquals("concept may not be null", e.getMessage()); + } + + try { + stringWriter.writeJSONString(null, AxKeyInfo.class); + fail("test should thrown an exception here"); + } + catch (Exception e) { + assertEquals("error writing JSON string", e.getMessage()); + } + + try { + stringWriter.writeXMLString(null, AxKeyInfo.class); + fail("test should thrown an exception here"); + } + catch (Exception e) { + assertEquals("error writing XML string", e.getMessage()); + } + + stringWriter.setValidateFlag(true); + assertTrue(stringWriter.isValidateFlag()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelWriter.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelWriter.java new file mode 100644 index 000000000..8e5af45b3 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestModelWriter.java @@ -0,0 +1,98 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestModelWriter { + + @Test + public void testModelWriter() throws IOException, ApexException { + AxModel model = new TestApexBasicModelCreator().getModel(); + + ApexModelWriter modelWriter = new ApexModelWriter(AxModel.class); + + modelWriter.setValidateFlag(true); + assertTrue(modelWriter.getValidateFlag()); + assertEquals(0, modelWriter.getCDataFieldSet().size()); + + assertFalse(modelWriter.isJsonOutput()); + modelWriter.setJsonOutput(true); + assertTrue(modelWriter.isJsonOutput()); + modelWriter.setJsonOutput(false); + assertFalse(modelWriter.isJsonOutput()); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + modelWriter.write(model, baos); + modelWriter.setJsonOutput(true); + modelWriter.write(model, baos); + modelWriter.setJsonOutput(false); + + modelWriter.setValidateFlag(false); + modelWriter.write(model, baos); + modelWriter.setJsonOutput(true); + modelWriter.write(model, baos); + modelWriter.setJsonOutput(false); + + modelWriter.setValidateFlag(true); + model.getKeyInformation().getKeyInfoMap().clear(); + try { + modelWriter.write(model, baos); + fail("Test should throw an exception here"); + } + catch (Exception e) { + assertEquals("Apex concept xml (BasicModel:0.0.1) validation failed", e.getMessage()); + } + model.getKeyInformation().generateKeyInfo(model); + + try { + modelWriter.write(null, baos); + fail("Test should throw an exception here"); + } + catch (Exception e) { + assertEquals("concept may not be null", e.getMessage()); + } + + try { + ByteArrayOutputStream nullBaos = null; + modelWriter.write(model, nullBaos); + fail("Test should throw an exception here"); + } + catch (Exception e) { + assertEquals("concept stream may not be null", e.getMessage()); + } + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestSchemaGenerator.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestSchemaGenerator.java new file mode 100644 index 000000000..cdf3b4615 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/handling/TestSchemaGenerator.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.handling; + +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintStream; + +import org.junit.Test; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestSchemaGenerator { + + @Test + public void test() throws IOException { + final ByteArrayOutputStream baos0 = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos0)); + + final String[] args0 = {}; + ApexSchemaGenerator.main(args0); + assertTrue(baos0.toString().contains("usage: ApexSchemaGenerator apex-root-class [schema-file-name]")); + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + + final ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos1)); + + final String[] args1 = { "hello", "goodbye", "here" }; + ApexSchemaGenerator.main(args1); + assertTrue(baos1.toString().contains("usage: ApexSchemaGenerator apex-root-class [schema-file-name]")); + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + + final ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos2)); + + final String[] args2 = { "hello", "goodbye" }; + ApexSchemaGenerator.main(args2); + assertTrue(baos2.toString().contains("error on Apex schema output")); + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + + final ByteArrayOutputStream baos3 = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos3)); + + final String[] args3 = { "hello" }; + ApexSchemaGenerator.main(args3); + assertTrue(baos3.toString().contains("could not create JAXB context, root class hello not found")); + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + + final ByteArrayOutputStream baos4 = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos4)); + + final String[] args4 = { "org.onap.policy.apex.model.basicmodel.concepts.AxModel" }; + ApexSchemaGenerator.main(args4); + assertTrue(baos4.toString().contains("targetNamespace=\"http://www.onap.org/policy/apex-pdp\"")); + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + + final ByteArrayOutputStream baos5 = new ByteArrayOutputStream(); + System.setOut(new PrintStream(baos5)); + + final File tempFile = File.createTempFile("ApexSchemaGeneratorTest", "xsd"); + final String[] args5 = + { "org.onap.policy.apex.model.basicmodel.concepts.AxModel", tempFile.getCanonicalPath() }; + + ApexSchemaGenerator.main(args5); + assertTrue(tempFile.length() > 100); + System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); + tempFile.delete(); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/IllegalParameters.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/IllegalParameters.java new file mode 100644 index 000000000..3a7fdf530 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/IllegalParameters.java @@ -0,0 +1,32 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class IllegalParameters extends AbstractParameters { + public IllegalParameters() { + super("somewhere.over.the.rainbow"); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/LegalParameters.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/LegalParameters.java new file mode 100644 index 000000000..3de3ecb58 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/LegalParameters.java @@ -0,0 +1,32 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +import org.onap.policy.apex.model.basicmodel.service.AbstractParameters; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class LegalParameters extends AbstractParameters { + public LegalParameters() { + super(LegalParameters.class.getCanonicalName()); + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestAbstractParameters.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestAbstractParameters.java new file mode 100644 index 000000000..7afa14440 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestAbstractParameters.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import org.junit.Test; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestAbstractParameters { + + @Test + public void testAbstractParameters() { + final LegalParameters parameters = new LegalParameters(); + assertNotNull(parameters); + assertEquals( + "AbstractParameters [parameterClassName=org.onap.policy.apex.model.basicmodel.service.LegalParameters]", + parameters.toString()); + + assertEquals(LegalParameters.class, parameters.getParameterClass()); + assertEquals("org.onap.policy.apex.model.basicmodel.service.LegalParameters", + parameters.getParameterClassName()); + + try { + new IllegalParameters(); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals( + "class \"somewhere.over.the.rainbow\" not found or not an instance of \"org.onap.policy.apex.model.basicmodel.service.IllegalParameters\"", + e.getMessage()); + } + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestModelService.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestModelService.java new file mode 100644 index 000000000..9c20d837f --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestModelService.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +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 org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.handling.TestApexBasicModelCreator; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestModelService { + + @Test + public void testModelService() { + ModelService.clear(); + + assertFalse(ModelService.existsModel(AxKeyInformation.class)); + try { + ModelService.getModel(AxKeyInformation.class); + } catch (final Exception e) { + assertEquals( + "Model for org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation not found in model service", + e.getMessage()); + } + + ModelService.registerModel(AxKeyInformation.class, + new TestApexBasicModelCreator().getModel().getKeyInformation()); + assertTrue(ModelService.existsModel(AxKeyInformation.class)); + assertNotNull(ModelService.getModel(AxKeyInformation.class)); + + ModelService.deregisterModel(AxKeyInformation.class); + + assertFalse(ModelService.existsModel(AxKeyInformation.class)); + try { + ModelService.getModel(AxKeyInformation.class); + } catch (final Exception e) { + assertEquals( + "Model for org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation not found in model service", + e.getMessage()); + } + + ModelService.registerModel(AxKeyInformation.class, + new TestApexBasicModelCreator().getModel().getKeyInformation()); + assertTrue(ModelService.existsModel(AxKeyInformation.class)); + assertNotNull(ModelService.getModel(AxKeyInformation.class)); + + ModelService.clear(); + assertFalse(ModelService.existsModel(AxKeyInformation.class)); + try { + ModelService.getModel(AxKeyInformation.class); + } catch (final Exception e) { + assertEquals( + "Model for org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation not found in model service", + e.getMessage()); + } + + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestParameterService.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestParameterService.java new file mode 100644 index 000000000..e84b3e252 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/service/TestParameterService.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.service; + +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 org.junit.Test; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestParameterService { + + @Test + public void testParameterService() { + ParameterService.clear(); + + assertFalse(ParameterService.existsParameters(LegalParameters.class)); + try { + ParameterService.getParameters(LegalParameters.class); + } catch (final Exception e) { + assertEquals( + "Parameters for org.onap.policy.apex.model.basicmodel.service.LegalParameters not found in parameter service", + e.getMessage()); + } + + ParameterService.registerParameters(LegalParameters.class, new LegalParameters()); + assertTrue(ParameterService.existsParameters(LegalParameters.class)); + assertNotNull(ParameterService.getParameters(LegalParameters.class)); + + ParameterService.deregisterParameters(LegalParameters.class); + + assertFalse(ParameterService.existsParameters(LegalParameters.class)); + try { + ParameterService.getParameters(LegalParameters.class); + } catch (final Exception e) { + assertEquals( + "Parameters for org.onap.policy.apex.model.basicmodel.service.LegalParameters not found in parameter service", + e.getMessage()); + } + + ParameterService.registerParameters(LegalParameters.class, new LegalParameters()); + assertTrue(ParameterService.existsParameters(LegalParameters.class)); + assertNotNull(ParameterService.getParameters(LegalParameters.class)); + + assertNotNull(ParameterService.getAll()); + ParameterService.clear(); + assertFalse(ParameterService.existsParameters(LegalParameters.class)); + try { + ParameterService.getParameters(LegalParameters.class); + } catch (final Exception e) { + assertEquals( + "Parameters for org.onap.policy.apex.model.basicmodel.service.LegalParameters not found in parameter service", + e.getMessage()); + } + + } +} diff --git a/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java new file mode 100644 index 000000000..bde0956b8 --- /dev/null +++ b/model/basic-model/src/test/java/org/onap/policy/apex/model/basicmodel/xml/TestAxReferenceKeyAdapter.java @@ -0,0 +1,46 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.basicmodel.xml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.xml.AxReferenceKeyAdapter; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestAxReferenceKeyAdapter { + + @Test + public void test() throws Exception { + AxReferenceKeyAdapter arka = new AxReferenceKeyAdapter(); + assertNotNull(arka); + + AxReferenceKey rKey = new AxReferenceKey("Name", "0.0.1", "PLN", "LN"); + + String rKeyString = arka.marshal(rKey); + assertEquals("LN", rKeyString); + assertEquals(rKey.getLocalName(),arka.unmarshal(rKeyString).getLocalName()); + } +} diff --git a/model/basic-model/src/test/resources/META-INF/persistence.xml b/model/basic-model/src/test/resources/META-INF/persistence.xml index 5d02906fc..a7bf1f6ac 100644 --- a/model/basic-model/src/test/resources/META-INF/persistence.xml +++ b/model/basic-model/src/test/resources/META-INF/persistence.xml @@ -23,14 +23,14 @@ org.eclipse.persistence.jpa.PersistenceProvider - org.onap.apex.model.basicmodel.dao.converters.CDATAConditioner - org.onap.apex.model.basicmodel.dao.converters.UUID2String - org.onap.apex.model.basicmodel.concepts.AxArtifactKey - org.onap.apex.model.basicmodel.concepts.AxReferenceKey - org.onap.apex.model.basicmodel.concepts.AxKeyInfo - org.onap.apex.model.basicmodel.concepts.AxKeyInformation - org.onap.apex.model.basicmodel.concepts.AxModel - org.onap.apex.model.basicmodel.concepts.TestEntity + org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner + org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String + org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey + org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey + org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo + org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation + org.onap.policy.apex.model.basicmodel.concepts.AxModel + org.onap.policy.apex.model.basicmodel.concepts.TestEntity diff --git a/model/basic-model/src/test/resources/logback-test.xml b/model/basic-model/src/test/resources/logback-test.xml index d9d77f797..4ece82083 100644 --- a/model/basic-model/src/test/resources/logback-test.xml +++ b/model/basic-model/src/test/resources/logback-test.xml @@ -44,8 +44,7 @@ - + ${LOG_DIR}/apex.log %d %-5relative [procId=${processId}] [%thread] %-5level @@ -53,8 +52,7 @@ - + ${LOG_DIR}/apex_ctxt.log %d %-5relative [procId=${processId}] [%thread] %-5level @@ -62,11 +60,11 @@ - + - + diff --git a/model/context-model/pom.xml b/model/context-model/pom.xml index 9f7766c79..b7ee5b447 100644 --- a/model/context-model/pom.xml +++ b/model/context-model/pom.xml @@ -36,12 +36,6 @@ basic-model ${project.version} - - org.apache.derby - derby - 10.13.1.1 - test - @@ -57,10 +51,10 @@ java - org.onap.apex.model.basicmodel.handling.ApexSchemaGenerator + org.onap.policy.apex.model.basicmodel.handling.ApexSchemaGenerator compile - org.onap.apex.model.contextmodel.concepts.AxContextModel + org.onap.policy.apex.model.contextmodel.concepts.AxContextModel ${project.build.directory}/model/xml/apex-context-model.xsd diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbum.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbum.java deleted file mode 100644 index 045ea0aba..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbum.java +++ /dev/null @@ -1,426 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import java.util.List; - -import javax.persistence.AttributeOverride; -import javax.persistence.AttributeOverrides; -import javax.persistence.Column; -import javax.persistence.Embedded; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyUse; -import org.onap.apex.model.basicmodel.concepts.AxValidationMessage; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class is used to define an album of context. - *

- * A context album is a distributed map of context that will be distributed across all process - * instances that require access to it. This class defines the schema (structure) of the items in - * the context album, whether the items on the context album are writable or not, and what the scope - * of the context album is. - *

- * The structure of items (objects) the context album is defined as a schema, which is understood by - * whatever schema implementation is being used for the context album. - *

- * The scope of a context album is a string field, understood by whatever distribution mechanism is - * being used for the context album. The distribution mechanism uses the scope of the context album - * to decide to which executable entities a given context album is distributed. - *

- * The writable flag on a context album defines whether users of a context album can write to the - * context album or just read objects from the context album. - *

- * Validation checks that the album key and the context schema key are not null and that the scope - * field is not undefined and matches the regular expression {@link SCOPE_REGEXP}. - */ -@Entity -@Table(name = "AxContextAlbum") - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "apexContextAlbum", namespace = "http://www.ericsson.com/apex") -@XmlType(name = "AxContextAlbum", namespace = "http://www.ericsson.com/apex", - propOrder = {"key", "scope", "isWritable", "itemSchema"}) - -public class AxContextAlbum extends AxConcept { - private static final String SCOPE_STRING = "scope"; - - private static final long serialVersionUID = 4290442590545820316L; - - /** - * The legal values for the scope of a context album is constrained by this regular expression. - */ - public static final String SCOPE_REGEXP = "[A-Za-z0-9\\-_]+"; - - /** The value of scope for a context album for which a scope has not been specified. */ - public static final String SCOPE_UNDEFINED = "UNDEFINED"; - - private static final int HASH_PRIME_0 = 1231; - private static final int HASH_PRIME_1 = 1237; - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - @Column(name = SCOPE_STRING) - @XmlElement(name = SCOPE_STRING, required = true) - private String scope; - - @Column(name = "isWritable") - @XmlElement(name = "isWritable", required = true) - private boolean isWritable; - - // @formatter:off - @Embedded - @AttributeOverrides({ - @AttributeOverride(name = "name", column = @Column(name = "itemSchemaName")), - @AttributeOverride(name = "version", column = @Column(name = "itemSchemaVersion")) - }) - @Column(name = "itemSchema") - @XmlElement(name = "itemSchema", required = true) - private AxArtifactKey itemSchema; - // @formatter:on - - /** - * The default constructor creates a context album with a null artifact key. The scope of the - * context album is set as {@link SCOPE_UNDEFINED}, the album is writable, and the artifact key - * of the context schema is set to the null artifact key. - */ - public AxContextAlbum() { - this(new AxArtifactKey()); - scope = SCOPE_UNDEFINED; - isWritable = true; - itemSchema = AxArtifactKey.getNullKey(); - } - - /** - * Copy constructor - * - * @param copyConcept the concept to copy from - */ - public AxContextAlbum(final AxContextAlbum copyConcept) { - super(copyConcept); - } - - /** - * The keyed constructor creates a context album with the specified artifact key. The scope of - * the context album is set as {@link SCOPE_UNDEFINED}, the album is writable, and the artifact - * key of the context schema is set to the null artifact key. - * - * @param key the key of the context album - */ - public AxContextAlbum(final AxArtifactKey key) { - this(key, SCOPE_UNDEFINED, true, AxArtifactKey.getNullKey()); - } - - /** - * Constructor that sets all the fields of the context album. - * - * @param key the key of the context album - * @param scope the scope field, must match the regular expression {@link SCOPE_REGEXP} - * @param isWritable specifies whether the context album will be writable or not - * @param itemSchema the artifact key of the context schema to use for this context album - */ - public AxContextAlbum(final AxArtifactKey key, final String scope, final boolean isWritable, - final AxArtifactKey itemSchema) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(scope, "scope may not be null"); - Assertions.argumentNotNull(itemSchema, "itemSchema may not be null"); - - this.key = key; - this.scope = Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); - this.isWritable = isWritable; - this.itemSchema = itemSchema; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = key.getKeys(); - keyList.add(new AxKeyUse(itemSchema.getKey())); - - return keyList; - } - - /** - * Sets the key of the context album. - * - * @param key the context album key - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the scope of the context album. - * - * @return the context album scope - */ - public String getScope() { - return scope; - } - - /** - * Sets the scope of the context album. - * - * @param scope the context album scope - */ - public void setScope(final String scope) { - Assertions.argumentNotNull(scope, "scope may not be null"); - this.scope = Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); - } - - /** - * Sets whether the album is writable or not. - * - * @param writable the writable flag value - */ - public void setWritable(final boolean writable) { - this.isWritable = writable; - } - - /** - * Checks if the album is writable. - * - * @return true, if the album is writable - */ - public boolean isWritable() { - return isWritable; - } - - /** - * Gets the artifact key of the item schema of this context album. - * - * @return the item schema key - */ - public AxArtifactKey getItemSchema() { - return itemSchema; - } - - /** - * Sets the artifact key of the item schema of this context album. - * - * @param itemSchema the item schema key - */ - public void setItemSchema(final AxArtifactKey itemSchema) { - Assertions.argumentNotNull(itemSchema, "itemSchema key may not be null"); - this.itemSchema = itemSchema; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com.ericsson.apex.model. - * basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - result = key.validate(result); - - if (scope.replaceAll("\\s+$", "").length() == 0 || scope.equals(SCOPE_UNDEFINED)) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "scope is not defined")); - } - - try { - Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); - } catch (final IllegalArgumentException e) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "scope invalid-" + e.getMessage())); - } - - if (itemSchema.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "itemSchema reference is a null key, an item schema must be specified")); - } - result = itemSchema.validate(result); - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - scope = Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); - itemSchema.clean(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("key="); - builder.append(key); - builder.append(",scope="); - builder.append(scope); - builder.append(",isWritable="); - builder.append(isWritable); - builder.append(",itemSchema="); - builder.append(itemSchema); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model. - * basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "targetObject may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxContextAlbum.class); - - final AxContextAlbum copy = ((AxContextAlbum) copyObject); - copy.setKey(new AxArtifactKey(key)); - copy.setScope(scope); - copy.setWritable(isWritable); - copy.setItemSchema(new AxArtifactKey(itemSchema)); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + scope.hashCode(); - result = prime * result + (isWritable ? HASH_PRIME_0 : HASH_PRIME_1); - result = prime * result + itemSchema.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - final AxContextAlbum other = (AxContextAlbum) obj; - if (!key.equals(other.key)) { - return false; - } - if (!scope.equals(other.scope)) { - return false; - } - if (isWritable != other.isWritable) { - return (false); - } - return itemSchema.equals(other.itemSchema); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxContextAlbum other = (AxContextAlbum) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - if (!scope.equals(other.scope)) { - return scope.compareTo(other.scope); - } - if (isWritable != other.isWritable) { - return (isWritable ? 1 : -1); - } - return itemSchema.compareTo(other.itemSchema); - } -} diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbums.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbums.java deleted file mode 100644 index e48d064cb..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextAlbums.java +++ /dev/null @@ -1,427 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.Set; -import java.util.TreeMap; - -import javax.persistence.CascadeType; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.OneToMany; -import javax.persistence.Table; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxConceptGetter; -import org.onap.apex.model.basicmodel.concepts.AxConceptGetterImpl; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationMessage; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class is a context album container and holds a map of the context albums for an entire Apex - * model. All Apex models that use context albums must have an {@link AxContextAlbums} field. The - * {@link AxContextAlbums} class implements the helper methods of the {@link AxConceptGetter} - * interface to allow {@link AxContextAlbum} instances to be retrieved by calling methods directly - * on this class without referencing the contained map. - *

- * Validation checks that the container key is not null. An observation is issued if no context - * albums are defined in the container. If context albums do exist, they are checked to ensure that - * keys and values are not null and that the map key matches the key in the map value for all album - * entries. Each context album entry is then validated individually. - */ -@Entity -@Table(name = "AxContextAlbums") - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "AxContextAlbums", namespace = "http://www.ericsson.com/apex", propOrder = {"key", "albums"}) - -public final class AxContextAlbums extends AxConcept implements AxConceptGetter { - private static final long serialVersionUID = -4844259809024470975L; - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - // @formatter:off - @OneToMany(cascade = CascadeType.ALL) - @JoinTable(joinColumns = {@JoinColumn(name = "contextName", referencedColumnName = "name"), - @JoinColumn(name = "contextVersion", referencedColumnName = "version")}) - @XmlElement(name = "albums", required = true) - private Map albums; - // @formatter:on - - /** - * The Default Constructor creates a {@link AxContextAlbums} object with a null artifact key and - * creates an empty context album map. - */ - public AxContextAlbums() { - this(new AxArtifactKey()); - } - - /** - * Copy constructor - * - * @param copyConcept the concept to copy from - */ - public AxContextAlbums(final AxContextAlbums copyConcept) { - super(copyConcept); - } - - /** - * The Key Constructor creates a {@link AxContextAlbums} object with the given artifact key and - * creates an empty context album map. - * - * @param key the key of the context album container - */ - public AxContextAlbums(final AxArtifactKey key) { - this(key, new TreeMap()); - } - - /** - * Constructor that creates the context album map with the given albums and key. - * - * @param key the key of the context album container - * @param albums the context albums to place in this context album container - */ - public AxContextAlbums(final AxArtifactKey key, final Map albums) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(albums, "albums may not be null"); - - this.key = key; - this.albums = new TreeMap<>(); - this.albums.putAll(albums); - } - - /** - * When a model is unmarshalled from disk or from the database, the context album map is - * returned as a raw hash map. This method is called by JAXB after unmarshaling and is used to - * convert the hash map to a {@link NavigableMap} so that it will work with the - * {@link AxConceptGetter} interface. - * - * @param u the unmarshaler that is unmarshaling the model - * @param parent the parent object of this object in the unmarshaler - */ - public void afterUnmarshal(final Unmarshaller u, final Object parent) { - // The map must be navigable to allow name and version searching, unmarshaling returns a - // hash map - final NavigableMap navigableAlbums = new TreeMap<>(); - navigableAlbums.putAll(albums); - albums = navigableAlbums; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = key.getKeys(); - - for (final AxContextAlbum contextAlbum : albums.values()) { - keyList.addAll(contextAlbum.getKeys()); - } - - return keyList; - } - - /** - * Sets the key of the context album container. - * - * @param key the context album container key - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the map of context albums from the context album container. - * - * @return the context album map - */ - public Map getAlbumsMap() { - return albums; - } - - /** - * Sets the map of context albums from the context album container. - * - * @param albumsMap the map of context albums to place in the container - */ - public void setAlbumsMap(final Map albumsMap) { - Assertions.argumentNotNull(albumsMap, "albums may not be null"); - this.albums = new TreeMap<>(); - this.albums.putAll(albumsMap); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - for (final Entry contextAlbumEntry : albums.entrySet()) { - contextAlbumEntry.getKey().clean(); - contextAlbumEntry.getValue().clean(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("key="); - builder.append(key); - builder.append(",albums="); - builder.append(albums); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com.ericsson.apex.model. - * basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - - result = key.validate(result); - - if (albums.size() == 0) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.OBSERVATION, "albums are empty")); - } else { - for (final Entry contextAlbumEntry : albums.entrySet()) { - if (contextAlbumEntry.getKey().equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key on context album entry " + contextAlbumEntry.getKey() + " may not be the null key")); - } else if (contextAlbumEntry.getValue() == null) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "value on context album entry " + contextAlbumEntry.getKey() + " may not be null")); - } else { - if (!contextAlbumEntry.getKey().equals(contextAlbumEntry.getValue().getKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key on context album entry key " + contextAlbumEntry.getKey() - + " does not equal context album value key " - + contextAlbumEntry.getValue().getKey())); - } - - result = contextAlbumEntry.getValue().validate(result); - } - } - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model. - * basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxContextAlbums.class); - - final AxContextAlbums copy = ((AxContextAlbums) copyObject); - copy.setKey(key); - final Map newContextAlbum = new TreeMap<>(); - for (final Entry contextAlbumEntry : albums.entrySet()) { - newContextAlbum.put(new AxArtifactKey(contextAlbumEntry.getKey()), - new AxContextAlbum(contextAlbumEntry.getValue())); - } - copy.setAlbumsMap(newContextAlbum); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + albums.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - final AxContextAlbums other = (AxContextAlbums) obj; - if (!key.equals(other.key)) { - return false; - } - return albums.equals(other.albums); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxContextAlbums other = (AxContextAlbums) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - if (!albums.equals(other.albums)) { - return (albums.hashCode() - other.albums.hashCode()); - } - - return 0; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConceptGetter#get(com.ericsson.apex.model. - * basicmodel.concepts.AxArtifactKey) - */ - @Override - public AxContextAlbum get(final AxArtifactKey conceptKey) { - return new AxConceptGetterImpl<>((NavigableMap) albums).get(conceptKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String) - */ - @Override - public AxContextAlbum get(final String conceptKeyName) { - return new AxConceptGetterImpl<>((NavigableMap) albums).get(conceptKeyName); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String, - * java.lang.String) - */ - @Override - public AxContextAlbum get(final String conceptKeyName, final String conceptKeyVersion) { - return new AxConceptGetterImpl<>((NavigableMap) albums).get(conceptKeyName, - conceptKeyVersion); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String) - */ - @Override - public Set getAll(final String conceptKeyName) { - return new AxConceptGetterImpl<>((NavigableMap) albums).getAll(conceptKeyName); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, - * java.lang.String) - */ - @Override - public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { - return new AxConceptGetterImpl<>((NavigableMap) albums).getAll(conceptKeyName, - conceptKeyVersion); - } -} diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextModel.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextModel.java deleted file mode 100644 index dcd381872..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextModel.java +++ /dev/null @@ -1,346 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.JoinColumns; -import javax.persistence.OneToOne; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.concepts.AxModel; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.service.ModelService; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * A container class for an Apex context model. This class is a container class that allows an Apex - * model to be constructed that just contains context and the key information for that context. The - * model contains schema definitions and the definitions of context albums that use those schemas. - * In the case where Apex context is being used without policy or independent of policy, an Apex - * context model is sufficient to get Apex context working. - *

- * Validation runs {@link AxModel} validation on the model. In addition, the - * {@link AxContextSchemas} and {@link AxContextAlbums} validation is run on the context schemas and - * albums in the model. - */ -@Entity -@Table(name = "AxContextModel") - -@XmlRootElement(name = "apexContextModel", namespace = "http://www.ericsson.com/apex") -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "AxContextModel", namespace = "http://www.ericsson.com/apex", propOrder = {"schemas", "albums"}) - -public class AxContextModel extends AxModel { - private static final long serialVersionUID = 8800599637708309945L; - - // @formatter:off - @OneToOne(cascade = CascadeType.ALL) - @JoinColumns({ - @JoinColumn(name = "schemasName", referencedColumnName = "name"), - @JoinColumn(name = "schemasVersion", referencedColumnName = "version") - }) - @XmlElement(name = "schemas", required = true) - private AxContextSchemas schemas; - - @OneToOne(cascade = CascadeType.ALL) - @JoinColumns({ - @JoinColumn(name = "albumsName", referencedColumnName = "name"), - @JoinColumn(name = "albumsVersion", referencedColumnName = "version") - }) - @XmlElement(name = "albums", required = true) - private AxContextAlbums albums; - // @formatter:on - - /** - * The Default Constructor creates a {@link AxContextModel} object with a null artifact key and - * creates an empty context model. - */ - public AxContextModel() { - this(new AxArtifactKey()); - } - - /** - * The Key Constructor creates a {@link AxContextModel} object with the given artifact key and - * creates an empty context model. - * - * @param key the key of the context model - */ - public AxContextModel(final AxArtifactKey key) { - this(key, new AxContextSchemas(new AxArtifactKey(key.getName() + "_Schemas", key.getVersion())), - new AxContextAlbums(new AxArtifactKey(key.getName() + "_Albums", key.getVersion())), - new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion()))); - } - - /** - * Copy constructor - * - * @param copyConcept the concept to copy from - */ - public AxContextModel(final AxContextModel copyConcept) { - super(copyConcept); - } - - /** - * Constructor that initiates a {@link AxContextModel} with schemas and keys for those schemas. - * An empty {@link AxContextAlbums} container is created. - * - * @param key the key of the context model - * @param schemas the context schema definitions - * @param keyInformation the key information for those context schemas - */ - public AxContextModel(final AxArtifactKey key, final AxContextSchemas schemas, - final AxKeyInformation keyInformation) { - this(key, schemas, new AxContextAlbums(new AxArtifactKey(key.getName() + "_Albums", key.getVersion())), - keyInformation); - } - - /** - * Constructor that initiates a {@link AxContextModel} with all its fields. - * - * @param key the key of the context model - * @param schemas the context schema definitions - * @param albums the context album container containing context albums - * @param keyInformation the key information for those context schemas - */ - public AxContextModel(final AxArtifactKey key, final AxContextSchemas schemas, final AxContextAlbums albums, - final AxKeyInformation keyInformation) { - super(key, keyInformation); - Assertions.argumentNotNull(schemas, "schemas may not be null"); - Assertions.argumentNotNull(albums, "albums may not be null"); - this.schemas = schemas; - this.albums = albums; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#register() - */ - @Override - public void register() { - super.register(); - ModelService.registerModel(AxContextSchemas.class, getSchemas()); - ModelService.registerModel(AxContextAlbums.class, getAlbums()); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#getKeys() - */ - @Override - public List getKeys() { - final List keyList = super.getKeys(); - - keyList.addAll(schemas.getKeys()); - keyList.addAll(albums.getKeys()); - - return keyList; - } - - /** - * Gets the context schemas from the model. - * - * @return the context schemas - */ - public AxContextSchemas getSchemas() { - return schemas; - } - - /** - * Sets the context schemas on the model. - * - * @param schemas the context schemas - */ - public void setSchemas(final AxContextSchemas schemas) { - Assertions.argumentNotNull(schemas, "schemas may not be null"); - this.schemas = schemas; - } - - /** - * Gets the context albums from the model. - * - * @return the context albums - */ - public AxContextAlbums getAlbums() { - return albums; - } - - /** - * Sets the context albums on the model. - * - * @param albums the context albums - */ - public void setAlbums(final AxContextAlbums albums) { - Assertions.argumentNotNull(albums, "albums may not be null"); - this.albums = albums; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#validate(com.ericsson.apex.model. - * basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - result = super.validate(result); - result = schemas.validate(result); - return albums.validate(result); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#clean() - */ - @Override - public void clean() { - super.clean(); - schemas.clean(); - albums.clean(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append(super.toString()); - builder.append(",schemas="); - builder.append(schemas); - builder.append(",albums="); - builder.append(albums); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model. - * basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxContextModel.class); - - final AxContextModel copy = ((AxContextModel) copyObject); - super.copyTo(target); - copy.setSchemas(new AxContextSchemas(schemas)); - copy.setAlbums(new AxContextAlbums(albums)); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + super.hashCode(); - result = prime * result + schemas.hashCode(); - result = prime * result + albums.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - throw new IllegalArgumentException("comparison object may not be null"); - } - - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - - final AxContextModel other = (AxContextModel) obj; - if (!super.equals(other)) { - return false; - } - if (!schemas.equals(other.schemas)) { - return false; - } - return albums.equals(other.albums); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxModel#compareTo(com.ericsson.apex.model. - * basicmodel.concepts.AxConcept) - */ - @Override - public int compareTo(final AxConcept otherObj) { - Assertions.argumentNotNull(otherObj, "comparison object may not be null"); - - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxContextModel other = (AxContextModel) otherObj; - if (!super.equals(other)) { - return super.compareTo(other); - } - if (!schemas.equals(other.schemas)) { - return schemas.compareTo(other.schemas); - } - return albums.compareTo(other.albums); - } -} diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchema.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchema.java deleted file mode 100644 index 852e3f552..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchema.java +++ /dev/null @@ -1,383 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Convert; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationMessage; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.apex.model.basicmodel.dao.converters.CDATAConditioner; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class holds a data schema definition in Apex. A data schema describes the structure of a - * single atom of data handled by Apex. This atom of data can be a primitive type such as an integer - * or a string, or it can be a more complex data type such as a Java object or an object described - * using a data definition language such as Avro. The schema flavour defines the type of schema - * being defined and the schema itself defines the schema. The schema flavour is used by Apex to - * look up and load a plugin class that understands and interprets the schema definition and can - * create instances of classes for the schema. - *

- * An {@link AxContextSchema} is used to define each parameter in Apex events, the messages that - * enter, exit, and are passed internally in Apex. In addition, an Apex {@link AxContextAlbum} - * instances hold a map of {@link AxContextSchema} instances to represent the context being managed - * as an {@link AxContextAlbum}. For example, the state of all cells in a mobile network might be - * represented as an {@link AxContextAlbum} with its {@link AxContextSchema} being defined as @code - * cell} objects. - *

- * Validation checks that the schema key is not null. It also checks that the schema flavour is - * defined and matches the regular expression {@link SCHEMA_FLAVOUR_REGEXP}. Finally, validation - * checks that the defined schema is not a blank or empty string. - */ -@Entity -@Table(name = "AxContextSchema") - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlRootElement(name = "apexContextSchema", namespace = "http://www.ericsson.com/apex") -@XmlType(name = "AxContextSchema", namespace = "http://www.ericsson.com/apex", - propOrder = {"key", "schemaFlavour", "schemaDefinition"}) - -public class AxContextSchema extends AxConcept { - private static final String SCHEMA_FLAVOUR = "schemaFlavour"; - private static final String WHITESPACE_REGEXP = "\\s+$"; - - private static final long serialVersionUID = -6443016863162692288L; - - /** Regular expression that constrains what values a schema flavour can have. */ - public static final String SCHEMA_FLAVOUR_REGEXP = "[A-Za-z0-9\\-_]+"; - - /** An undefined schema flavour has this value. */ - public static final String SCHEMA_FLAVOUR_UNDEFINED = "UNDEFINED"; - - /** The maximum permissible size of a schema definition. */ - public static final int MAX_SCHEMA_SIZE = 32672; // The maximum size supported by Apache Derby - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - @Column(name = SCHEMA_FLAVOUR) - @XmlElement(required = true) - private String schemaFlavour; - - @Column(name = "schemaDefinition", length = MAX_SCHEMA_SIZE) - @Convert(converter = CDATAConditioner.class) - @XmlJavaTypeAdapter(value = CDATAConditioner.class) - @XmlElement(name = "schemaDefinition", required = true) - private String schemaDefinition; - - /** - * The default constructor creates a context schema with a null artifact key. The flavour of the - * context album is set as {@link SCHEMA_FLAVOUR_UNDEFINED} and the schema itself is defined as - * an empty string. - */ - public AxContextSchema() { - this(new AxArtifactKey()); - schemaFlavour = SCHEMA_FLAVOUR_UNDEFINED; - } - - /** - * Copy constructor - * - * @param copyConcept the concept to copy from - */ - public AxContextSchema(final AxContextSchema copyConcept) { - super(copyConcept); - } - - /** - * The key constructor creates a context schema with the given artifact key. The flavour of the - * context album is set as {@link SCHEMA_FLAVOUR_UNDEFINED} and the schema itself is defined as - * an empty string. - * - * @param key the key - */ - public AxContextSchema(final AxArtifactKey key) { - this(key, SCHEMA_FLAVOUR_UNDEFINED, ""); - } - - /** - * This Constructor creates a context schema with all of its fields defined. - * - * @param key the key - * @param schemaFlavour the schema flavour - * @param schemaDefinition the schema definition - */ - public AxContextSchema(final AxArtifactKey key, final String schemaFlavour, final String schemaDefinition) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(schemaFlavour, "schemaFlavour may not be null"); - Assertions.argumentNotNull(schemaDefinition, "schemaDefinition may not be null"); - - this.key = key; - this.schemaFlavour = Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); - this.schemaDefinition = schemaDefinition.replaceAll(WHITESPACE_REGEXP, ""); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - return key.getKeys(); - } - - /** - * Sets the key of the context schema. - * - * @param key the key of the context schema - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the schema flavour, which defines the schema definition type being used. - * - * @return the schema flavour - */ - public String getSchemaFlavour() { - return schemaFlavour; - } - - /** - * Sets the schema flavour, which defines the type of schema definition being used. - * - * @param schemaFlavour the schema flavour - */ - public void setSchemaFlavour(final String schemaFlavour) { - this.schemaFlavour = Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); - } - - /** - * Gets the schema, which defines the structure of this data schema atom. - * - * @return the schema definition - */ - public String getSchema() { - return schemaDefinition; - } - - /** - * Sets the schema, which defines the structure of this data schema atom. - * - * @param schema the schema definition - */ - public void setSchema(final String schema) { - Assertions.argumentNotNull(schema, "schema may not be null"); - this.schemaDefinition = schema.replaceAll(WHITESPACE_REGEXP, ""); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com.ericsson.apex.model. - * basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - - result = key.validate(result); - - if (schemaFlavour.replaceAll(WHITESPACE_REGEXP, "").length() == 0 - || schemaFlavour.equals(SCHEMA_FLAVOUR_UNDEFINED)) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "schema flavour is not defined")); - } - - try { - Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); - } catch (final IllegalArgumentException e) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "schema flavour invalid-" + e.getMessage())); - } - - if (schemaDefinition.replaceAll(WHITESPACE_REGEXP, "").length() == 0) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "no schemaDefinition specified, schemaDefinition may not be blank")); - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - schemaFlavour = Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); - schemaDefinition = schemaDefinition.replaceAll(WHITESPACE_REGEXP, ""); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("key="); - builder.append(key); - builder.append(",schemaFlavour="); - builder.append(schemaFlavour); - builder.append(",schemaDefinition="); - builder.append(schemaDefinition); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model. - * basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxContextSchema.class); - - final AxContextSchema copy = ((AxContextSchema) copyObject); - copy.setKey(new AxArtifactKey(key)); - copy.setSchemaFlavour(schemaFlavour); - copy.setSchema(schemaDefinition); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + schemaFlavour.hashCode(); - result = prime * result + schemaDefinition.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - - if (getClass() != obj.getClass()) { - return false; - } - - final AxContextSchema other = (AxContextSchema) obj; - - if (!key.equals(other.key)) { - return false; - } - if (!schemaFlavour.equals(other.schemaFlavour)) { - return false; - } - final String thisSchema = CDATAConditioner.clean(schemaDefinition).replaceAll("\n", ""); - final String otherSchema = CDATAConditioner.clean(other.schemaDefinition).replaceAll("\n", ""); - return thisSchema.equals(otherSchema); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxContextSchema other = (AxContextSchema) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - if (!schemaFlavour.equals(other.schemaFlavour)) { - return schemaFlavour.compareTo(other.schemaFlavour); - } - final String thisSchema = CDATAConditioner.clean(schemaDefinition).replaceAll("\n", ""); - final String otherSchema = CDATAConditioner.clean(other.schemaDefinition).replaceAll("\n", ""); - return thisSchema.compareTo(otherSchema); - } -} diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchemas.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchemas.java deleted file mode 100644 index b4a7e4ada..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/AxContextSchemas.java +++ /dev/null @@ -1,424 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.Set; -import java.util.TreeMap; - -import javax.persistence.CascadeType; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxConcept; -import org.onap.apex.model.basicmodel.concepts.AxConceptGetter; -import org.onap.apex.model.basicmodel.concepts.AxConceptGetterImpl; -import org.onap.apex.model.basicmodel.concepts.AxKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationMessage; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.policy.apex.model.utilities.Assertions; - -/** - * This class is a context schema container and holds a map of the context schemas for an entire - * Apex model. All Apex models that use context schemas must have an {@link AxContextSchemas} field. - * The {@link AxContextSchemas} class implements the helper methods of the {@link AxConceptGetter} - * interface to allow {@link AxContextSchema} instances to be retrieved by calling methods directly - * on this class without referencing the contained map. - *

- * Validation checks that the container key is not null. An error is issued if no context schemas - * are defined in the container. Each context schema entry is checked to ensure that its key and - * value are not null and that the key matches the key in the map value. Each context schema entry - * is then validated individually. - */ -@Entity -@Table(name = "AxContextSchemas") - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "AxContextSchemas", namespace = "http://www.ericsson.com/apex", propOrder = {"key", "schemas"}) - -public class AxContextSchemas extends AxConcept implements AxConceptGetter { - private static final long serialVersionUID = -3203734282886453582L; - - @EmbeddedId - @XmlElement(name = "key", required = true) - private AxArtifactKey key; - - // @formatter:off - @ManyToMany(cascade = CascadeType.ALL) - @JoinTable( - joinColumns = {@JoinColumn(name = "contextSchemasName", referencedColumnName = "name"), - @JoinColumn(name = "contextSchemasVersion", referencedColumnName = "version")}, - inverseJoinColumns = {@JoinColumn(name = "contextSchemaName", referencedColumnName = "name"), - @JoinColumn(name = "contextSchemaVersion", referencedColumnName = "version")}) - @XmlElement(name = "schemas", required = true) - private Map schemas; - // @formatter:on - - /** - * The Default Constructor creates a {@link AxContextSchemas} object with a null artifact key - * and creates an empty context schemas map. - */ - public AxContextSchemas() { - this(new AxArtifactKey()); - } - - /** - * Copy constructor - * - * @param copyConcept the concept to copy from - */ - public AxContextSchemas(final AxContextSchemas copyConcept) { - super(copyConcept); - } - - /** - * The Key Constructor creates a {@link AxContextSchemas} object with the given artifact key and - * creates an empty context schemas map. - * - * @param key the key of the context album container - */ - public AxContextSchemas(final AxArtifactKey key) { - this(key, new TreeMap()); - } - - /** - * This Constructor creates a {@link AxContextSchemas} object with all its fields defined. - * - * @param key the key of the context schema container - * @param schemas a map of the schemas to insert in the context schema container - */ - public AxContextSchemas(final AxArtifactKey key, final Map schemas) { - super(); - Assertions.argumentNotNull(key, "key may not be null"); - Assertions.argumentNotNull(schemas, "schemas may not be null"); - - this.key = key; - this.schemas = new TreeMap<>(); - this.schemas.putAll(schemas); - } - - /** - * When a model is unmarshalled from disk or from the database, the context schema map is - * returned as a raw hash map. This method is called by JAXB after unmarshaling and is used to - * convert the hash map to a {@link NavigableMap} so that it will work with the - * {@link AxConceptGetter} interface. - * - * @param u the unmarshaler that is unmarshaling the model - * @param parent the parent object of this object in the unmarshaler - */ - public void afterUnmarshal(final Unmarshaller u, final Object parent) { - // The map must be navigable to allow name and version searching, unmarshaling returns a - // hash map - final NavigableMap navigableContextSchemas = new TreeMap<>(); - navigableContextSchemas.putAll(schemas); - schemas = navigableContextSchemas; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKey() - */ - @Override - public AxArtifactKey getKey() { - return key; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#getKeys() - */ - @Override - public List getKeys() { - final List keyList = key.getKeys(); - keyList.addAll(schemas.keySet()); - - return keyList; - } - - /** - * Sets the key of the context schema container. - * - * @param key the key of the container - */ - public void setKey(final AxArtifactKey key) { - Assertions.argumentNotNull(key, "key may not be null"); - this.key = key; - } - - /** - * Gets the map of context schemas in this container. - * - * @return the map of schemas - */ - public Map getSchemasMap() { - return schemas; - } - - /** - * Sets the map of context schemas in this container. - * - * @param schemasMap the map of schemas - */ - public void setSchemasMap(final Map schemasMap) { - Assertions.argumentNotNull(schemasMap, "schemasMap may not be null"); - - this.schemas = new TreeMap<>(); - this.schemas.putAll(schemasMap); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#validate(com.ericsson.apex.model. - * basicmodel.concepts.AxValidationResult) - */ - @Override - public AxValidationResult validate(final AxValidationResult resultIn) { - AxValidationResult result = resultIn; - - if (key.equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage( - new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); - } - - result = key.validate(result); - - if (schemas.size() == 0) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "contextSchemas may not be empty")); - } else { - for (final Entry contextSchemaEntry : schemas.entrySet()) { - if (contextSchemaEntry.getKey().equals(AxArtifactKey.getNullKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "key on schemas entry " + contextSchemaEntry.getKey() + " may not be the null key")); - } else if (contextSchemaEntry.getValue() == null) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "value on schemas entry " + contextSchemaEntry.getKey() + " may not be null")); - } else { - if (!contextSchemaEntry.getKey().equals(contextSchemaEntry.getValue().getKey())) { - result.addValidationMessage(new AxValidationMessage(key, this.getClass(), - ValidationResult.INVALID, "key on schemas entry " + contextSchemaEntry.getKey() - + " does not equal entry key " + contextSchemaEntry.getValue().getKey())); - } - - result = contextSchemaEntry.getValue().validate(result); - } - } - } - - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#clean() - */ - @Override - public void clean() { - key.clean(); - for (final Entry contextSchemaEntry : schemas.entrySet()) { - contextSchemaEntry.getKey().clean(); - contextSchemaEntry.getValue().clean(); - } - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#toString() - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(this.getClass().getSimpleName()); - builder.append(":("); - builder.append("key="); - builder.append(key); - builder.append(",schemas="); - builder.append(schemas); - builder.append(")"); - return builder.toString(); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#copyTo(com.ericsson.apex.model. - * basicmodel.concepts.AxConcept) - */ - @Override - public AxConcept copyTo(final AxConcept target) { - Assertions.argumentNotNull(target, "target may not be null"); - - final Object copyObject = target; - Assertions.instanceOf(copyObject, AxContextSchemas.class); - - final AxContextSchemas copy = ((AxContextSchemas) copyObject); - copy.setKey(new AxArtifactKey(key)); - - final Map newcontextSchemas = new TreeMap<>(); - for (final Entry contextSchemasEntry : schemas.entrySet()) { - newcontextSchemas.put(new AxArtifactKey(contextSchemasEntry.getKey()), - new AxContextSchema(contextSchemasEntry.getValue())); - } - copy.setSchemasMap(newcontextSchemas); - - return copy; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + key.hashCode(); - result = prime * result + schemas.hashCode(); - return result; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) - */ - @Override - public boolean equals(final Object obj) { - if (obj == null) { - return false; - } - if (this == obj) { - return true; - } - if (getClass() != obj.getClass()) { - return false; - } - - final AxContextSchemas other = (AxContextSchemas) obj; - if (!key.equals(other.key)) { - return false; - } - return schemas.equals(other.schemas); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Comparable#compareTo(java.lang.Object) - */ - @Override - public int compareTo(final AxConcept otherObj) { - if (otherObj == null) { - return -1; - } - if (this == otherObj) { - return 0; - } - if (getClass() != otherObj.getClass()) { - return this.hashCode() - otherObj.hashCode(); - } - - final AxContextSchemas other = (AxContextSchemas) otherObj; - if (!key.equals(other.key)) { - return key.compareTo(other.key); - } - if (!schemas.equals(other.schemas)) { - return (schemas.hashCode() - other.schemas.hashCode()); - } - - return 0; - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(com.ericsson.apex.core. - * basicmodel.concepts.AxArtifactKey) - */ - @Override - public AxContextSchema get(final AxArtifactKey conceptKey) { - return new AxConceptGetterImpl<>((NavigableMap) schemas).get(conceptKey); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang.String) - */ - @Override - public AxContextSchema get(final String conceptKeyName) { - return new AxConceptGetterImpl<>((NavigableMap) schemas).get(conceptKeyName); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang.String, - * java.lang.String) - */ - @Override - public AxContextSchema get(final String conceptKeyName, final String conceptKeyVersion) { - return new AxConceptGetterImpl<>((NavigableMap) schemas).get(conceptKeyName, - conceptKeyVersion); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String) - */ - @Override - public Set getAll(final String conceptKeyName) { - return new AxConceptGetterImpl<>((NavigableMap) schemas).getAll(conceptKeyName); - } - - /* - * (non-Javadoc) - * - * @see com.ericsson.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, - * java.lang.String) - */ - @Override - public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { - return new AxConceptGetterImpl<>((NavigableMap) schemas).getAll(conceptKeyName, - conceptKeyVersion); - } -} diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/package-info.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/package-info.java deleted file mode 100644 index f89f2f803..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/concepts/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Contains the concepts required to manage context in APEX. It defines the main APEX concepts of - * Context Schemas and Context Albums. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.contextmodel.concepts; diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/ContextComparer.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/ContextComparer.java deleted file mode 100644 index 8d654be74..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/ContextComparer.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.handling; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbum; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbums; -import org.onap.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.apex.model.contextmodel.concepts.AxContextSchemas; -import org.onap.policy.apex.model.utilities.comparison.KeyedMapComparer; -import org.onap.policy.apex.model.utilities.comparison.KeyedMapDifference; - -/** - * This class compares the context in two AxContext objects and returns the differences. The - * differences are returned in a {@link KeyedMapDifference} object that contains the left, equal, - * and right context schemas or albums. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class ContextComparer { - - /** - * Compare two {@link AxContextAlbums} objects, comparing their context albums one after - * another. - * - * @param left the left context - * @param right the right context - * @return the difference - */ - public KeyedMapDifference compare(final AxContextAlbums left, - final AxContextAlbums right) { - // Find the difference between the AxContext objects - return new KeyedMapComparer().compareMaps(left.getAlbumsMap(), - right.getAlbumsMap()); - } - - /** - * Compare two {@link AxContextSchema} objects, comparing their context schemas one after - * another. - * - * @param left the left context - * @param right the right context - * @return the difference - */ - public KeyedMapDifference compare(final AxContextSchemas left, - final AxContextSchemas right) { - // Find the difference between the AxContext objects - return new KeyedMapComparer().compareMaps(left.getSchemasMap(), - right.getSchemasMap()); - } - -} diff --git a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/package-info.java b/model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/package-info.java deleted file mode 100644 index bfc44f7e0..000000000 --- a/model/context-model/src/main/java/org/onap/apex/model/contextmodel/handling/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -/** - * Provides some helper classes for handling context, including a utility class for comparing two - * context objects. - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -package org.onap.apex.model.contextmodel.handling; diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java new file mode 100644 index 000000000..27f9b8b9b --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbum.java @@ -0,0 +1,425 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import java.util.List; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyUse; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is used to define an album of context. + *

+ * A context album is a distributed map of context that will be distributed across all process instances that require + * access to it. This class defines the schema (structure) of the items in the context album, whether the items on the + * context album are writable or not, and what the scope of the context album is. + *

+ * The structure of items (objects) the context album is defined as a schema, which is understood by whatever schema + * implementation is being used for the context album. + *

+ * The scope of a context album is a string field, understood by whatever distribution mechanism is being used for the + * context album. The distribution mechanism uses the scope of the context album to decide to which executable entities + * a given context album is distributed. + *

+ * The writable flag on a context album defines whether users of a context album can write to the context album or just + * read objects from the context album. + *

+ * Validation checks that the album key and the context schema key are not null and that the scope field is not + * undefined and matches the regular expression {@link SCOPE_REGEXP}. + */ +@Entity +@Table(name = "AxContextAlbum") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexContextAlbum", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxContextAlbum", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "key", "scope", "isWritable", "itemSchema" }) + +public class AxContextAlbum extends AxConcept { + private static final String SCOPE_STRING = "scope"; + + private static final long serialVersionUID = 4290442590545820316L; + + /** + * The legal values for the scope of a context album is constrained by this regular expression. + */ + public static final String SCOPE_REGEXP = "[A-Za-z0-9\\-_]+"; + + /** The value of scope for a context album for which a scope has not been specified. */ + public static final String SCOPE_UNDEFINED = "UNDEFINED"; + + private static final int HASH_PRIME_0 = 1231; + private static final int HASH_PRIME_1 = 1237; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + @Column(name = SCOPE_STRING) + @XmlElement(name = SCOPE_STRING, required = true) + private String scope; + + @Column(name = "isWritable") + @XmlElement(name = "isWritable", required = true) + private boolean isWritable; + + // @formatter:off + @Embedded + @AttributeOverrides({ + @AttributeOverride(name = "name", column = @Column(name = "itemSchemaName")), + @AttributeOverride(name = "version", column = @Column(name = "itemSchemaVersion")) + }) + @Column(name = "itemSchema") + @XmlElement(name = "itemSchema", required = true) + private AxArtifactKey itemSchema; + // @formatter:on + + /** + * The default constructor creates a context album with a null artifact key. The scope of the context album is set + * as {@link SCOPE_UNDEFINED}, the album is writable, and the artifact key of the context schema is set to the null + * artifact key. + */ + public AxContextAlbum() { + this(new AxArtifactKey()); + scope = SCOPE_UNDEFINED; + isWritable = true; + itemSchema = AxArtifactKey.getNullKey(); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxContextAlbum(final AxContextAlbum copyConcept) { + super(copyConcept); + } + + /** + * The keyed constructor creates a context album with the specified artifact key. The scope of the context album is + * set as {@link SCOPE_UNDEFINED}, the album is writable, and the artifact key of the context schema is set to the + * null artifact key. + * + * @param key the key of the context album + */ + public AxContextAlbum(final AxArtifactKey key) { + this(key, SCOPE_UNDEFINED, true, AxArtifactKey.getNullKey()); + } + + /** + * Constructor that sets all the fields of the context album. + * + * @param key the key of the context album + * @param scope the scope field, must match the regular expression {@link SCOPE_REGEXP} + * @param isWritable specifies whether the context album will be writable or not + * @param itemSchema the artifact key of the context schema to use for this context album + */ + public AxContextAlbum(final AxArtifactKey key, final String scope, final boolean isWritable, + final AxArtifactKey itemSchema) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(scope, "scope may not be null"); + Assertions.argumentNotNull(itemSchema, "itemSchema may not be null"); + + this.key = key; + this.scope = Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); + this.isWritable = isWritable; + this.itemSchema = itemSchema; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + keyList.add(new AxKeyUse(itemSchema.getKey())); + + return keyList; + } + + /** + * Sets the key of the context album. + * + * @param key the context album key + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the scope of the context album. + * + * @return the context album scope + */ + public String getScope() { + return scope; + } + + /** + * Sets the scope of the context album. + * + * @param scope the context album scope + */ + public void setScope(final String scope) { + Assertions.argumentNotNull(scope, "scope may not be null"); + this.scope = Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); + } + + /** + * Sets whether the album is writable or not. + * + * @param writable the writable flag value + */ + public void setWritable(final boolean writable) { + this.isWritable = writable; + } + + /** + * Checks if the album is writable. + * + * @return true, if the album is writable + */ + public boolean isWritable() { + return isWritable; + } + + /** + * Gets the artifact key of the item schema of this context album. + * + * @return the item schema key + */ + public AxArtifactKey getItemSchema() { + return itemSchema; + } + + /** + * Sets the artifact key of the item schema of this context album. + * + * @param itemSchema the item schema key + */ + public void setItemSchema(final AxArtifactKey itemSchema) { + Assertions.argumentNotNull(itemSchema, "itemSchema key may not be null"); + this.itemSchema = itemSchema; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model. + * basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + result = key.validate(result); + + if (scope.replaceAll("\\s+$", "").length() == 0 || scope.equals(SCOPE_UNDEFINED)) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "scope is not defined")); + } + + try { + Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "scope invalid-" + e.getMessage())); + } + + if (itemSchema.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "itemSchema reference is a null key, an item schema must be specified")); + } + result = itemSchema.validate(result); + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + scope = Assertions.validateStringParameter(SCOPE_STRING, scope, SCOPE_REGEXP); + itemSchema.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",scope="); + builder.append(scope); + builder.append(",isWritable="); + builder.append(isWritable); + builder.append(",itemSchema="); + builder.append(itemSchema); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "targetObject may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxContextAlbum.class); + + final AxContextAlbum copy = ((AxContextAlbum) copyObject); + copy.setKey(new AxArtifactKey(key)); + copy.setScope(scope); + copy.setWritable(isWritable); + copy.setItemSchema(new AxArtifactKey(itemSchema)); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + scope.hashCode(); + result = prime * result + (isWritable ? HASH_PRIME_0 : HASH_PRIME_1); + result = prime * result + itemSchema.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxContextAlbum other = (AxContextAlbum) obj; + if (!key.equals(other.key)) { + return false; + } + if (!scope.equals(other.scope)) { + return false; + } + if (isWritable != other.isWritable) { + return (false); + } + return itemSchema.equals(other.itemSchema); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxContextAlbum other = (AxContextAlbum) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!scope.equals(other.scope)) { + return scope.compareTo(other.scope); + } + if (isWritable != other.isWritable) { + return (isWritable ? 1 : -1); + } + return itemSchema.compareTo(other.itemSchema); + } +} diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java new file mode 100644 index 000000000..f9d34cef6 --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextAlbums.java @@ -0,0 +1,423 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.Set; +import java.util.TreeMap; + +import javax.persistence.CascadeType; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter; +import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetterImpl; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is a context album container and holds a map of the context albums for an entire Apex model. All Apex + * models that use context albums must have an {@link AxContextAlbums} field. The {@link AxContextAlbums} class + * implements the helper methods of the {@link AxConceptGetter} interface to allow {@link AxContextAlbum} instances to + * be retrieved by calling methods directly on this class without referencing the contained map. + *

+ * Validation checks that the container key is not null. An observation is issued if no context albums are defined in + * the container. If context albums do exist, they are checked to ensure that keys and values are not null and that the + * map key matches the key in the map value for all album entries. Each context album entry is then validated + * individually. + */ +@Entity +@Table(name = "AxContextAlbums") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxContextAlbums", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "key", "albums" }) + +public final class AxContextAlbums extends AxConcept implements AxConceptGetter { + private static final long serialVersionUID = -4844259809024470975L; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + // @formatter:off + @OneToMany(cascade = CascadeType.ALL) + @JoinTable(joinColumns = {@JoinColumn(name = "contextName", referencedColumnName = "name"), + @JoinColumn(name = "contextVersion", referencedColumnName = "version")}) + @XmlElement(name = "albums", required = true) + private Map albums; + // @formatter:on + + /** + * The Default Constructor creates a {@link AxContextAlbums} object with a null artifact key and creates an empty + * context album map. + */ + public AxContextAlbums() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxContextAlbums(final AxContextAlbums copyConcept) { + super(copyConcept); + } + + /** + * The Key Constructor creates a {@link AxContextAlbums} object with the given artifact key and creates an empty + * context album map. + * + * @param key the key of the context album container + */ + public AxContextAlbums(final AxArtifactKey key) { + this(key, new TreeMap()); + } + + /** + * Constructor that creates the context album map with the given albums and key. + * + * @param key the key of the context album container + * @param albums the context albums to place in this context album container + */ + public AxContextAlbums(final AxArtifactKey key, final Map albums) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(albums, "albums may not be null"); + + this.key = key; + this.albums = new TreeMap<>(); + this.albums.putAll(albums); + } + + /** + * When a model is unmarshalled from disk or from the database, the context album map is returned as a raw hash map. + * This method is called by JAXB after unmarshaling and is used to convert the hash map to a {@link NavigableMap} so + * that it will work with the {@link AxConceptGetter} interface. + * + * @param u the unmarshaler that is unmarshaling the model + * @param parent the parent object of this object in the unmarshaler + */ + public void afterUnmarshal(final Unmarshaller u, final Object parent) { + // The map must be navigable to allow name and version searching, unmarshaling returns a + // hash map + final NavigableMap navigableAlbums = new TreeMap<>(); + navigableAlbums.putAll(albums); + albums = navigableAlbums; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + + for (final AxContextAlbum contextAlbum : albums.values()) { + keyList.addAll(contextAlbum.getKeys()); + } + + return keyList; + } + + /** + * Sets the key of the context album container. + * + * @param key the context album container key + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the map of context albums from the context album container. + * + * @return the context album map + */ + public Map getAlbumsMap() { + return albums; + } + + /** + * Sets the map of context albums from the context album container. + * + * @param albumsMap the map of context albums to place in the container + */ + public void setAlbumsMap(final Map albumsMap) { + Assertions.argumentNotNull(albumsMap, "albums may not be null"); + this.albums = new TreeMap<>(); + this.albums.putAll(albumsMap); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + for (final Entry contextAlbumEntry : albums.entrySet()) { + contextAlbumEntry.getKey().clean(); + contextAlbumEntry.getValue().clean(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",albums="); + builder.append(albums); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model. + * basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (albums.size() == 0) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.OBSERVATION, "albums are empty")); + } else { + for (final Entry contextAlbumEntry : albums.entrySet()) { + if (contextAlbumEntry.getKey().equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on context album entry " + contextAlbumEntry.getKey() + " may not be the null key")); + } else if (contextAlbumEntry.getValue() == null) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "value on context album entry " + contextAlbumEntry.getKey() + " may not be null")); + } else { + if (!contextAlbumEntry.getKey().equals(contextAlbumEntry.getValue().getKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on context album entry key " + contextAlbumEntry.getKey() + + " does not equal context album value key " + + contextAlbumEntry.getValue().getKey())); + } + + result = contextAlbumEntry.getValue().validate(result); + } + } + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxContextAlbums.class); + + final AxContextAlbums copy = ((AxContextAlbums) copyObject); + copy.setKey(key); + final Map newContextAlbum = new TreeMap<>(); + for (final Entry contextAlbumEntry : albums.entrySet()) { + newContextAlbum.put(new AxArtifactKey(contextAlbumEntry.getKey()), + new AxContextAlbum(contextAlbumEntry.getValue())); + } + copy.setAlbumsMap(newContextAlbum); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + albums.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxContextAlbums other = (AxContextAlbums) obj; + if (!key.equals(other.key)) { + return false; + } + return albums.equals(other.albums); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxContextAlbums other = (AxContextAlbums) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!albums.equals(other.albums)) { + return (albums.hashCode() - other.albums.hashCode()); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.model. + * basicmodel.concepts.AxArtifactKey) + */ + @Override + public AxContextAlbum get(final AxArtifactKey conceptKey) { + return new AxConceptGetterImpl<>((NavigableMap) albums).get(conceptKey); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String) + */ + @Override + public AxContextAlbum get(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) albums).get(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String, java.lang.String) + */ + @Override + public AxContextAlbum get(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) albums).get(conceptKeyName, + conceptKeyVersion); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) albums).getAll(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) albums).getAll(conceptKeyName, + conceptKeyVersion); + } +} diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java new file mode 100644 index 000000000..2aa6fc70a --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextModel.java @@ -0,0 +1,345 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * A container class for an Apex context model. This class is a container class that allows an Apex model to be + * constructed that just contains context and the key information for that context. The model contains schema + * definitions and the definitions of context albums that use those schemas. In the case where Apex context is being + * used without policy or independent of policy, an Apex context model is sufficient to get Apex context working. + *

+ * Validation runs {@link AxModel} validation on the model. In addition, the {@link AxContextSchemas} and + * {@link AxContextAlbums} validation is run on the context schemas and albums in the model. + */ +@Entity +@Table(name = "AxContextModel") + +@XmlRootElement(name = "apexContextModel", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxContextModel", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "schemas", "albums" }) + +public class AxContextModel extends AxModel { + private static final long serialVersionUID = 8800599637708309945L; + + // @formatter:off + @OneToOne(cascade = CascadeType.ALL) + @JoinColumns({ + @JoinColumn(name = "schemasName", referencedColumnName = "name"), + @JoinColumn(name = "schemasVersion", referencedColumnName = "version") + }) + @XmlElement(name = "schemas", required = true) + private AxContextSchemas schemas; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumns({ + @JoinColumn(name = "albumsName", referencedColumnName = "name"), + @JoinColumn(name = "albumsVersion", referencedColumnName = "version") + }) + @XmlElement(name = "albums", required = true) + private AxContextAlbums albums; + // @formatter:on + + /** + * The Default Constructor creates a {@link AxContextModel} object with a null artifact key and creates an empty + * context model. + */ + public AxContextModel() { + this(new AxArtifactKey()); + } + + /** + * The Key Constructor creates a {@link AxContextModel} object with the given artifact key and creates an empty + * context model. + * + * @param key the key of the context model + */ + public AxContextModel(final AxArtifactKey key) { + this(key, new AxContextSchemas(new AxArtifactKey(key.getName() + "_Schemas", key.getVersion())), + new AxContextAlbums(new AxArtifactKey(key.getName() + "_Albums", key.getVersion())), + new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion()))); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxContextModel(final AxContextModel copyConcept) { + super(copyConcept); + } + + /** + * Constructor that initiates a {@link AxContextModel} with schemas and keys for those schemas. An empty + * {@link AxContextAlbums} container is created. + * + * @param key the key of the context model + * @param schemas the context schema definitions + * @param keyInformation the key information for those context schemas + */ + public AxContextModel(final AxArtifactKey key, final AxContextSchemas schemas, + final AxKeyInformation keyInformation) { + this(key, schemas, new AxContextAlbums(new AxArtifactKey(key.getName() + "_Albums", key.getVersion())), + keyInformation); + } + + /** + * Constructor that initiates a {@link AxContextModel} with all its fields. + * + * @param key the key of the context model + * @param schemas the context schema definitions + * @param albums the context album container containing context albums + * @param keyInformation the key information for those context schemas + */ + public AxContextModel(final AxArtifactKey key, final AxContextSchemas schemas, final AxContextAlbums albums, + final AxKeyInformation keyInformation) { + super(key, keyInformation); + Assertions.argumentNotNull(schemas, "schemas may not be null"); + Assertions.argumentNotNull(albums, "albums may not be null"); + this.schemas = schemas; + this.albums = albums; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#register() + */ + @Override + public void register() { + super.register(); + ModelService.registerModel(AxContextSchemas.class, getSchemas()); + ModelService.registerModel(AxContextAlbums.class, getAlbums()); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#getKeys() + */ + @Override + public List getKeys() { + final List keyList = super.getKeys(); + + keyList.addAll(schemas.getKeys()); + keyList.addAll(albums.getKeys()); + + return keyList; + } + + /** + * Gets the context schemas from the model. + * + * @return the context schemas + */ + public AxContextSchemas getSchemas() { + return schemas; + } + + /** + * Sets the context schemas on the model. + * + * @param schemas the context schemas + */ + public void setSchemas(final AxContextSchemas schemas) { + Assertions.argumentNotNull(schemas, "schemas may not be null"); + this.schemas = schemas; + } + + /** + * Gets the context albums from the model. + * + * @return the context albums + */ + public AxContextAlbums getAlbums() { + return albums; + } + + /** + * Sets the context albums on the model. + * + * @param albums the context albums + */ + public void setAlbums(final AxContextAlbums albums) { + Assertions.argumentNotNull(albums, "albums may not be null"); + this.albums = albums; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#validate(org.onap.policy.apex.model. + * basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + result = super.validate(result); + result = schemas.validate(result); + return albums.validate(result); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#clean() + */ + @Override + public void clean() { + super.clean(); + schemas.clean(); + albums.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append(super.toString()); + builder.append(",schemas="); + builder.append(schemas); + builder.append(",albums="); + builder.append(albums); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxContextModel.class); + + final AxContextModel copy = ((AxContextModel) copyObject); + super.copyTo(target); + copy.setSchemas(new AxContextSchemas(schemas)); + copy.setAlbums(new AxContextAlbums(albums)); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + super.hashCode(); + result = prime * result + schemas.hashCode(); + result = prime * result + albums.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("comparison object may not be null"); + } + + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxContextModel other = (AxContextModel) obj; + if (!super.equals(other)) { + return false; + } + if (!schemas.equals(other.schemas)) { + return false; + } + return albums.equals(other.albums); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#compareTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public int compareTo(final AxConcept otherObj) { + Assertions.argumentNotNull(otherObj, "comparison object may not be null"); + + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxContextModel other = (AxContextModel) otherObj; + if (!super.equals(other)) { + return super.compareTo(other); + } + if (!schemas.equals(other.schemas)) { + return schemas.compareTo(other.schemas); + } + return albums.compareTo(other.albums); + } +} diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchema.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchema.java new file mode 100644 index 000000000..3abcebee9 --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchema.java @@ -0,0 +1,379 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import java.util.List; + +import javax.persistence.Column; +import javax.persistence.Convert; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class holds a data schema definition in Apex. A data schema describes the structure of a single atom of data + * handled by Apex. This atom of data can be a primitive type such as an integer or a string, or it can be a more + * complex data type such as a Java object or an object described using a data definition language such as Avro. The + * schema flavour defines the type of schema being defined and the schema itself defines the schema. The schema flavour + * is used by Apex to look up and load a plugin class that understands and interprets the schema definition and can + * create instances of classes for the schema. + *

+ * An {@link AxContextSchema} is used to define each parameter in Apex events, the messages that enter, exit, and are + * passed internally in Apex. In addition, an Apex {@link AxContextAlbum} instances hold a map of + * {@link AxContextSchema} instances to represent the context being managed as an {@link AxContextAlbum}. For example, + * the state of all cells in a mobile network might be represented as an {@link AxContextAlbum} with its + * {@link AxContextSchema} being defined as @code cell} objects. + *

+ * Validation checks that the schema key is not null. It also checks that the schema flavour is defined and matches the + * regular expression {@link SCHEMA_FLAVOUR_REGEXP}. Finally, validation checks that the defined schema is not a blank + * or empty string. + */ +@Entity +@Table(name = "AxContextSchema") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexContextSchema", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxContextSchema", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "key", "schemaFlavour", "schemaDefinition" }) + +public class AxContextSchema extends AxConcept { + private static final String SCHEMA_FLAVOUR = "schemaFlavour"; + private static final String WHITESPACE_REGEXP = "\\s+$"; + + private static final long serialVersionUID = -6443016863162692288L; + + /** Regular expression that constrains what values a schema flavour can have. */ + public static final String SCHEMA_FLAVOUR_REGEXP = "[A-Za-z0-9\\-_]+"; + + /** An undefined schema flavour has this value. */ + public static final String SCHEMA_FLAVOUR_UNDEFINED = "UNDEFINED"; + + /** The maximum permissible size of a schema definition. */ + public static final int MAX_SCHEMA_SIZE = 32672; // The maximum size supported by Apache Derby + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + @Column(name = SCHEMA_FLAVOUR) + @XmlElement(required = true) + private String schemaFlavour; + + @Column(name = "schemaDefinition", length = MAX_SCHEMA_SIZE) + @Convert(converter = CDATAConditioner.class) + @XmlJavaTypeAdapter(value = CDATAConditioner.class) + @XmlElement(name = "schemaDefinition", required = true) + private String schemaDefinition; + + /** + * The default constructor creates a context schema with a null artifact key. The flavour of the context album is + * set as {@link SCHEMA_FLAVOUR_UNDEFINED} and the schema itself is defined as an empty string. + */ + public AxContextSchema() { + this(new AxArtifactKey()); + schemaFlavour = SCHEMA_FLAVOUR_UNDEFINED; + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxContextSchema(final AxContextSchema copyConcept) { + super(copyConcept); + } + + /** + * The key constructor creates a context schema with the given artifact key. The flavour of the context album is set + * as {@link SCHEMA_FLAVOUR_UNDEFINED} and the schema itself is defined as an empty string. + * + * @param key the key + */ + public AxContextSchema(final AxArtifactKey key) { + this(key, SCHEMA_FLAVOUR_UNDEFINED, ""); + } + + /** + * This Constructor creates a context schema with all of its fields defined. + * + * @param key the key + * @param schemaFlavour the schema flavour + * @param schemaDefinition the schema definition + */ + public AxContextSchema(final AxArtifactKey key, final String schemaFlavour, final String schemaDefinition) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(schemaFlavour, "schemaFlavour may not be null"); + Assertions.argumentNotNull(schemaDefinition, "schemaDefinition may not be null"); + + this.key = key; + this.schemaFlavour = Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); + this.schemaDefinition = schemaDefinition.replaceAll(WHITESPACE_REGEXP, ""); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + return key.getKeys(); + } + + /** + * Sets the key of the context schema. + * + * @param key the key of the context schema + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the schema flavour, which defines the schema definition type being used. + * + * @return the schema flavour + */ + public String getSchemaFlavour() { + return schemaFlavour; + } + + /** + * Sets the schema flavour, which defines the type of schema definition being used. + * + * @param schemaFlavour the schema flavour + */ + public void setSchemaFlavour(final String schemaFlavour) { + this.schemaFlavour = Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); + } + + /** + * Gets the schema, which defines the structure of this data schema atom. + * + * @return the schema definition + */ + public String getSchema() { + return schemaDefinition; + } + + /** + * Sets the schema, which defines the structure of this data schema atom. + * + * @param schema the schema definition + */ + public void setSchema(final String schema) { + Assertions.argumentNotNull(schema, "schema may not be null"); + this.schemaDefinition = schema.replaceAll(WHITESPACE_REGEXP, ""); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model. + * basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (schemaFlavour.replaceAll(WHITESPACE_REGEXP, "").length() == 0 + || schemaFlavour.equals(SCHEMA_FLAVOUR_UNDEFINED)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "schema flavour is not defined")); + } + + try { + Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); + } catch (final IllegalArgumentException e) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "schema flavour invalid-" + e.getMessage())); + } + + if (schemaDefinition.replaceAll(WHITESPACE_REGEXP, "").length() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "no schemaDefinition specified, schemaDefinition may not be blank")); + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + schemaFlavour = Assertions.validateStringParameter(SCHEMA_FLAVOUR, schemaFlavour, SCHEMA_FLAVOUR_REGEXP); + schemaDefinition = schemaDefinition.replaceAll(WHITESPACE_REGEXP, ""); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",schemaFlavour="); + builder.append(schemaFlavour); + builder.append(",schemaDefinition="); + builder.append(schemaDefinition); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxContextSchema.class); + + final AxContextSchema copy = ((AxContextSchema) copyObject); + copy.setKey(new AxArtifactKey(key)); + copy.setSchemaFlavour(schemaFlavour); + copy.setSchema(schemaDefinition); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + schemaFlavour.hashCode(); + result = prime * result + schemaDefinition.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxContextSchema other = (AxContextSchema) obj; + + if (!key.equals(other.key)) { + return false; + } + if (!schemaFlavour.equals(other.schemaFlavour)) { + return false; + } + final String thisSchema = CDATAConditioner.clean(schemaDefinition).replaceAll("\n", ""); + final String otherSchema = CDATAConditioner.clean(other.schemaDefinition).replaceAll("\n", ""); + return thisSchema.equals(otherSchema); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxContextSchema other = (AxContextSchema) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!schemaFlavour.equals(other.schemaFlavour)) { + return schemaFlavour.compareTo(other.schemaFlavour); + } + final String thisSchema = CDATAConditioner.clean(schemaDefinition).replaceAll("\n", ""); + final String otherSchema = CDATAConditioner.clean(other.schemaDefinition).replaceAll("\n", ""); + return thisSchema.compareTo(otherSchema); + } +} diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchemas.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchemas.java new file mode 100644 index 000000000..df94a87a9 --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/AxContextSchemas.java @@ -0,0 +1,419 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.Set; +import java.util.TreeMap; + +import javax.persistence.CascadeType; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter; +import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetterImpl; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is a context schema container and holds a map of the context schemas for an entire Apex model. All Apex + * models that use context schemas must have an {@link AxContextSchemas} field. The {@link AxContextSchemas} class + * implements the helper methods of the {@link AxConceptGetter} interface to allow {@link AxContextSchema} instances to + * be retrieved by calling methods directly on this class without referencing the contained map. + *

+ * Validation checks that the container key is not null. An error is issued if no context schemas are defined in the + * container. Each context schema entry is checked to ensure that its key and value are not null and that the key + * matches the key in the map value. Each context schema entry is then validated individually. + */ +@Entity +@Table(name = "AxContextSchemas") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxContextSchemas", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "key", "schemas" }) + +public class AxContextSchemas extends AxConcept implements AxConceptGetter { + private static final long serialVersionUID = -3203734282886453582L; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + // @formatter:off + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable( + joinColumns = {@JoinColumn(name = "contextSchemasName", referencedColumnName = "name"), + @JoinColumn(name = "contextSchemasVersion", referencedColumnName = "version")}, + inverseJoinColumns = {@JoinColumn(name = "contextSchemaName", referencedColumnName = "name"), + @JoinColumn(name = "contextSchemaVersion", referencedColumnName = "version")}) + @XmlElement(name = "schemas", required = true) + private Map schemas; + // @formatter:on + + /** + * The Default Constructor creates a {@link AxContextSchemas} object with a null artifact key and creates an empty + * context schemas map. + */ + public AxContextSchemas() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxContextSchemas(final AxContextSchemas copyConcept) { + super(copyConcept); + } + + /** + * The Key Constructor creates a {@link AxContextSchemas} object with the given artifact key and creates an empty + * context schemas map. + * + * @param key the key of the context album container + */ + public AxContextSchemas(final AxArtifactKey key) { + this(key, new TreeMap()); + } + + /** + * This Constructor creates a {@link AxContextSchemas} object with all its fields defined. + * + * @param key the key of the context schema container + * @param schemas a map of the schemas to insert in the context schema container + */ + public AxContextSchemas(final AxArtifactKey key, final Map schemas) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(schemas, "schemas may not be null"); + + this.key = key; + this.schemas = new TreeMap<>(); + this.schemas.putAll(schemas); + } + + /** + * When a model is unmarshalled from disk or from the database, the context schema map is returned as a raw hash + * map. This method is called by JAXB after unmarshaling and is used to convert the hash map to a + * {@link NavigableMap} so that it will work with the {@link AxConceptGetter} interface. + * + * @param u the unmarshaler that is unmarshaling the model + * @param parent the parent object of this object in the unmarshaler + */ + public void afterUnmarshal(final Unmarshaller u, final Object parent) { + // The map must be navigable to allow name and version searching, unmarshaling returns a + // hash map + final NavigableMap navigableContextSchemas = new TreeMap<>(); + navigableContextSchemas.putAll(schemas); + schemas = navigableContextSchemas; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + keyList.addAll(schemas.keySet()); + + return keyList; + } + + /** + * Sets the key of the context schema container. + * + * @param key the key of the container + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the map of context schemas in this container. + * + * @return the map of schemas + */ + public Map getSchemasMap() { + return schemas; + } + + /** + * Sets the map of context schemas in this container. + * + * @param schemasMap the map of schemas + */ + public void setSchemasMap(final Map schemasMap) { + Assertions.argumentNotNull(schemasMap, "schemasMap may not be null"); + + this.schemas = new TreeMap<>(); + this.schemas.putAll(schemasMap); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model. + * basicmodel.concepts.AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (schemas.size() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "contextSchemas may not be empty")); + } else { + for (final Entry contextSchemaEntry : schemas.entrySet()) { + if (contextSchemaEntry.getKey().equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on schemas entry " + contextSchemaEntry.getKey() + " may not be the null key")); + } else if (contextSchemaEntry.getValue() == null) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "value on schemas entry " + contextSchemaEntry.getKey() + " may not be null")); + } else { + if (!contextSchemaEntry.getKey().equals(contextSchemaEntry.getValue().getKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), + ValidationResult.INVALID, "key on schemas entry " + contextSchemaEntry.getKey() + + " does not equal entry key " + contextSchemaEntry.getValue().getKey())); + } + + result = contextSchemaEntry.getValue().validate(result); + } + } + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + for (final Entry contextSchemaEntry : schemas.entrySet()) { + contextSchemaEntry.getKey().clean(); + contextSchemaEntry.getValue().clean(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",schemas="); + builder.append(schemas); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model. + * basicmodel.concepts.AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept target) { + Assertions.argumentNotNull(target, "target may not be null"); + + final Object copyObject = target; + Assertions.instanceOf(copyObject, AxContextSchemas.class); + + final AxContextSchemas copy = ((AxContextSchemas) copyObject); + copy.setKey(new AxArtifactKey(key)); + + final Map newcontextSchemas = new TreeMap<>(); + for (final Entry contextSchemasEntry : schemas.entrySet()) { + newcontextSchemas.put(new AxArtifactKey(contextSchemasEntry.getKey()), + new AxContextSchema(contextSchemasEntry.getValue())); + } + copy.setSchemasMap(newcontextSchemas); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + schemas.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxContextSchemas other = (AxContextSchemas) obj; + if (!key.equals(other.key)) { + return false; + } + return schemas.equals(other.schemas); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxContextSchemas other = (AxContextSchemas) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!schemas.equals(other.schemas)) { + return (schemas.hashCode() - other.schemas.hashCode()); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.core. + * basicmodel.concepts.AxArtifactKey) + */ + @Override + public AxContextSchema get(final AxArtifactKey conceptKey) { + return new AxConceptGetterImpl<>((NavigableMap) schemas).get(conceptKey); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang.String) + */ + @Override + public AxContextSchema get(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) schemas).get(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#get(java.lang.String, java.lang.String) + */ + @Override + public AxContextSchema get(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) schemas).get(conceptKeyName, + conceptKeyVersion); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) schemas).getAll(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.core.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) schemas).getAll(conceptKeyName, + conceptKeyVersion); + } +} diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/package-info.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/package-info.java new file mode 100644 index 000000000..a7aa3a5ad --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/concepts/package-info.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains the concepts required to manage context in APEX. It defines the main APEX concepts of Context Schemas and + * Context Albums. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +package org.onap.policy.apex.model.contextmodel.concepts; diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/ContextComparer.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/ContextComparer.java new file mode 100644 index 000000000..7a5ebfd22 --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/ContextComparer.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.utilities.comparison.KeyedMapComparer; +import org.onap.policy.apex.model.utilities.comparison.KeyedMapDifference; + +/** + * This class compares the context in two AxContext objects and returns the differences. The + * differences are returned in a {@link KeyedMapDifference} object that contains the left, equal, + * and right context schemas or albums. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class ContextComparer { + + /** + * Compare two {@link AxContextAlbums} objects, comparing their context albums one after + * another. + * + * @param left the left context + * @param right the right context + * @return the difference + */ + public KeyedMapDifference compare(final AxContextAlbums left, + final AxContextAlbums right) { + // Find the difference between the AxContext objects + return new KeyedMapComparer().compareMaps(left.getAlbumsMap(), + right.getAlbumsMap()); + } + + /** + * Compare two {@link AxContextSchema} objects, comparing their context schemas one after + * another. + * + * @param left the left context + * @param right the right context + * @return the difference + */ + public KeyedMapDifference compare(final AxContextSchemas left, + final AxContextSchemas right) { + // Find the difference between the AxContext objects + return new KeyedMapComparer().compareMaps(left.getSchemasMap(), + right.getSchemasMap()); + } + +} diff --git a/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/package-info.java b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/package-info.java new file mode 100644 index 000000000..ec1fa893f --- /dev/null +++ b/model/context-model/src/main/java/org/onap/policy/apex/model/contextmodel/handling/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Provides some helper classes for handling context, including a utility class for comparing two + * context objects. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +package org.onap.policy.apex.model.contextmodel.handling; diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextAlbums.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextAlbums.java deleted file mode 100644 index 476cda9a3..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextAlbums.java +++ /dev/null @@ -1,210 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbum; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbums; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextAlbums { - - @Test - public void testContextAlbums() { - assertNotNull(new AxContextAlbum()); - assertNotNull(new AxContextAlbum(new AxArtifactKey())); - assertNotNull(new AxContextAlbum(new AxArtifactKey(), "AlbumScope", false, new AxArtifactKey())); - - final AxArtifactKey albumKey = new AxArtifactKey("AlbumName", "0.0.1"); - final AxArtifactKey albumSchemaKey = new AxArtifactKey("AlbumSchemaName", "0.0.1"); - - final AxContextAlbum album = new AxContextAlbum(albumKey, "AlbumScope", false, albumSchemaKey); - assertNotNull(album); - - final AxArtifactKey newKey = new AxArtifactKey("NewAlbumName", "0.0.1"); - album.setKey(newKey); - assertEquals("NewAlbumName:0.0.1", album.getKey().getID()); - assertEquals("NewAlbumName:0.0.1", album.getKeys().get(0).getID()); - album.setKey(albumKey); - - try { - album.setScope(""); - fail("test should throw an exception here"); - } catch (final Exception e) { - assertEquals("parameter \"scope\": value \"\", does not match regular expression \"[A-Za-z0-9\\-_]+\"", - e.getMessage()); - } - - album.setScope("NewAlbumScope"); - assertEquals("NewAlbumScope", album.getScope()); - - assertEquals(false, album.isWritable()); - album.setWritable(true); - assertEquals(true, album.isWritable()); - - final AxArtifactKey newSchemaKey = new AxArtifactKey("NewAlbumSchemaName", "0.0.1"); - album.setItemSchema(newSchemaKey); - assertEquals("NewAlbumSchemaName:0.0.1", album.getItemSchema().getID()); - album.setItemSchema(albumSchemaKey); - - AxValidationResult result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - album.setKey(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - album.setKey(newKey); - result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - album.setScope("UNDEFINED"); - result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - album.setScope("NewAlbumScope"); - result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - album.setItemSchema(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - album.setItemSchema(albumSchemaKey); - result = new AxValidationResult(); - result = album.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - album.clean(); - - final AxContextAlbum clonedAlbum = new AxContextAlbum(album); - assertEquals( - "AxContextAlbum:(key=AxArtifactKey:(name=NewAlbumName,version=0.0.1),scope=NewAlbumScope,isWritable=true,itemSchema=AxArtifactKey:(name=AlbumSchemaName,version=0.0.1))", - clonedAlbum.toString()); - - assertFalse(album.hashCode() == 0); - - assertTrue(album.equals(album)); - assertTrue(album.equals(clonedAlbum)); - assertFalse(album.equals(null)); - assertFalse(album.equals("Hello")); - assertFalse(album.equals(new AxContextAlbum(new AxArtifactKey(), "Scope", false, AxArtifactKey.getNullKey()))); - assertFalse(album.equals(new AxContextAlbum(newKey, "Scope", false, AxArtifactKey.getNullKey()))); - assertFalse(album.equals(new AxContextAlbum(newKey, "NewAlbumScope", false, AxArtifactKey.getNullKey()))); - assertFalse(album.equals(new AxContextAlbum(newKey, "NewAlbumScope", true, AxArtifactKey.getNullKey()))); - assertTrue(album.equals(new AxContextAlbum(newKey, "NewAlbumScope", true, albumSchemaKey))); - - assertEquals(0, album.compareTo(album)); - assertEquals(0, album.compareTo(clonedAlbum)); - assertNotEquals(0, album.compareTo(null)); - assertNotEquals(0, album.compareTo(new AxArtifactKey())); - assertNotEquals(0, - album.compareTo(new AxContextAlbum(new AxArtifactKey(), "Scope", false, AxArtifactKey.getNullKey()))); - assertNotEquals(0, album.compareTo(new AxContextAlbum(newKey, "Scope", false, AxArtifactKey.getNullKey()))); - assertNotEquals(0, - album.compareTo(new AxContextAlbum(newKey, "NewAlbumScope", false, AxArtifactKey.getNullKey()))); - assertNotEquals(0, - album.compareTo(new AxContextAlbum(newKey, "NewAlbumScope", true, AxArtifactKey.getNullKey()))); - assertEquals(0, album.compareTo(new AxContextAlbum(newKey, "NewAlbumScope", true, albumSchemaKey))); - - final AxContextAlbums albums = new AxContextAlbums(); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - // Observation, no albums in album map - albums.setKey(new AxArtifactKey("AlbumsKey", "0.0.1")); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.OBSERVATION, result.getValidationResult()); - - albums.getAlbumsMap().put(newKey, album); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - albums.getAlbumsMap().put(AxArtifactKey.getNullKey(), null); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - albums.getAlbumsMap().remove(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - albums.getAlbumsMap().put(new AxArtifactKey("NullValueKey", "0.0.1"), null); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - albums.getAlbumsMap().remove(new AxArtifactKey("NullValueKey", "0.0.1")); - result = new AxValidationResult(); - result = albums.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - albums.clean(); - - final AxContextAlbums clonedAlbums = new AxContextAlbums(albums); - assertTrue(clonedAlbums.toString() - .startsWith("AxContextAlbums:(AxContextAlbums:(key=AxArtifactKey:(name=AlbumsKey,version=0.0.1)")); - - assertFalse(albums.hashCode() == 0); - - assertTrue(albums.equals(albums)); - assertTrue(albums.equals(clonedAlbums)); - assertFalse(albums.equals(null)); - assertFalse(albums.equals("Hello")); - assertFalse(albums.equals(new AxContextAlbums(new AxArtifactKey()))); - - assertEquals(0, albums.compareTo(albums)); - assertEquals(0, albums.compareTo(clonedAlbums)); - assertNotEquals(0, albums.compareTo(null)); - assertNotEquals(0, albums.compareTo(new AxArtifactKey())); - assertNotEquals(0, albums.compareTo(new AxContextAlbums(new AxArtifactKey()))); - - clonedAlbums.get(newKey).setScope("YetAnotherScope"); - assertNotEquals(0, albums.compareTo(clonedAlbums)); - - assertEquals("NewAlbumName", albums.get("NewAlbumName").getKey().getName()); - assertEquals("NewAlbumName", albums.get("NewAlbumName", "0.0.1").getKey().getName()); - assertEquals(1, albums.getAll("NewAlbumName", "0.0.1").size()); - assertEquals(0, albums.getAll("NonExistantAlbumName").size()); - } -} diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextModel.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextModel.java deleted file mode 100644 index cab40f316..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextModel.java +++ /dev/null @@ -1,82 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbums; -import org.onap.apex.model.contextmodel.concepts.AxContextModel; -import org.onap.apex.model.contextmodel.concepts.AxContextSchemas; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextModel { - - @Test - public void test() { - assertNotNull(new AxContextModel()); - assertNotNull(new AxContextModel(new AxArtifactKey())); - assertNotNull(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxKeyInformation())); - assertNotNull(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation())); - - final AxArtifactKey modelKey = new AxArtifactKey("ModelKey", "0.0.1"); - final AxArtifactKey schemasKey = new AxArtifactKey("SchemasKey", "0.0.1"); - final AxArtifactKey albumsKey = new AxArtifactKey("SchemasKey", "0.0.1"); - final AxArtifactKey keyInfoKey = new AxArtifactKey("SchemasKey", "0.0.1"); - final AxContextModel model = new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(albumsKey), new AxKeyInformation(keyInfoKey)); - model.register(); - - model.clean(); - assertNotNull(model); - assertEquals("AxContextModel:(AxContextModel:(key=AxArtifactKey:", model.toString().substring(0, 50)); - - final AxContextModel clonedModel = new AxContextModel(model); - - assertFalse(model.hashCode() == 0); - - assertTrue(model.equals(model)); - assertTrue(model.equals(clonedModel)); - assertFalse(model.equals("Hello")); - assertFalse(model.equals(new AxContextModel(new AxArtifactKey()))); - assertFalse(model.equals(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); - assertFalse(model.equals(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); - assertFalse(model.equals(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); - assertFalse(model.equals(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); - assertTrue(model.equals(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(albumsKey), new AxKeyInformation(keyInfoKey)))); - - assertEquals(0, model.compareTo(model)); - assertEquals(0, model.compareTo(clonedModel)); - assertNotEquals(0, model.compareTo(new AxArtifactKey())); - assertNotEquals(0, model.compareTo(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); - assertNotEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); - assertNotEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); - assertNotEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); - assertEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(albumsKey), new AxKeyInformation(keyInfoKey)))); - } -} diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextSchemas.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextSchemas.java deleted file mode 100644 index 1e81c5a95..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/concepts/TestContextSchemas.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.concepts; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; -import org.onap.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.apex.model.contextmodel.concepts.AxContextSchemas; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextSchemas { - - @Test - public void testContextSchemas() { - assertNotNull(new AxContextSchema()); - assertNotNull(new AxContextSchema(new AxArtifactKey(), "SchemaFlavour", "SchemaDefinition")); - - final AxContextSchema schema = - new AxContextSchema(new AxArtifactKey("SchemaName", "0.0.1"), "SchemaFlavour", "SchemaDefinition"); - assertNotNull(schema); - - final AxArtifactKey newKey = new AxArtifactKey("NewSchemaName", "0.0.1"); - schema.setKey(newKey); - assertEquals("NewSchemaName:0.0.1", schema.getKey().getID()); - assertEquals("NewSchemaName:0.0.1", schema.getKeys().get(0).getID()); - - try { - schema.setSchemaFlavour(""); - fail("test should throw an exception here"); - } catch (final Exception e) { - assertEquals( - "parameter \"schemaFlavour\": value \"\", does not match regular expression \"[A-Za-z0-9\\-_]+\"", - e.getMessage()); - } - - schema.setSchemaFlavour("NewSchemaFlavour"); - assertEquals("NewSchemaFlavour", schema.getSchemaFlavour()); - - schema.setSchema("NewSchemaDefinition"); - assertEquals("NewSchemaDefinition", schema.getSchema()); - - AxValidationResult result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schema.setKey(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - schema.setKey(newKey); - result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schema.setSchemaFlavour("UNDEFINED"); - result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - schema.setSchemaFlavour("NewSchemaFlavour"); - result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schema.setSchema(""); - result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - schema.setSchema("NewSchemaDefinition"); - result = new AxValidationResult(); - result = schema.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schema.clean(); - - final AxContextSchema clonedSchema = new AxContextSchema(schema); - assertEquals( - "AxContextSchema:(key=AxArtifactKey:(name=NewSchemaName,version=0.0.1),schemaFlavour=NewSchemaFlavour,schemaDefinition=NewSchemaDefinition)", - clonedSchema.toString()); - - assertFalse(schema.hashCode() == 0); - - assertTrue(schema.equals(schema)); - assertTrue(schema.equals(clonedSchema)); - assertFalse(schema.equals(null)); - assertFalse(schema.equals("Hello")); - assertFalse(schema.equals(new AxContextSchema(new AxArtifactKey(), "Flavour", "Def"))); - assertFalse(schema.equals(new AxContextSchema(newKey, "Flavour", "Def"))); - assertFalse(schema.equals(new AxContextSchema(newKey, "NewSchemaFlavour", "Def"))); - assertTrue(schema.equals(new AxContextSchema(newKey, "NewSchemaFlavour", "NewSchemaDefinition"))); - - assertEquals(0, schema.compareTo(schema)); - assertEquals(0, schema.compareTo(clonedSchema)); - assertNotEquals(0, schema.compareTo(null)); - assertNotEquals(0, schema.compareTo(new AxArtifactKey())); - assertNotEquals(0, schema.compareTo(new AxContextSchema(new AxArtifactKey(), "Flavour", "Def"))); - assertNotEquals(0, schema.compareTo(new AxContextSchema(newKey, "Flavour", "Def"))); - assertNotEquals(0, schema.compareTo(new AxContextSchema(newKey, "NewSchemaFlavour", "Def"))); - assertEquals(0, schema.compareTo(new AxContextSchema(newKey, "NewSchemaFlavour", "NewSchemaDefinition"))); - - final AxContextSchemas schemas = new AxContextSchemas(); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - // Still invalid, no schemas in schema map - schemas.setKey(new AxArtifactKey("SchemasKey", "0.0.1")); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - schemas.getSchemasMap().put(newKey, schema); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schemas.getSchemasMap().put(AxArtifactKey.getNullKey(), null); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - schemas.getSchemasMap().remove(AxArtifactKey.getNullKey()); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schemas.getSchemasMap().put(new AxArtifactKey("NullValueKey", "0.0.1"), null); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.INVALID, result.getValidationResult()); - - schemas.getSchemasMap().remove(new AxArtifactKey("NullValueKey", "0.0.1")); - result = new AxValidationResult(); - result = schemas.validate(result); - assertEquals(ValidationResult.VALID, result.getValidationResult()); - - schemas.clean(); - - final AxContextSchemas clonedSchemas = new AxContextSchemas(schemas); - assertTrue(clonedSchemas.toString() - .startsWith("AxContextSchemas:(key=AxArtifactKey:(name=SchemasKey,version=0.0.1),")); - - assertFalse(schemas.hashCode() == 0); - - assertTrue(schemas.equals(schemas)); - assertTrue(schemas.equals(clonedSchemas)); - assertFalse(schemas.equals(null)); - assertFalse(schemas.equals("Hello")); - assertFalse(schemas.equals(new AxContextSchemas(new AxArtifactKey()))); - - assertEquals(0, schemas.compareTo(schemas)); - assertEquals(0, schemas.compareTo(clonedSchemas)); - assertNotEquals(0, schemas.compareTo(null)); - assertNotEquals(0, schemas.compareTo(new AxArtifactKey())); - assertNotEquals(0, schemas.compareTo(new AxContextSchemas(new AxArtifactKey()))); - - clonedSchemas.get(newKey).setSchemaFlavour("YetAnotherFlavour"); - assertNotEquals(0, schemas.compareTo(clonedSchemas)); - - assertEquals("NewSchemaName", schemas.get("NewSchemaName").getKey().getName()); - assertEquals("NewSchemaName", schemas.get("NewSchemaName", "0.0.1").getKey().getName()); - assertEquals(1, schemas.getAll("NewSchemaName", "0.0.1").size()); - assertEquals(0, schemas.getAll("NonExistantSchemaName").size()); - } -} diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModel.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModel.java deleted file mode 100644 index 0723a6827..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModel.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.handling; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.apex.model.basicmodel.dao.DAOParameters; -import org.onap.apex.model.basicmodel.test.TestApexModel; -import org.onap.apex.model.contextmodel.concepts.AxContextModel; - -public class TestApexContextModel { - private Connection connection; - TestApexModel testApexModel; - - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel(AxContextModel.class, new TestApexContextModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelValid() throws Exception { - final AxValidationResult result = testApexModel.testApexModelValid(); - assertTrue(result.toString().equals(VALID_MODEL_STRING)); - } - - @Test - public void testApexModelVaidateObservation() throws Exception { - final AxValidationResult result = testApexModel.testApexModelVaidateObservation(); - assertTrue(result.toString().equals(OBSERVATION_MODEL_STRING)); - } - - @Test - public void testApexModelVaidateWarning() throws Exception { - final AxValidationResult result = testApexModel.testApexModelVaidateWarning(); - assertTrue(result.toString().equals(WARNING_MODEL_STRING)); - } - - @Test - public void testModelVaidateInvalidModel() throws Exception { - final AxValidationResult result = testApexModel.testApexModelVaidateInvalidModel(); - assertTrue(result.toString().equals(INVALID_MODEL_STRING)); - } - - @Test - public void testModelVaidateMalstructured() throws Exception { - final AxValidationResult result = testApexModel.testApexModelVaidateMalstructured(); - assertTrue(result.toString().equals(INVALID_MODEL_MALSTRUCTURED_STRING)); - } - - @Test - public void testModelWriteReadXML() throws Exception { - testApexModel.testApexModelWriteReadXML(); - } - - @Test - public void testModelWriteReadJSON() throws Exception { - testApexModel.testApexModelWriteReadJSON(); - } - - @Test - public void testModelWriteReadJPA() throws Exception { - final DAOParameters daoParameters = new DAOParameters(); - daoParameters.setPluginClass("org.onap.apex.model.basicmodel.dao.impl.DefaultApexDao"); - daoParameters.setPersistenceUnit("DAOTest"); - - testApexModel.testApexModelWriteReadJPA(daoParameters); - } - - private static final String VALID_MODEL_STRING = "***validation of model successful***"; - - private static final String OBSERVATION_MODEL_STRING = - "\n" + "***observations noted during validation of model***\n" - + "AxArtifactKey:(name=contextAlbum1,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInfo:OBSERVATION:description is blank\n" - + "********************************"; - - private static final String WARNING_MODEL_STRING = "\n" + "***warnings issued during validation of model***\n" - + "AxArtifactKey:(name=contextAlbum1,version=0.0.1):org.onap.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" - + "********************************"; - - private static final String INVALID_MODEL_STRING = "\n" + "***validation of model failed***\n" - + "AxArtifactKey:(name=StringType,version=0.0.1):org.onap.apex.model.contextmodel.concepts.AxContextSchema:INVALID:no schemaDefinition specified, schemaDefinition may not be blank\n" - + "AxArtifactKey:(name=contextAlbum0,version=0.0.1):org.onap.apex.model.contextmodel.concepts.AxContextAlbum:INVALID:scope is not defined\n" - + "********************************"; - - private static final String INVALID_MODEL_MALSTRUCTURED_STRING = "\n" + "***validation of model failed***\n" - + "AxArtifactKey:(name=ContextModel,version=0.0.1):org.onap.apex.model.contextmodel.concepts.AxContextModel:INVALID:key information not found for key AxArtifactKey:(name=contextAlbum1,version=0.0.2)\n" - + "AxArtifactKey:(name=contextAlbum1,version=0.0.1):org.onap.apex.model.contextmodel.concepts.AxContextModel:WARNING:key not found for key information entry\n" - + "AxArtifactKey:(name=ContextSchemas,version=0.0.1):org.onap.apex.model.contextmodel.concepts.AxContextSchemas:INVALID:key on schemas entry AxArtifactKey:(name=MapType,version=0.0.1) does not equal entry key AxArtifactKey:(name=MapType,version=0.0.2)\n" - + "AxArtifactKey:(name=contextAlbums,version=0.0.1):org.onap.apex.model.contextmodel.concepts.AxContextAlbums:INVALID:key on context album entry key AxArtifactKey:(name=contextAlbum1,version=0.0.1) does not equal context album value key AxArtifactKey:(name=contextAlbum1,version=0.0.2)\n" - + "********************************"; - -} diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModelCreator.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModelCreator.java deleted file mode 100644 index b53d8d04d..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestApexContextModelCreator.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.handling; - -import java.util.UUID; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.basicmodel.concepts.AxKeyInfo; -import org.onap.apex.model.basicmodel.concepts.AxKeyInformation; -import org.onap.apex.model.basicmodel.test.TestApexModelCreator; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbum; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbums; -import org.onap.apex.model.contextmodel.concepts.AxContextModel; -import org.onap.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.apex.model.contextmodel.concepts.AxContextSchemas; - -public class TestApexContextModelCreator implements TestApexModelCreator { - - @Override - public AxContextModel getModel() { - final AxContextSchema schema0 = new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", "com.ericsson.apex.concept.TestContextItem000"); - final AxContextSchema schema1 = new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", "com.ericsson.apex.concept.TestContextItem00A"); - - final AxContextSchemas contextSchemas = new AxContextSchemas(new AxArtifactKey("ContextSchemas", "0.0.1")); - contextSchemas.getSchemasMap().put(schema0.getKey(), schema0); - contextSchemas.getSchemasMap().put(schema1.getKey(), schema1); - - final AxContextAlbum contextAlbum0 = new AxContextAlbum(new AxArtifactKey("contextAlbum0", "0.0.1"), "APPLICATION", true, schema0.getKey()); - final AxContextAlbum contextAlbum1 = new AxContextAlbum(new AxArtifactKey("contextAlbum1", "0.0.1"), "GLOBAL" , false, schema1.getKey()); - - final AxContextAlbums axContext = new AxContextAlbums(new AxArtifactKey("contextAlbums", "0.0.1")); - axContext.getAlbumsMap().put(contextAlbum0.getKey(), contextAlbum0); - axContext.getAlbumsMap().put(contextAlbum1.getKey(), contextAlbum1); - - final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); - final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1"), contextSchemas, axContext, keyInformation); - - contextModel.setKeyInformation(keyInformation); - contextModel.getKeyInformation().getKeyInfoMap().put(schema0 .getKey(), new AxKeyInfo(schema0 .getKey(), UUID.fromString("00000000-0000-0000-0000-000000000001"), "axContextSchema0")); - contextModel.getKeyInformation().getKeyInfoMap().put(schema1 .getKey(), new AxKeyInfo(schema1 .getKey(), UUID.fromString("00000000-0000-0000-0000-000000000002"), "axContextSchema1")); - contextModel.getKeyInformation().getKeyInfoMap().put(contextSchemas.getKey(), new AxKeyInfo(contextSchemas.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000003"), "ContextSchemas")); - contextModel.getKeyInformation().getKeyInfoMap().put(contextAlbum0 .getKey(), new AxKeyInfo(contextAlbum0 .getKey(), UUID.fromString("00000000-0000-0000-0000-000000000004"), "contextAlbum0")); - contextModel.getKeyInformation().getKeyInfoMap().put(contextAlbum1 .getKey(), new AxKeyInfo(contextAlbum1 .getKey(), UUID.fromString("00000000-0000-0000-0000-000000000005"), "contextAlbum1")); - contextModel.getKeyInformation().getKeyInfoMap().put(axContext .getKey(), new AxKeyInfo(axContext .getKey(), UUID.fromString("00000000-0000-0000-0000-000000000006"), "axContext")); - contextModel.getKeyInformation().getKeyInfoMap().put(contextModel .getKey(), new AxKeyInfo(contextModel .getKey(), UUID.fromString("00000000-0000-0000-0000-000000000007"), "contextModel")); - contextModel.getKeyInformation().getKeyInfoMap().put(keyInformation.getKey(), new AxKeyInfo(keyInformation.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000008"), "keyInformation")); - - return contextModel; - } - - @Override - public AxContextModel getInvalidModel() { - final AxContextModel contextModel = getModel(); - - contextModel.getAlbums().get(new AxArtifactKey("contextAlbum0", "0.0.1")).setScope("UNDEFINED"); - - contextModel.getSchemas().get(new AxArtifactKey("StringType", "0.0.1")).setSchema(""); - - return contextModel; - } - - public AxContextModel getMalstructuredModel() { - final AxContextModel contextModel = getModel(); - - contextModel.getAlbums().get(new AxArtifactKey("contextAlbum1", "0.0.1")).setKey(new AxArtifactKey("contextAlbum1", "0.0.2"));; - contextModel.getSchemas().get(new AxArtifactKey("MapType", "0.0.1")).setKey(new AxArtifactKey("MapType", "0.0.2"));; - - return contextModel; - } - - @Override - public AxContextModel getObservationModel() { - final AxContextModel contextModel = getModel(); - - contextModel.getKeyInformation().get("contextAlbum1", "0.0.1").setDescription(""); - - return contextModel; - } - - @Override - public AxContextModel getWarningModel() { - final AxContextModel contextModel = getModel(); - - contextModel.getKeyInformation().get("contextAlbum1", "0.0.1").setUuid(UUID.fromString("00000000-0000-0000-0000-000000000000")); - - return contextModel; - } -} diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparison.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparison.java deleted file mode 100644 index fe87509b9..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparison.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.handling; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.junit.Before; -import org.junit.Test; -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbum; -import org.onap.apex.model.contextmodel.concepts.AxContextModel; -import org.onap.apex.model.contextmodel.concepts.AxContextSchema; -import org.onap.apex.model.contextmodel.handling.ContextComparer; -import org.onap.policy.apex.model.utilities.comparison.KeyedMapDifference; - -/** - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextComparison { - private AxContextModel emptyModel; - private AxContextModel fullModel; - private AxContextModel noGlobalContextModel; - private AxContextModel shellModel; - private AxContextModel singleEntryModel; - - @Before - public void getContext() { - final TestContextComparisonFactory factory = new TestContextComparisonFactory(); - emptyModel = factory.getEmptyModel(); - fullModel = factory.getFullModel(); - noGlobalContextModel = factory.getNoGlobalContextModel(); - shellModel = factory.getShellModel(); - singleEntryModel = factory.getSingleEntryModel(); - } - - @Test - public void testEmptyEmpty() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), emptyModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(emptyModel.getSchemas().getSchemasMap().equals(schemaResult.getIdenticalValues())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), emptyModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(emptyModel.getAlbums().getAlbumsMap().equals(albumResult.getIdenticalValues())); - } - - @Test - public void testEmptyFull() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), fullModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(fullModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), fullModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(fullModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); - } - - @Test - public void testFullEmpty() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(fullModel.getSchemas(), emptyModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(fullModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(fullModel.getAlbums(), emptyModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(fullModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); - } - - @Test - public void testEmptyNoGlobalContext() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), noGlobalContextModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(noGlobalContextModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), noGlobalContextModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(noGlobalContextModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); - } - - @Test - public void testNoGlobalContextEmpty() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(noGlobalContextModel.getSchemas(), emptyModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(noGlobalContextModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(noGlobalContextModel.getAlbums(), emptyModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(noGlobalContextModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); - } - - @Test - public void testEmptyShell() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), shellModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(shellModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), shellModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(shellModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); - } - - @Test - public void testShellEmpty() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(shellModel.getSchemas(), emptyModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(shellModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(shellModel.getAlbums(), emptyModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(shellModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); - } - - @Test - public void testEmptySingleEntry() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), singleEntryModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(singleEntryModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), singleEntryModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(singleEntryModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); - } - - @Test - public void testSingleEntryEmpty() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(singleEntryModel.getSchemas(), emptyModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(singleEntryModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(singleEntryModel.getAlbums(), emptyModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(singleEntryModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); - } - - @Test - public void testFullFull() { - final KeyedMapDifference schemaResult = new ContextComparer().compare(fullModel.getSchemas(), fullModel.getSchemas()); - assertNotNull(schemaResult); - assertTrue(fullModel.getSchemas().getSchemasMap().equals(schemaResult.getIdenticalValues())); - - final KeyedMapDifference albumResult = new ContextComparer().compare(fullModel.getAlbums(), fullModel.getAlbums()); - assertNotNull(albumResult); - assertTrue(fullModel.getAlbums().getAlbumsMap().equals(albumResult.getIdenticalValues())); - } -} diff --git a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparisonFactory.java b/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparisonFactory.java deleted file mode 100644 index 1850c222d..000000000 --- a/model/context-model/src/test/java/org/onap/apex/model/contextmodel/handling/TestContextComparisonFactory.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.apex.model.contextmodel.handling; - -import org.onap.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.apex.model.contextmodel.concepts.AxContextAlbum; -import org.onap.apex.model.contextmodel.concepts.AxContextModel; -import org.onap.apex.model.contextmodel.concepts.AxContextSchema; - -/** - * This class creates sample Policy Models - * - * @author Liam Fallon (liam.fallon@ericsson.com) - */ -public class TestContextComparisonFactory { - - public AxContextModel getFullModel() { - final AxContextSchema testContextSchema000 = new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema000"); - final AxContextSchema testContextSchema00A = new AxContextSchema(new AxArtifactKey("TestContextSchema00A", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema00A"); - final AxContextSchema testContextSchema00C = new AxContextSchema(new AxArtifactKey("TestContextSchema00C", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema00C"); - - final AxContextAlbum externalContextAlbum = new AxContextAlbum(new AxArtifactKey("ExternalContextAlbum", "0.0.1"), "EXTERNAL", false, - testContextSchema000.getKey()); - final AxContextAlbum globalContextAlbum = new AxContextAlbum(new AxArtifactKey("GlobalContextAlbum", "0.0.1"), "GLOBAL", true, testContextSchema00A.getKey()); - final AxContextAlbum policy0ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy0ContextAlbum", "0.0.1"), "APPLICATION", true, - testContextSchema00C.getKey()); - final AxContextAlbum policy1ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy1ContextAlbum ", "0.0.1"), "APPLICATION", true, - testContextSchema00C.getKey()); - - final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); - contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); - contextModel.getSchemas().getSchemasMap().put(testContextSchema00A.getKey(), testContextSchema00A); - contextModel.getSchemas().getSchemasMap().put(testContextSchema00C.getKey(), testContextSchema00C); - - contextModel.getAlbums().getAlbumsMap().put(externalContextAlbum.getKey(), externalContextAlbum); - contextModel.getAlbums().getAlbumsMap().put(globalContextAlbum.getKey(), globalContextAlbum); - contextModel.getAlbums().getAlbumsMap().put(policy0ContextAlbum.getKey(), policy0ContextAlbum); - contextModel.getAlbums().getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); - - return contextModel; - } - - public AxContextModel getEmptyModel() { - return new AxContextModel(new AxArtifactKey("Context", "0.0.1")); - } - - public AxContextModel getShellModel() { - final AxContextSchema testContextSchema000 = new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema000"); - final AxContextSchema testContextSchema00A = new AxContextSchema(new AxArtifactKey("TestContextSchema00A", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema00A"); - final AxContextSchema testContextSchema00C = new AxContextSchema(new AxArtifactKey("TestContextSchema00C", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema00C"); - - final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); - contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); - contextModel.getSchemas().getSchemasMap().put(testContextSchema00A.getKey(), testContextSchema00A); - contextModel.getSchemas().getSchemasMap().put(testContextSchema00C.getKey(), testContextSchema00C); - - return contextModel; - } - - public AxContextModel getSingleEntryModel() { - final AxContextSchema testContextSchema000 = new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema000"); - - final AxContextAlbum policy1ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy1ContextAlbum ", "0.0.1"), "APPLICATION", true, - testContextSchema000.getKey()); - - final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); - contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); - - contextModel.getAlbums().getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); - - return contextModel; - } - - public AxContextModel getNoGlobalContextModel() { - final AxContextSchema testContextSchema000 = new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema000"); - final AxContextSchema testContextSchema00C = new AxContextSchema(new AxArtifactKey("TestContextSchema00C", "0.0.1"), "JAVA", - "com.ericsson.apex.concept.TestContextSchema00C"); - - final AxContextAlbum externalContextAlbum = new AxContextAlbum(new AxArtifactKey("ExternalContextAlbum", "0.0.1"), "EXTERNAL", false, - testContextSchema000.getKey()); - final AxContextAlbum policy0ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy0ContextAlbum", "0.0.1"), "APPLICATION", true, - testContextSchema00C.getKey()); - final AxContextAlbum policy1ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy1ContextAlbum ", "0.0.1"), "APPLICATION", true, - testContextSchema00C.getKey()); - - final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); - contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); - contextModel.getSchemas().getSchemasMap().put(testContextSchema00C.getKey(), testContextSchema00C); - - contextModel.getAlbums().getAlbumsMap().put(externalContextAlbum.getKey(), externalContextAlbum); - contextModel.getAlbums().getAlbumsMap().put(policy0ContextAlbum.getKey(), policy0ContextAlbum); - contextModel.getAlbums().getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); - - return contextModel; - } -} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextAlbums.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextAlbums.java new file mode 100644 index 000000000..710c44e5b --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextAlbums.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextAlbums { + + @Test + public void testContextAlbums() { + assertNotNull(new AxContextAlbum()); + assertNotNull(new AxContextAlbum(new AxArtifactKey())); + assertNotNull(new AxContextAlbum(new AxArtifactKey(), "AlbumScope", false, new AxArtifactKey())); + + final AxArtifactKey albumKey = new AxArtifactKey("AlbumName", "0.0.1"); + final AxArtifactKey albumSchemaKey = new AxArtifactKey("AlbumSchemaName", "0.0.1"); + + final AxContextAlbum album = new AxContextAlbum(albumKey, "AlbumScope", false, albumSchemaKey); + assertNotNull(album); + + final AxArtifactKey newKey = new AxArtifactKey("NewAlbumName", "0.0.1"); + album.setKey(newKey); + assertEquals("NewAlbumName:0.0.1", album.getKey().getID()); + assertEquals("NewAlbumName:0.0.1", album.getKeys().get(0).getID()); + album.setKey(albumKey); + + try { + album.setScope(""); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals("parameter \"scope\": value \"\", does not match regular expression \"[A-Za-z0-9\\-_]+\"", + e.getMessage()); + } + + album.setScope("NewAlbumScope"); + assertEquals("NewAlbumScope", album.getScope()); + + assertEquals(false, album.isWritable()); + album.setWritable(true); + assertEquals(true, album.isWritable()); + + final AxArtifactKey newSchemaKey = new AxArtifactKey("NewAlbumSchemaName", "0.0.1"); + album.setItemSchema(newSchemaKey); + assertEquals("NewAlbumSchemaName:0.0.1", album.getItemSchema().getID()); + album.setItemSchema(albumSchemaKey); + + AxValidationResult result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + album.setKey(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + album.setKey(newKey); + result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + album.setScope("UNDEFINED"); + result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + album.setScope("NewAlbumScope"); + result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + album.setItemSchema(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + album.setItemSchema(albumSchemaKey); + result = new AxValidationResult(); + result = album.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + album.clean(); + + final AxContextAlbum clonedAlbum = new AxContextAlbum(album); + assertEquals( + "AxContextAlbum:(key=AxArtifactKey:(name=NewAlbumName,version=0.0.1),scope=NewAlbumScope,isWritable=true,itemSchema=AxArtifactKey:(name=AlbumSchemaName,version=0.0.1))", + clonedAlbum.toString()); + + assertFalse(album.hashCode() == 0); + + assertTrue(album.equals(album)); + assertTrue(album.equals(clonedAlbum)); + assertFalse(album.equals(null)); + assertFalse(album.equals("Hello")); + assertFalse(album.equals(new AxContextAlbum(new AxArtifactKey(), "Scope", false, AxArtifactKey.getNullKey()))); + assertFalse(album.equals(new AxContextAlbum(newKey, "Scope", false, AxArtifactKey.getNullKey()))); + assertFalse(album.equals(new AxContextAlbum(newKey, "NewAlbumScope", false, AxArtifactKey.getNullKey()))); + assertFalse(album.equals(new AxContextAlbum(newKey, "NewAlbumScope", true, AxArtifactKey.getNullKey()))); + assertTrue(album.equals(new AxContextAlbum(newKey, "NewAlbumScope", true, albumSchemaKey))); + + assertEquals(0, album.compareTo(album)); + assertEquals(0, album.compareTo(clonedAlbum)); + assertNotEquals(0, album.compareTo(null)); + assertNotEquals(0, album.compareTo(new AxArtifactKey())); + assertNotEquals(0, + album.compareTo(new AxContextAlbum(new AxArtifactKey(), "Scope", false, AxArtifactKey.getNullKey()))); + assertNotEquals(0, album.compareTo(new AxContextAlbum(newKey, "Scope", false, AxArtifactKey.getNullKey()))); + assertNotEquals(0, + album.compareTo(new AxContextAlbum(newKey, "NewAlbumScope", false, AxArtifactKey.getNullKey()))); + assertNotEquals(0, + album.compareTo(new AxContextAlbum(newKey, "NewAlbumScope", true, AxArtifactKey.getNullKey()))); + assertEquals(0, album.compareTo(new AxContextAlbum(newKey, "NewAlbumScope", true, albumSchemaKey))); + + final AxContextAlbums albums = new AxContextAlbums(); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + // Observation, no albums in album map + albums.setKey(new AxArtifactKey("AlbumsKey", "0.0.1")); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.OBSERVATION, result.getValidationResult()); + + albums.getAlbumsMap().put(newKey, album); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + albums.getAlbumsMap().put(AxArtifactKey.getNullKey(), null); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + albums.getAlbumsMap().remove(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + albums.getAlbumsMap().put(new AxArtifactKey("NullValueKey", "0.0.1"), null); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + albums.getAlbumsMap().remove(new AxArtifactKey("NullValueKey", "0.0.1")); + result = new AxValidationResult(); + result = albums.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + albums.clean(); + + final AxContextAlbums clonedAlbums = new AxContextAlbums(albums); + assertTrue(clonedAlbums.toString() + .startsWith("AxContextAlbums:(AxContextAlbums:(key=AxArtifactKey:(name=AlbumsKey,version=0.0.1)")); + + assertFalse(albums.hashCode() == 0); + + assertTrue(albums.equals(albums)); + assertTrue(albums.equals(clonedAlbums)); + assertFalse(albums.equals(null)); + assertFalse(albums.equals("Hello")); + assertFalse(albums.equals(new AxContextAlbums(new AxArtifactKey()))); + + assertEquals(0, albums.compareTo(albums)); + assertEquals(0, albums.compareTo(clonedAlbums)); + assertNotEquals(0, albums.compareTo(null)); + assertNotEquals(0, albums.compareTo(new AxArtifactKey())); + assertNotEquals(0, albums.compareTo(new AxContextAlbums(new AxArtifactKey()))); + + clonedAlbums.get(newKey).setScope("YetAnotherScope"); + assertNotEquals(0, albums.compareTo(clonedAlbums)); + + assertEquals("NewAlbumName", albums.get("NewAlbumName").getKey().getName()); + assertEquals("NewAlbumName", albums.get("NewAlbumName", "0.0.1").getKey().getName()); + assertEquals(1, albums.getAll("NewAlbumName", "0.0.1").size()); + assertEquals(0, albums.getAll("NonExistantAlbumName").size()); + } +} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextModel.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextModel.java new file mode 100644 index 000000000..163e50018 --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextModel.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextModel { + + @Test + public void test() { + assertNotNull(new AxContextModel()); + assertNotNull(new AxContextModel(new AxArtifactKey())); + assertNotNull(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxKeyInformation())); + assertNotNull(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation())); + + final AxArtifactKey modelKey = new AxArtifactKey("ModelKey", "0.0.1"); + final AxArtifactKey schemasKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxArtifactKey albumsKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxArtifactKey keyInfoKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxContextModel model = new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(albumsKey), new AxKeyInformation(keyInfoKey)); + model.register(); + + model.clean(); + assertNotNull(model); + assertEquals("AxContextModel:(AxContextModel:(key=AxArtifactKey:", model.toString().substring(0, 50)); + + final AxContextModel clonedModel = new AxContextModel(model); + + assertFalse(model.hashCode() == 0); + + assertTrue(model.equals(model)); + assertTrue(model.equals(clonedModel)); + assertFalse(model.equals("Hello")); + assertFalse(model.equals(new AxContextModel(new AxArtifactKey()))); + assertFalse(model.equals(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); + assertFalse(model.equals(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); + assertFalse(model.equals(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); + assertFalse(model.equals(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); + assertTrue(model.equals(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(albumsKey), new AxKeyInformation(keyInfoKey)))); + + assertEquals(0, model.compareTo(model)); + assertEquals(0, model.compareTo(clonedModel)); + assertNotEquals(0, model.compareTo(new AxArtifactKey())); + assertNotEquals(0, model.compareTo(new AxContextModel(new AxArtifactKey(), new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); + assertNotEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation()))); + assertNotEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); + assertNotEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(), new AxKeyInformation(keyInfoKey)))); + assertEquals(0, model.compareTo(new AxContextModel(modelKey, new AxContextSchemas(schemasKey), new AxContextAlbums(albumsKey), new AxKeyInformation(keyInfoKey)))); + } +} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextSchemas.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextSchemas.java new file mode 100644 index 000000000..e9e9564ac --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/concepts/TestContextSchemas.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextSchemas { + + @Test + public void testContextSchemas() { + assertNotNull(new AxContextSchema()); + assertNotNull(new AxContextSchema(new AxArtifactKey(), "SchemaFlavour", "SchemaDefinition")); + + final AxContextSchema schema = + new AxContextSchema(new AxArtifactKey("SchemaName", "0.0.1"), "SchemaFlavour", "SchemaDefinition"); + assertNotNull(schema); + + final AxArtifactKey newKey = new AxArtifactKey("NewSchemaName", "0.0.1"); + schema.setKey(newKey); + assertEquals("NewSchemaName:0.0.1", schema.getKey().getID()); + assertEquals("NewSchemaName:0.0.1", schema.getKeys().get(0).getID()); + + try { + schema.setSchemaFlavour(""); + fail("test should throw an exception here"); + } catch (final Exception e) { + assertEquals( + "parameter \"schemaFlavour\": value \"\", does not match regular expression \"[A-Za-z0-9\\-_]+\"", + e.getMessage()); + } + + schema.setSchemaFlavour("NewSchemaFlavour"); + assertEquals("NewSchemaFlavour", schema.getSchemaFlavour()); + + schema.setSchema("NewSchemaDefinition"); + assertEquals("NewSchemaDefinition", schema.getSchema()); + + AxValidationResult result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schema.setKey(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + schema.setKey(newKey); + result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schema.setSchemaFlavour("UNDEFINED"); + result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + schema.setSchemaFlavour("NewSchemaFlavour"); + result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schema.setSchema(""); + result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + schema.setSchema("NewSchemaDefinition"); + result = new AxValidationResult(); + result = schema.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schema.clean(); + + final AxContextSchema clonedSchema = new AxContextSchema(schema); + assertEquals( + "AxContextSchema:(key=AxArtifactKey:(name=NewSchemaName,version=0.0.1),schemaFlavour=NewSchemaFlavour,schemaDefinition=NewSchemaDefinition)", + clonedSchema.toString()); + + assertFalse(schema.hashCode() == 0); + + assertTrue(schema.equals(schema)); + assertTrue(schema.equals(clonedSchema)); + assertFalse(schema.equals(null)); + assertFalse(schema.equals("Hello")); + assertFalse(schema.equals(new AxContextSchema(new AxArtifactKey(), "Flavour", "Def"))); + assertFalse(schema.equals(new AxContextSchema(newKey, "Flavour", "Def"))); + assertFalse(schema.equals(new AxContextSchema(newKey, "NewSchemaFlavour", "Def"))); + assertTrue(schema.equals(new AxContextSchema(newKey, "NewSchemaFlavour", "NewSchemaDefinition"))); + + assertEquals(0, schema.compareTo(schema)); + assertEquals(0, schema.compareTo(clonedSchema)); + assertNotEquals(0, schema.compareTo(null)); + assertNotEquals(0, schema.compareTo(new AxArtifactKey())); + assertNotEquals(0, schema.compareTo(new AxContextSchema(new AxArtifactKey(), "Flavour", "Def"))); + assertNotEquals(0, schema.compareTo(new AxContextSchema(newKey, "Flavour", "Def"))); + assertNotEquals(0, schema.compareTo(new AxContextSchema(newKey, "NewSchemaFlavour", "Def"))); + assertEquals(0, schema.compareTo(new AxContextSchema(newKey, "NewSchemaFlavour", "NewSchemaDefinition"))); + + final AxContextSchemas schemas = new AxContextSchemas(); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + // Still invalid, no schemas in schema map + schemas.setKey(new AxArtifactKey("SchemasKey", "0.0.1")); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + schemas.getSchemasMap().put(newKey, schema); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schemas.getSchemasMap().put(AxArtifactKey.getNullKey(), null); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + schemas.getSchemasMap().remove(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schemas.getSchemasMap().put(new AxArtifactKey("NullValueKey", "0.0.1"), null); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + schemas.getSchemasMap().remove(new AxArtifactKey("NullValueKey", "0.0.1")); + result = new AxValidationResult(); + result = schemas.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + schemas.clean(); + + final AxContextSchemas clonedSchemas = new AxContextSchemas(schemas); + assertTrue(clonedSchemas.toString() + .startsWith("AxContextSchemas:(key=AxArtifactKey:(name=SchemasKey,version=0.0.1),")); + + assertFalse(schemas.hashCode() == 0); + + assertTrue(schemas.equals(schemas)); + assertTrue(schemas.equals(clonedSchemas)); + assertFalse(schemas.equals(null)); + assertFalse(schemas.equals("Hello")); + assertFalse(schemas.equals(new AxContextSchemas(new AxArtifactKey()))); + + assertEquals(0, schemas.compareTo(schemas)); + assertEquals(0, schemas.compareTo(clonedSchemas)); + assertNotEquals(0, schemas.compareTo(null)); + assertNotEquals(0, schemas.compareTo(new AxArtifactKey())); + assertNotEquals(0, schemas.compareTo(new AxContextSchemas(new AxArtifactKey()))); + + clonedSchemas.get(newKey).setSchemaFlavour("YetAnotherFlavour"); + assertNotEquals(0, schemas.compareTo(clonedSchemas)); + + assertEquals("NewSchemaName", schemas.get("NewSchemaName").getKey().getName()); + assertEquals("NewSchemaName", schemas.get("NewSchemaName", "0.0.1").getKey().getName()); + assertEquals(1, schemas.getAll("NewSchemaName", "0.0.1").size()); + assertEquals(0, schemas.getAll("NonExistantSchemaName").size()); + } +} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModel.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModel.java new file mode 100644 index 000000000..477755ccc --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModel.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.handling; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DAOParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; + +public class TestApexContextModel { + private Connection connection; + TestApexModel testApexModel; + + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel(AxContextModel.class, new TestApexContextModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testApexModelVaidateObservation() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateObservation(); + assertTrue(result.toString().equals(OBSERVATION_MODEL_STRING)); + } + + @Test + public void testApexModelVaidateWarning() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateWarning(); + assertTrue(result.toString().equals(WARNING_MODEL_STRING)); + } + + @Test + public void testModelVaidateInvalidModel() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateInvalidModel(); + assertTrue(result.toString().equals(INVALID_MODEL_STRING)); + } + + @Test + public void testModelVaidateMalstructured() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateMalstructured(); + assertTrue(result.toString().equals(INVALID_MODEL_MALSTRUCTURED_STRING)); + } + + @Test + public void testModelWriteReadXML() throws Exception { + testApexModel.testApexModelWriteReadXML(); + } + + @Test + public void testModelWriteReadJSON() throws Exception { + testApexModel.testApexModelWriteReadJSON(); + } + + @Test + public void testModelWriteReadJPA() throws Exception { + final DAOParameters daoParameters = new DAOParameters(); + daoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + daoParameters.setPersistenceUnit("DAOTest"); + + testApexModel.testApexModelWriteReadJPA(daoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; + + private static final String OBSERVATION_MODEL_STRING = "\n" + + "***observations noted during validation of model***\n" + + "AxArtifactKey:(name=contextAlbum1,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo:OBSERVATION:description is blank\n" + + "********************************"; + + private static final String WARNING_MODEL_STRING = "\n" + "***warnings issued during validation of model***\n" + + "AxArtifactKey:(name=contextAlbum1,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo:WARNING:UUID is a zero UUID: 00000000-0000-0000-0000-000000000000\n" + + "********************************"; + + private static final String INVALID_MODEL_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=StringType,version=0.0.1):org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema:INVALID:no schemaDefinition specified, schemaDefinition may not be blank\n" + + "AxArtifactKey:(name=contextAlbum0,version=0.0.1):org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum:INVALID:scope is not defined\n" + + "********************************"; + + private static final String INVALID_MODEL_MALSTRUCTURED_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=ContextModel,version=0.0.1):org.onap.policy.apex.model.contextmodel.concepts.AxContextModel:INVALID:key information not found for key AxArtifactKey:(name=contextAlbum1,version=0.0.2)\n" + + "AxArtifactKey:(name=contextAlbum1,version=0.0.1):org.onap.policy.apex.model.contextmodel.concepts.AxContextModel:WARNING:key not found for key information entry\n" + + "AxArtifactKey:(name=ContextSchemas,version=0.0.1):org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas:INVALID:key on schemas entry AxArtifactKey:(name=MapType,version=0.0.1) does not equal entry key AxArtifactKey:(name=MapType,version=0.0.2)\n" + + "AxArtifactKey:(name=contextAlbums,version=0.0.1):org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums:INVALID:key on context album entry key AxArtifactKey:(name=contextAlbum1,version=0.0.1) does not equal context album value key AxArtifactKey:(name=contextAlbum1,version=0.0.2)\n" + + "********************************"; + +} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModelCreator.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModelCreator.java new file mode 100644 index 000000000..4e8d8d5a9 --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestApexContextModelCreator.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.handling; + +import java.util.UUID; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; + +public class TestApexContextModelCreator implements TestApexModelCreator { + + @Override + public AxContextModel getModel() { + final AxContextSchema schema0 = new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", + "org.onap.policy.apex.concept.TestContextItem000"); + final AxContextSchema schema1 = new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", + "org.onap.policy.apex.concept.TestContextItem00A"); + + final AxContextSchemas contextSchemas = new AxContextSchemas(new AxArtifactKey("ContextSchemas", "0.0.1")); + contextSchemas.getSchemasMap().put(schema0.getKey(), schema0); + contextSchemas.getSchemasMap().put(schema1.getKey(), schema1); + + final AxContextAlbum contextAlbum0 = + new AxContextAlbum(new AxArtifactKey("contextAlbum0", "0.0.1"), "APPLICATION", true, schema0.getKey()); + final AxContextAlbum contextAlbum1 = + new AxContextAlbum(new AxArtifactKey("contextAlbum1", "0.0.1"), "GLOBAL", false, schema1.getKey()); + + final AxContextAlbums axContext = new AxContextAlbums(new AxArtifactKey("contextAlbums", "0.0.1")); + axContext.getAlbumsMap().put(contextAlbum0.getKey(), contextAlbum0); + axContext.getAlbumsMap().put(contextAlbum1.getKey(), contextAlbum1); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); + final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1"), + contextSchemas, axContext, keyInformation); + + contextModel.setKeyInformation(keyInformation); + contextModel.getKeyInformation().getKeyInfoMap().put(schema0.getKey(), new AxKeyInfo(schema0.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000001"), "axContextSchema0")); + contextModel.getKeyInformation().getKeyInfoMap().put(schema1.getKey(), new AxKeyInfo(schema1.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000002"), "axContextSchema1")); + contextModel.getKeyInformation().getKeyInfoMap().put(contextSchemas.getKey(), new AxKeyInfo( + contextSchemas.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000003"), "ContextSchemas")); + contextModel.getKeyInformation().getKeyInfoMap().put(contextAlbum0.getKey(), new AxKeyInfo( + contextAlbum0.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000004"), "contextAlbum0")); + contextModel.getKeyInformation().getKeyInfoMap().put(contextAlbum1.getKey(), new AxKeyInfo( + contextAlbum1.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000005"), "contextAlbum1")); + contextModel.getKeyInformation().getKeyInfoMap().put(axContext.getKey(), new AxKeyInfo(axContext.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000006"), "axContext")); + contextModel.getKeyInformation().getKeyInfoMap().put(contextModel.getKey(), new AxKeyInfo(contextModel.getKey(), + UUID.fromString("00000000-0000-0000-0000-000000000007"), "contextModel")); + contextModel.getKeyInformation().getKeyInfoMap().put(keyInformation.getKey(), new AxKeyInfo( + keyInformation.getKey(), UUID.fromString("00000000-0000-0000-0000-000000000008"), "keyInformation")); + + return contextModel; + } + + @Override + public AxContextModel getInvalidModel() { + final AxContextModel contextModel = getModel(); + + contextModel.getAlbums().get(new AxArtifactKey("contextAlbum0", "0.0.1")).setScope("UNDEFINED"); + + contextModel.getSchemas().get(new AxArtifactKey("StringType", "0.0.1")).setSchema(""); + + return contextModel; + } + + @Override + public AxContextModel getMalstructuredModel() { + final AxContextModel contextModel = getModel(); + + contextModel.getAlbums().get(new AxArtifactKey("contextAlbum1", "0.0.1")) + .setKey(new AxArtifactKey("contextAlbum1", "0.0.2"));; + contextModel.getSchemas().get(new AxArtifactKey("MapType", "0.0.1")) + .setKey(new AxArtifactKey("MapType", "0.0.2"));; + + return contextModel; + } + + @Override + public AxContextModel getObservationModel() { + final AxContextModel contextModel = getModel(); + + contextModel.getKeyInformation().get("contextAlbum1", "0.0.1").setDescription(""); + + return contextModel; + } + + @Override + public AxContextModel getWarningModel() { + final AxContextModel contextModel = getModel(); + + contextModel.getKeyInformation().get("contextAlbum1", "0.0.1") + .setUuid(UUID.fromString("00000000-0000-0000-0000-000000000000")); + + return contextModel; + } +} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparison.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparison.java new file mode 100644 index 000000000..794cfa9f7 --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparison.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.handling; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.handling.ContextComparer; +import org.onap.policy.apex.model.utilities.comparison.KeyedMapDifference; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextComparison { + private AxContextModel emptyModel; + private AxContextModel fullModel; + private AxContextModel noGlobalContextModel; + private AxContextModel shellModel; + private AxContextModel singleEntryModel; + + @Before + public void getContext() { + final TestContextComparisonFactory factory = new TestContextComparisonFactory(); + emptyModel = factory.getEmptyModel(); + fullModel = factory.getFullModel(); + noGlobalContextModel = factory.getNoGlobalContextModel(); + shellModel = factory.getShellModel(); + singleEntryModel = factory.getSingleEntryModel(); + } + + @Test + public void testEmptyEmpty() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), emptyModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(emptyModel.getSchemas().getSchemasMap().equals(schemaResult.getIdenticalValues())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), emptyModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(emptyModel.getAlbums().getAlbumsMap().equals(albumResult.getIdenticalValues())); + } + + @Test + public void testEmptyFull() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), fullModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(fullModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), fullModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(fullModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); + } + + @Test + public void testFullEmpty() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(fullModel.getSchemas(), emptyModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(fullModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(fullModel.getAlbums(), emptyModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(fullModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); + } + + @Test + public void testEmptyNoGlobalContext() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), noGlobalContextModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(noGlobalContextModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), noGlobalContextModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(noGlobalContextModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); + } + + @Test + public void testNoGlobalContextEmpty() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(noGlobalContextModel.getSchemas(), emptyModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(noGlobalContextModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(noGlobalContextModel.getAlbums(), emptyModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(noGlobalContextModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); + } + + @Test + public void testEmptyShell() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), shellModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(shellModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), shellModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(shellModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); + } + + @Test + public void testShellEmpty() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(shellModel.getSchemas(), emptyModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(shellModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(shellModel.getAlbums(), emptyModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(shellModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); + } + + @Test + public void testEmptySingleEntry() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(emptyModel.getSchemas(), singleEntryModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(singleEntryModel.getSchemas().getSchemasMap().equals(schemaResult.getRightOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(emptyModel.getAlbums(), singleEntryModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(singleEntryModel.getAlbums().getAlbumsMap().equals(albumResult.getRightOnly())); + } + + @Test + public void testSingleEntryEmpty() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(singleEntryModel.getSchemas(), emptyModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(singleEntryModel.getSchemas().getSchemasMap().equals(schemaResult.getLeftOnly())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(singleEntryModel.getAlbums(), emptyModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(singleEntryModel.getAlbums().getAlbumsMap().equals(albumResult.getLeftOnly())); + } + + @Test + public void testFullFull() { + final KeyedMapDifference schemaResult = new ContextComparer().compare(fullModel.getSchemas(), fullModel.getSchemas()); + assertNotNull(schemaResult); + assertTrue(fullModel.getSchemas().getSchemasMap().equals(schemaResult.getIdenticalValues())); + + final KeyedMapDifference albumResult = new ContextComparer().compare(fullModel.getAlbums(), fullModel.getAlbums()); + assertNotNull(albumResult); + assertTrue(fullModel.getAlbums().getAlbumsMap().equals(albumResult.getIdenticalValues())); + } +} diff --git a/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparisonFactory.java b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparisonFactory.java new file mode 100644 index 000000000..2c6f8e172 --- /dev/null +++ b/model/context-model/src/test/java/org/onap/policy/apex/model/contextmodel/handling/TestContextComparisonFactory.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.contextmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextModel; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; + +/** + * This class creates sample Policy Models + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestContextComparisonFactory { + + public AxContextModel getFullModel() { + final AxContextSchema testContextSchema000 = + new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema000"); + final AxContextSchema testContextSchema00A = + new AxContextSchema(new AxArtifactKey("TestContextSchema00A", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema00A"); + final AxContextSchema testContextSchema00C = + new AxContextSchema(new AxArtifactKey("TestContextSchema00C", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema00C"); + + final AxContextAlbum externalContextAlbum = new AxContextAlbum( + new AxArtifactKey("ExternalContextAlbum", "0.0.1"), "EXTERNAL", false, testContextSchema000.getKey()); + final AxContextAlbum globalContextAlbum = new AxContextAlbum(new AxArtifactKey("GlobalContextAlbum", "0.0.1"), + "GLOBAL", true, testContextSchema00A.getKey()); + final AxContextAlbum policy0ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy0ContextAlbum", "0.0.1"), + "APPLICATION", true, testContextSchema00C.getKey()); + final AxContextAlbum policy1ContextAlbum = new AxContextAlbum( + new AxArtifactKey("Policy1ContextAlbum ", "0.0.1"), "APPLICATION", true, testContextSchema00C.getKey()); + + final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); + contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); + contextModel.getSchemas().getSchemasMap().put(testContextSchema00A.getKey(), testContextSchema00A); + contextModel.getSchemas().getSchemasMap().put(testContextSchema00C.getKey(), testContextSchema00C); + + contextModel.getAlbums().getAlbumsMap().put(externalContextAlbum.getKey(), externalContextAlbum); + contextModel.getAlbums().getAlbumsMap().put(globalContextAlbum.getKey(), globalContextAlbum); + contextModel.getAlbums().getAlbumsMap().put(policy0ContextAlbum.getKey(), policy0ContextAlbum); + contextModel.getAlbums().getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); + + return contextModel; + } + + public AxContextModel getEmptyModel() { + return new AxContextModel(new AxArtifactKey("Context", "0.0.1")); + } + + public AxContextModel getShellModel() { + final AxContextSchema testContextSchema000 = + new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema000"); + final AxContextSchema testContextSchema00A = + new AxContextSchema(new AxArtifactKey("TestContextSchema00A", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema00A"); + final AxContextSchema testContextSchema00C = + new AxContextSchema(new AxArtifactKey("TestContextSchema00C", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema00C"); + + final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); + contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); + contextModel.getSchemas().getSchemasMap().put(testContextSchema00A.getKey(), testContextSchema00A); + contextModel.getSchemas().getSchemasMap().put(testContextSchema00C.getKey(), testContextSchema00C); + + return contextModel; + } + + public AxContextModel getSingleEntryModel() { + final AxContextSchema testContextSchema000 = + new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema000"); + + final AxContextAlbum policy1ContextAlbum = new AxContextAlbum( + new AxArtifactKey("Policy1ContextAlbum ", "0.0.1"), "APPLICATION", true, testContextSchema000.getKey()); + + final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); + contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); + + contextModel.getAlbums().getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); + + return contextModel; + } + + public AxContextModel getNoGlobalContextModel() { + final AxContextSchema testContextSchema000 = + new AxContextSchema(new AxArtifactKey("TestContextSchema000", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema000"); + final AxContextSchema testContextSchema00C = + new AxContextSchema(new AxArtifactKey("TestContextSchema00C", "0.0.1"), "JAVA", + "org.onap.policy.apex.concept.TestContextSchema00C"); + + final AxContextAlbum externalContextAlbum = new AxContextAlbum( + new AxArtifactKey("ExternalContextAlbum", "0.0.1"), "EXTERNAL", false, testContextSchema000.getKey()); + final AxContextAlbum policy0ContextAlbum = new AxContextAlbum(new AxArtifactKey("Policy0ContextAlbum", "0.0.1"), + "APPLICATION", true, testContextSchema00C.getKey()); + final AxContextAlbum policy1ContextAlbum = new AxContextAlbum( + new AxArtifactKey("Policy1ContextAlbum ", "0.0.1"), "APPLICATION", true, testContextSchema00C.getKey()); + + final AxContextModel contextModel = new AxContextModel(new AxArtifactKey("ContextModel", "0.0.1")); + contextModel.getSchemas().getSchemasMap().put(testContextSchema000.getKey(), testContextSchema000); + contextModel.getSchemas().getSchemasMap().put(testContextSchema00C.getKey(), testContextSchema00C); + + contextModel.getAlbums().getAlbumsMap().put(externalContextAlbum.getKey(), externalContextAlbum); + contextModel.getAlbums().getAlbumsMap().put(policy0ContextAlbum.getKey(), policy0ContextAlbum); + contextModel.getAlbums().getAlbumsMap().put(policy1ContextAlbum.getKey(), policy1ContextAlbum); + + return contextModel; + } +} diff --git a/model/context-model/src/test/resources/META-INF/persistence.xml b/model/context-model/src/test/resources/META-INF/persistence.xml index d9203b4be..ec9357851 100644 --- a/model/context-model/src/test/resources/META-INF/persistence.xml +++ b/model/context-model/src/test/resources/META-INF/persistence.xml @@ -23,19 +23,19 @@ org.eclipse.persistence.jpa.PersistenceProvider - org.onap.apex.model.basicmodel.dao.converters.CDATAConditioner - org.onap.apex.model.basicmodel.dao.converters.UUID2String - org.onap.apex.model.basicmodel.concepts.AxArtifactKey - org.onap.apex.model.basicmodel.concepts.AxConcept - org.onap.apex.model.basicmodel.concepts.AxKeyInfo - org.onap.apex.model.basicmodel.concepts.AxKeyInformation - org.onap.apex.model.basicmodel.concepts.AxModel - org.onap.apex.model.basicmodel.concepts.TestEntity - org.onap.apex.model.contextmodel.concepts.AxContextSchema - org.onap.apex.model.contextmodel.concepts.AxContextSchemas - org.onap.apex.model.contextmodel.concepts.AxContextAlbum - org.onap.apex.model.contextmodel.concepts.AxContextAlbums - org.onap.apex.model.contextmodel.concepts.AxContextModel + org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner + org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String + org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey + org.onap.policy.apex.model.basicmodel.concepts.AxConcept + org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo + org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation + org.onap.policy.apex.model.basicmodel.concepts.AxModel + org.onap.policy.apex.model.basicmodel.concepts.TestEntity + org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema + org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas + org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum + org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums + org.onap.policy.apex.model.contextmodel.concepts.AxContextModel diff --git a/model/context-model/src/test/resources/json/ContextModel.json b/model/context-model/src/test/resources/json/ContextModel.json index cbaabc63b..2c93ef1c2 100644 --- a/model/context-model/src/test/resources/json/ContextModel.json +++ b/model/context-model/src/test/resources/json/ContextModel.json @@ -85,7 +85,7 @@ "name" : "StringType", "version" : "0.0.1" }, - "javaType" : "com.ericsson.apex.core.contextmodel.concepts.TestContextItem000" + "javaType" : "org.onap.policy.apex.core.contextmodel.concepts.TestContextItem000" }, "isWritable" : true, "valueString" : "" @@ -96,7 +96,7 @@ "name" : "MapType", "version" : "0.0.1" }, - "javaType" : "com.ericsson.apex.core.contextmodel.concepts.TestContextItem00A" + "javaType" : "org.onap.policy.apex.core.contextmodel.concepts.TestContextItem00A" }, "isWritable" : true, "valueString" : "" @@ -107,7 +107,7 @@ "name" : "StringType", "version" : "0.0.1" }, - "javaType" : "com.ericsson.apex.core.contextmodel.concepts.TestContextItem000" + "javaType" : "org.onap.policy.apex.core.contextmodel.concepts.TestContextItem000" }, "isWritable" : true, "valueString" : "" @@ -118,7 +118,7 @@ "name" : "MapType", "version" : "0.0.1" }, - "javaType" : "com.ericsson.apex.core.contextmodel.concepts.TestContextItem00A" + "javaType" : "org.onap.policy.apex.core.contextmodel.concepts.TestContextItem00A" }, "isWritable" : true, "valueString" : "" @@ -141,7 +141,7 @@ "name" : "MapType", "version" : "0.0.1" }, - "javaType" : "com.ericsson.apex.core.contextmodel.concepts.TestContextItem00A" + "javaType" : "org.onap.policy.apex.core.contextmodel.concepts.TestContextItem00A" }, "isWritable" : true }, diff --git a/model/context-model/src/test/resources/logback-test.xml b/model/context-model/src/test/resources/logback-test.xml index 07bc02591..628f02397 100644 --- a/model/context-model/src/test/resources/logback-test.xml +++ b/model/context-model/src/test/resources/logback-test.xml @@ -40,7 +40,7 @@ - + @@ -48,7 +48,7 @@ - + @@ -68,11 +68,11 @@ - + - + diff --git a/model/event-model/pom.xml b/model/event-model/pom.xml new file mode 100644 index 000000000..8e60a8bf4 --- /dev/null +++ b/model/event-model/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + org.onap.policy.apex-pdp.model + model + 2.0.0-SNAPSHOT + + + event-model + ${project.artifactId} + Event Models used in Apex + + + + org.onap.policy.apex-pdp.model + context-model + ${project.version} + + + + + + + org.codehaus.mojo + exec-maven-plugin + + + generate-xml-schema + process-classes + + java + + + org.onap.policy.apex.model.basicmodel.handling.ApexSchemaGenerator + compile + + org.onap.policy.apex.model.eventmodel.concepts.AxEventModel + ${project.build.directory}/model/xml/apex-event-model.xsd + + + + + + + + + \ No newline at end of file diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvent.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvent.java new file mode 100644 index 000000000..4944f1b8a --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvent.java @@ -0,0 +1,560 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.TreeSet; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class defines an Apex event. An {@link AxEvent} is used to kick off execution of policies in Apex and is emitted + * by policies when they completer execution. In addition, Apex uses {@link AxEvent} instances internally to pass + * control from one Apex state to the next during execution. + *

+ * The {@link AxArtifactKey} of an event uniquely identifies it in an Apex system and the name field in the key is the + * name of the event. + *

+ * Each {@link AxEvent} has a name space, which is usually set to identify the domain of application of an event. For + * example a 4G cell power event might have the name space {@code org.onap.radio.4g} and the name {@code PowerEvent}. + * The source and target of the event are reserved to hold an identifier that defines the sender and receiver of an + * event respectively. The definition and structure of these fields is reserved for future use and their use by + * applications is currently not recommended. + *

+ * The parameters that an event has are defined as a map of {@link AxField} instances. + *

+ * Validation checks that the event key is valid. If name space is a blank string, a warning is issued. Blank source or + * target fields result in observations being issued. An event may not have any parameters. If it has parameters, the + * name and value of each parameter entry is checked to ensure they are not null. Then the local name of each parameter + * is checked to ensure it matches the event parameter key on the event. Finally, the parent key of each parameter is + * checked to ensure it matches the event key. + */ +@Entity +@Table(name = "AxEvent") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexEvent", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxEvent", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "key", "nameSpace", "source", "target", "parameterMap" }) + +public class AxEvent extends AxConcept { + private static final long serialVersionUID = -1460388382582984269L; + + private static final String WHITESPACE_REGEXP = "\\s+$"; + + /** The key of the event, unique in the Apex system. */ + @EmbeddedId + @XmlElement(name = "key", required = true) + // CHECKSTYLE:OFF: checkstyle:VisibilityMonitor + protected AxArtifactKey key; + // CHECKSTYLE:ON: checkstyle:VisibilityMonitor + + @Column(name = "nameSpace") + @XmlElement(required = true) + private String nameSpace; + + @Column(name = "source") + @XmlElement(required = true) + private String source; + + @Column(name = "target") + @XmlElement(required = true) + private String target; + + @OneToMany(cascade = CascadeType.ALL) + @XmlElement(name = "parameter", required = true) + private Map parameterMap; + + /** + * The default constructor creates an event with a null artifact key. The event name space, source, and target are + * all defined as empty strings and the parameter map is initialized as an empty map. + */ + public AxEvent() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxEvent(final AxEvent copyConcept) { + super(copyConcept); + } + + /** + * The default constructor creates an event with the given artifact key. The event name space, source, and target + * are all defined as empty strings and the parameter map is initialized as an empty map. + * + * @param key the key of the event + */ + public AxEvent(final AxArtifactKey key) { + this(key, "", "", "", new TreeMap()); + } + + /** + * This constructor creates an event with the given artifact key and name space. The event source, and target are + * all defined as empty strings and the parameter map is initialized as an empty map. + * + * @param key the key of the event + * @param nameSpace the name space of the event + */ + public AxEvent(final AxArtifactKey key, final String nameSpace) { + this(key, nameSpace, "", "", new TreeMap()); + } + + /** + * This constructor creates an event with the given artifact key, name space, source and target. The parameter map + * is initialized as an empty map. + * + * @param key the key of the event + * @param nameSpace the name space of the event + * @param source the source of the event + * @param target the target of the event + */ + public AxEvent(final AxArtifactKey key, final String nameSpace, final String source, final String target) { + this(key, nameSpace, source, target, new TreeMap()); + } + + /** + * This constructor creates an event with all its fields defined. + * + * @param key the key of the event + * @param nameSpace the name space of the event + * @param source the source of the event + * @param target the target of the event + * @param parameterMap the map of parameters that the event has + */ + public AxEvent(final AxArtifactKey key, final String nameSpace, final String source, final String target, + final SortedMap parameterMap) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(nameSpace, "nameSpace may not be null"); + Assertions.argumentNotNull(source, "source may not be null"); + Assertions.argumentNotNull(target, "target may not be null"); + Assertions.argumentNotNull(parameterMap, "parameterMap may not be null"); + + this.key = key; + this.nameSpace = nameSpace; + this.source = source; + this.target = target; + this.parameterMap = parameterMap; + } + + /** + * This method checks that an event has all the fields in the {@code otherFieldSet} set defined on it. + * + * @param otherFieldSet the set of fields to check for existence on this event + * @return true, if all the {@code otherFieldSet} fields are defined on this event + */ + public boolean hasFields(final Set otherFieldSet) { + return parameterMap.values().containsAll(otherFieldSet); + } + + /** + * When an event is unmarshalled from disk or from the database, the parent key in the reference keys in its + * parameter map are not set. This method is called by JAXB after unmarshaling and is used to set the parent key of + * the {@link AxField} instances in the parameter map to be the key of the event that contains them. + * + * @param u the unmarshaler that is unmarshaling the model + * @param parent the parent object of this object in the unmarshaler + */ + public void afterUnmarshal(final Unmarshaller u, final Object parent) { + for (final AxField parameter : parameterMap.values()) { + parameter.getKey().setParentArtifactKey(key); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + + for (final AxField field : parameterMap.values()) { + keyList.addAll(field.getKeys()); + } + return keyList; + } + + /** + * Sets the key of the event. + * + * @param key the key of the event + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + + for (final AxField parameter : parameterMap.values()) { + parameter.getKey().setParentArtifactKey(key); + } + } + + /** + * Gets the name space of the event. + * + * @return the name space of the event + */ + public String getNameSpace() { + return nameSpace; + } + + /** + * Sets the name space of the event. + * + * @param nameSpace the name space of the event + */ + public void setNameSpace(final String nameSpace) { + Assertions.argumentNotNull(nameSpace, "nameSpace may not be null"); + this.nameSpace = nameSpace.trim(); + } + + /** + * Gets the source of the event. + * + * @return the source of the event + */ + public String getSource() { + return source; + } + + /** + * Sets the source of the event. + * + * @param source the source of the event + */ + public void setSource(final String source) { + Assertions.argumentNotNull(source, "source may not be null"); + this.source = source.trim(); + } + + /** + * Gets the target of the event. + * + * @return the target of the event + */ + public String getTarget() { + return target; + } + + /** + * Sets the target of the event. + * + * @param target the target of the event + */ + public void setTarget(final String target) { + Assertions.argumentNotNull(target, "target may not be null"); + this.target = target.trim(); + } + + /** + * Gets the event parameter map. + * + * @return the event parameter map + */ + public Map getParameterMap() { + return parameterMap; + } + + /** + * Gets the fields defined on the event as a set. + * + * @return the fields defined on the event as a set + */ + public Set getFields() { + return new TreeSet<>(parameterMap.values()); + } + + /** + * Sets the event parameter map, containing all the fields of the event. + * + * @param parameterMap the event parameter map + */ + public void setParameterMap(final Map parameterMap) { + Assertions.argumentNotNull(parameterMap, "parameterMap may not be null"); + this.parameterMap = parameterMap; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (nameSpace.replaceAll(WHITESPACE_REGEXP, "").length() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.WARNING, + "nameSpace on event is blank")); + } + + if (source.replaceAll(WHITESPACE_REGEXP, "").length() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.OBSERVATION, + "source on event is blank")); + } + + if (target.replaceAll(WHITESPACE_REGEXP, "").length() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.OBSERVATION, + "target on event is blank")); + } + + for (final Entry eventParameterEntry : parameterMap.entrySet()) { + if (eventParameterEntry.getKey() == null || eventParameterEntry.getKey().equals(AxKey.NULL_KEY_NAME)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on parameter " + eventParameterEntry.getKey() + " may not be the null key")); + } else if (eventParameterEntry.getValue() == null) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "value on parameter " + eventParameterEntry.getKey() + " may not be null")); + } else { + result = vaidateEventParameters(eventParameterEntry, result); + } + } + + return result; + } + + /** + * Validate an event parameter entry + * + * @param eventParameterEntry the event parameter entry + * @param result the validation result to append to + * @return The validation result + */ + private AxValidationResult vaidateEventParameters(final Entry eventParameterEntry, + final AxValidationResult result) { + if (!eventParameterEntry.getKey().equals(eventParameterEntry.getValue().getKey().getLocalName())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on parameter " + eventParameterEntry.getKey() + " does not equal parameter field local name " + + eventParameterEntry.getValue().getKey().getLocalName())); + } + + if (!eventParameterEntry.getValue().getKey().getParentArtifactKey().equals(key)) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "parent key on parameter field " + eventParameterEntry.getValue().getKey() + + " does not equal event key")); + } + + return eventParameterEntry.getValue().validate(result); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + nameSpace = nameSpace.trim(); + source = source.trim(); + target = target.trim(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",nameSpace="); + builder.append(nameSpace); + builder.append(",source="); + builder.append(source); + builder.append(",target="); + builder.append(target); + builder.append(",parameter="); + builder.append(parameterMap); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept targetObject) { + Assertions.argumentNotNull(targetObject, "targetObject may not be null"); + + final Object copyObject = targetObject; + Assertions.instanceOf(copyObject, AxEvent.class); + + final AxEvent copy = (AxEvent) copyObject; + + final Map newParameterMap = new TreeMap<>(); + for (final Entry eventParameterMapEntry : parameterMap.entrySet()) { + newParameterMap.put(eventParameterMapEntry.getKey(), new AxField(eventParameterMapEntry.getValue())); + } + copy.setParameterMap(newParameterMap); + + copy.setKey(new AxArtifactKey(key)); + copy.setNameSpace(nameSpace); + copy.setSource(source); + copy.setTarget(target); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + nameSpace.hashCode(); + result = prime * result + source.hashCode(); + result = prime * result + target.hashCode(); + result = prime * result + parameterMap.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxEvent other = (AxEvent) obj; + if (!key.equals(other.key)) { + return false; + } + if (!nameSpace.equals(other.nameSpace)) { + return false; + } + if (!source.equals(other.source)) { + return false; + } + if (!target.equals(other.target)) { + return false; + } + return parameterMap.equals(other.parameterMap); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxEvent other = (AxEvent) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!nameSpace.equals(other.nameSpace)) { + return nameSpace.compareTo(other.nameSpace); + } + if (!source.equals(other.source)) { + return target.compareTo(other.source); + } + if (!target.equals(other.target)) { + return target.compareTo(other.target); + } + if (!parameterMap.equals(other.parameterMap)) { + return (parameterMap.hashCode() - other.parameterMap.hashCode()); + } + + return 0; + } +} diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java new file mode 100644 index 000000000..3447ff8f9 --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEventModel.java @@ -0,0 +1,330 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.OneToOne; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxModel; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.service.ModelService; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * A container class for an Apex event model. This class is a container class that allows an Apex model to be + * constructed that contains events and context and the key information for those events and context. The model contains + * schema definitions and the definitions of events that use those schemas. + *

+ * Validation runs {@link AxModel} validation on the model. In addition, the {@link AxContextSchemas} and + * {@link AxEvents} validation is run on the context schemas and events in the model. + */ + +@Entity +@Table(name = "AxEventModel") + +@XmlRootElement(name = "apexEventModel", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxEventModel", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "schemas", "events" }) + +public class AxEventModel extends AxModel { + private static final long serialVersionUID = 8800599637708309945L; + + // @formatter:off + @OneToOne(cascade = CascadeType.ALL) + @JoinColumns({ @JoinColumn(name = "schemasName", referencedColumnName = "name"), + @JoinColumn(name = "schemasVersion", referencedColumnName = "version") }) + @XmlElement(name = "schemas", required = true) + private AxContextSchemas schemas; + + @OneToOne(cascade = CascadeType.ALL) + @JoinColumns({ @JoinColumn(name = "eventsName", referencedColumnName = "name"), + @JoinColumn(name = "eventsVersion", referencedColumnName = "version") }) + @XmlElement(name = "events", required = true) + private AxEvents events; + // @formatter:on + + /** + * The Default Constructor creates a {@link AxEventModel} object with a null artifact key and creates an empty event + * model. + */ + public AxEventModel() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxEventModel(final AxEventModel copyConcept) { + super(copyConcept); + } + + /** + * The Key Constructor creates a {@link AxEventModel} object with the given artifact key and creates an empty event + * model. + * + * @param key the event model key + */ + public AxEventModel(final AxArtifactKey key) { + this(key, new AxContextSchemas(new AxArtifactKey(key.getName() + "_Schemas", key.getVersion())), + new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion())), + new AxEvents(new AxArtifactKey(key.getName() + "_Events", key.getVersion()))); + } + + /** + * Constructor that initiates a {@link AxEventModel} with all its fields. + * + * @param key the event model key + * @param schemas the schemas for events in the event model + * @param keyInformation the key information for context schemas and events in the event model + * @param events the events in the event model + */ + public AxEventModel(final AxArtifactKey key, final AxContextSchemas schemas, final AxKeyInformation keyInformation, + final AxEvents events) { + super(key, keyInformation); + Assertions.argumentNotNull(events, "events may not be null"); + + this.schemas = schemas; + this.events = events; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#register() + */ + @Override + public void register() { + super.register(); + ModelService.registerModel(AxContextSchemas.class, getSchemas()); + ModelService.registerModel(AxEvents.class, getEvents()); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#getKeys() + */ + @Override + public List getKeys() { + final List keyList = super.getKeys(); + + keyList.addAll(schemas.getKeys()); + keyList.addAll(events.getKeys()); + + return keyList; + } + + /** + * Gets the context schemas. + * + * @return the context schemas + */ + public AxContextSchemas getSchemas() { + return schemas; + } + + /** + * Sets the context schemas. + * + * @param schemas the context schemas + */ + public void setSchemas(final AxContextSchemas schemas) { + Assertions.argumentNotNull(schemas, "schemas may not be null"); + this.schemas = schemas; + } + + /** + * Gets the events from the model. + * + * @return the events + */ + public AxEvents getEvents() { + return events; + } + + /** + * Sets the events in the model. + * + * @param events the events + */ + public void setEvents(final AxEvents events) { + Assertions.argumentNotNull(events, "events may not be null"); + this.events = events; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxModel#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + result = super.validate(result); + result = schemas.validate(result); + return events.validate(result); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#clean() + */ + @Override + public void clean() { + super.clean(); + schemas.clean(); + events.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append(super.toString()); + builder.append(",schemas="); + builder.append(schemas); + builder.append(",events="); + builder.append(events); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept targetObject) { + Assertions.argumentNotNull(targetObject, "target may not be null"); + + final Object copyObject = targetObject; + Assertions.instanceOf(copyObject, AxEventModel.class); + + final AxEventModel copy = ((AxEventModel) copyObject); + super.copyTo(targetObject); + copy.setSchemas(new AxContextSchemas(schemas)); + copy.setEvents(new AxEvents(events)); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + super.hashCode(); + result = prime * result + schemas.hashCode(); + result = prime * result + events.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxModel#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + throw new IllegalArgumentException("comparison object may not be null"); + } + + if (this == obj) { + return true; + } + if (getClass() != obj.getClass()) { + return false; + } + + final AxEventModel other = (AxEventModel) obj; + if (!super.equals(other)) { + return false; + } + if (!schemas.equals(other.schemas)) { + return false; + } + return events.equals(other.events); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxModel#compareTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public int compareTo(final AxConcept otherObj) { + Assertions.argumentNotNull(otherObj, "comparison object may not be null"); + + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxEventModel other = (AxEventModel) otherObj; + if (!super.equals(other)) { + return super.compareTo(other); + } + if (!schemas.equals(other.schemas)) { + return schemas.compareTo(other.schemas); + } + return events.compareTo(other.events); + } +} diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvents.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvents.java new file mode 100644 index 000000000..df398c2c9 --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxEvents.java @@ -0,0 +1,420 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NavigableMap; +import java.util.Set; +import java.util.TreeMap; + +import javax.persistence.CascadeType; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.Table; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter; +import org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetterImpl; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * This class is an event container and holds a map of the events for an entire Apex model. All Apex models that use + * events must have an {@link AxEvents} field. The {@link AxEvents} class implements the helper methods of the + * {@link AxConceptGetter} interface to allow {@link AxEvents} instances to be retrieved by calling methods directly on + * this class without referencing the contained map. + *

+ * Validation checks that the container key is not null. An error is issued if no events are defined in the container. + * Each event entry is checked to ensure that its key and value are not null and that the key matches the key in the map + * value. Each event entry is then validated individually. + */ +@Entity +@Table(name = "AxEvents") + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AxEvents", namespace = "http://www.onap.org/policy/apex-pdp", propOrder = { "key", "eventMap" }) + +public class AxEvents extends AxConcept implements AxConceptGetter { + private static final long serialVersionUID = 4290442590545820316L; + + @EmbeddedId + @XmlElement(name = "key", required = true) + private AxArtifactKey key; + + // @formatter:off + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable( + joinColumns = { @JoinColumn(name = "eventMapName", referencedColumnName = "name"), + @JoinColumn(name = "eventMapVersion", referencedColumnName = "version") }, + inverseJoinColumns = { @JoinColumn(name = "eventName", referencedColumnName = "name"), + @JoinColumn(name = "eventVersion", referencedColumnName = "version") }) + @XmlElement(required = true) + private Map eventMap; + // @formatter:on + + /** + * The Default Constructor creates a {@link AxEvents} object with a null artifact key and creates an empty event + * map. + */ + public AxEvents() { + this(new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxEvents(final AxEvents copyConcept) { + super(copyConcept); + } + + /** + * The Key Constructor creates a {@link AxEvents} object with the given artifact key and creates an empty event map. + * + * @param key the event container key + */ + public AxEvents(final AxArtifactKey key) { + this(key, new TreeMap()); + } + + /** + * This Constructor creates an event container with all of its fields defined. + * + * @param key the event container key + * @param eventMap the events to be stored in the event container + */ + public AxEvents(final AxArtifactKey key, final Map eventMap) { + super(); + Assertions.argumentNotNull(key, "key may not be null"); + Assertions.argumentNotNull(eventMap, "eventMap may not be null"); + + this.key = key; + this.eventMap = new TreeMap<>(); + this.eventMap.putAll(eventMap); + } + + /** + * When a model is unmarshalled from disk or from the database, the event map is returned as a raw hash map. This + * method is called by JAXB after unmarshaling and is used to convert the hash map to a {@link NavigableMap} so that + * it will work with the {@link AxConceptGetter} interface. + * + * @param u the unmarshaler that is unmarshaling the model + * @param parent the parent object of this object in the unmarshaler + */ + public void afterUnmarshal(final Unmarshaller u, final Object parent) { + // The map must be navigable to allow name and version searching, unmarshaling returns a hash map + final NavigableMap navigableEventMap = new TreeMap<>(); + navigableEventMap.putAll(eventMap); + eventMap = navigableEventMap; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxArtifactKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + + for (final AxEvent event : eventMap.values()) { + keyList.addAll(event.getKeys()); + } + + return keyList; + } + + /** + * Sets the key of the event container. + * + * @param key the event container key + */ + public void setKey(final AxArtifactKey key) { + Assertions.argumentNotNull(key, "key may not be null"); + this.key = key; + } + + /** + * Gets the event map containing the events in the event container. + * + * @return the event map with all the events in the event container + */ + public Map getEventMap() { + return eventMap; + } + + /** + * Sets the event map containing the events in the event container. + * + * @param eventMap the event map containing the events in the event container + */ + public void setEventMap(final Map eventMap) { + Assertions.argumentNotNull(eventMap, "eventMap may not be null"); + this.eventMap = new TreeMap<>(); + this.eventMap.putAll(eventMap); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (eventMap.size() == 0) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "eventMap may not be empty")); + } else { + for (final Entry eventEntry : eventMap.entrySet()) { + if (eventEntry.getKey().equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "key on event entry " + eventEntry.getKey() + " may not be the null key")); + } else if (eventEntry.getValue() == null) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "value on event entry " + eventEntry.getKey() + " may not be null")); + } else { + if (!eventEntry.getKey().equals(eventEntry.getValue().getKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), + ValidationResult.INVALID, "key on event entry key " + eventEntry.getKey() + + " does not equal event value key " + eventEntry.getValue().getKey())); + } + + result = eventEntry.getValue().validate(result); + } + } + } + + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + for (final Entry eventEntry : eventMap.entrySet()) { + eventEntry.getKey().clean(); + eventEntry.getValue().clean(); + } + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",eventMap="); + builder.append(eventMap); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept targetObject) { + Assertions.argumentNotNull(targetObject, "target may not be null"); + + final Object copyObject = targetObject; + Assertions.instanceOf(copyObject, AxEvents.class); + + final AxEvents copy = (AxEvents) copyObject; + copy.setKey(new AxArtifactKey(key)); + final Map newEventMap = new TreeMap<>(); + for (final Entry eventMapEntry : eventMap.entrySet()) { + newEventMap.put(new AxArtifactKey(eventMapEntry.getKey()), new AxEvent(eventMapEntry.getValue())); + } + copy.setEventMap(newEventMap); + + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + eventMap.hashCode(); + return result; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (getClass() != obj.getClass()) { + return false; + } + + final AxEvents other = (AxEvents) obj; + if (!key.equals(other.key)) { + return false; + } + return eventMap.equals(other.eventMap); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return -1; + } + if (this == otherObj) { + return 0; + } + if (getClass() != otherObj.getClass()) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxEvents other = (AxEvents) otherObj; + if (!key.equals(other.key)) { + return key.compareTo(other.key); + } + if (!eventMap.equals(other.eventMap)) { + return (eventMap.hashCode() - other.eventMap.hashCode()); + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(org.onap.policy.apex.model.basicmodel. + * concepts. AxArtifactKey) + */ + @Override + public AxEvent get(final AxArtifactKey conceptKey) { + return new AxConceptGetterImpl<>((NavigableMap) eventMap).get(conceptKey); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String) + */ + @Override + public AxEvent get(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) eventMap).get(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#get(java.lang.String, java.lang.String) + */ + @Override + public AxEvent get(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) eventMap).get(conceptKeyName, + conceptKeyVersion); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName) { + return new AxConceptGetterImpl<>((NavigableMap) eventMap).getAll(conceptKeyName); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConceptGetter#getAll(java.lang.String, java.lang.String) + */ + @Override + public Set getAll(final String conceptKeyName, final String conceptKeyVersion) { + return new AxConceptGetterImpl<>((NavigableMap) eventMap).getAll(conceptKeyName, + conceptKeyVersion); + } +} diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java new file mode 100644 index 000000000..4aee0ebca --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxField.java @@ -0,0 +1,406 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import java.util.List; + +import javax.persistence.AttributeOverride; +import javax.persistence.AttributeOverrides; +import javax.persistence.Column; +import javax.persistence.Embedded; +import javax.persistence.EmbeddedId; +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxConcept; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyUse; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationMessage; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.basicmodel.xml.AxReferenceKeyAdapter; +import org.onap.policy.apex.model.utilities.Assertions; + +/** + * In Apex, a field is an input or output parameter to or from a concept. For example, the parameters of an event are + * fields and the input and output of a task is defined as a collection of fields. + *

+ * A field has an {@link AxReferenceKey} key that defines its name and parent, and a {@link AxArtifactKey} key to a + * context schema that defines the structure of the data atom that holds the value of the field. Fields can be specified + * as being optional but are mandatory by default. + *

+ * Validation checks that the field key and the field schema reference key are not null. + */ +@Entity +@Table(name = "AxField") +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexField", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxField", namespace = "http://www.onap.org/policy/apex-pdp", + propOrder = { "key", "fieldSchemaKey", "optional" }) + +public class AxField extends AxConcept { + private static final String KEY_MAY_NOT_BE_NULL = "key may not be null"; + private static final String FIELD_SCHEMA_KEY_MAY_NOT_BE_NULL = "fieldSchemaKey may not be null"; + + private static final long serialVersionUID = -6443016863162692288L; + + private static final int HASH_PRIME_0 = 1231; + private static final int HASH_PRIME_1 = 1237; + + @EmbeddedId() + @XmlElement(name = "key", required = true) + @XmlJavaTypeAdapter(AxReferenceKeyAdapter.class) + private AxReferenceKey key; + + // @formatter:off + @Embedded + @AttributeOverrides({ @AttributeOverride(name = "name", column = @Column(name = "fieldSchemaName")), + @AttributeOverride(name = "version", column = @Column(name = "fieldSchemaVersion")) }) + @Column(name = "fieldSchemaKey") + @XmlElement(required = true) + private AxArtifactKey fieldSchemaKey; + // @formatter:on + + @Column(name = "optional") + @XmlElement(required = false) + private boolean optional; + + /** + * The default constructor creates a field with a null artifact and schema key. + */ + public AxField() { + this(new AxReferenceKey()); + optional = false; + } + + /** + * The default constructor creates a field with the given artifact key and a null schema key. + * + * @param key the field key + */ + public AxField(final AxReferenceKey key) { + this(key, new AxArtifactKey()); + } + + /** + * Copy constructor + * + * @param copyConcept the concept to copy from + */ + public AxField(final AxField copyConcept) { + super(copyConcept); + } + + /** + * Constructor to create the field with both its keys defined. + * + * @param key the field key + * @param fieldSchemaKey the key of the field schema to use for this field + */ + public AxField(final AxReferenceKey key, final AxArtifactKey fieldSchemaKey) { + super(); + Assertions.argumentNotNull(key, KEY_MAY_NOT_BE_NULL); + Assertions.argumentNotNull(fieldSchemaKey, FIELD_SCHEMA_KEY_MAY_NOT_BE_NULL); + + this.key = key; + this.fieldSchemaKey = fieldSchemaKey; + } + + /** + * Constructor to create the field with all its fields defined. + * + * @param key the field key + * @param fieldSchemaKey the key of the field schema to use for this field + * @param optional true if this field is optional + */ + public AxField(final AxReferenceKey key, final AxArtifactKey fieldSchemaKey, final boolean optional) { + super(); + Assertions.argumentNotNull(key, KEY_MAY_NOT_BE_NULL); + Assertions.argumentNotNull(fieldSchemaKey, FIELD_SCHEMA_KEY_MAY_NOT_BE_NULL); + + this.key = key; + this.fieldSchemaKey = fieldSchemaKey; + this.optional = optional; + } + + /** + * Constructor to create the field with the local name of its reference key defined and its schema key defined. + * + * @param localName the local name of the field reference key + * @param fieldSchemaKey the key of the field schema to use for this field + */ + public AxField(final String localName, final AxArtifactKey fieldSchemaKey) { + super(); + Assertions.argumentNotNull(localName, "localName may not be null"); + Assertions.argumentNotNull(fieldSchemaKey, FIELD_SCHEMA_KEY_MAY_NOT_BE_NULL); + + key = new AxReferenceKey(); + key.setLocalName(localName); + this.fieldSchemaKey = fieldSchemaKey; + } + + /** + * Constructor to create the field with the local name of its reference key defined, its schema key and optionality + * defined. + * + * @param localName the local name of the field reference key + * @param fieldSchemaKey the key of the field schema to use for this field + * @param optional true if this field is optional + */ + public AxField(final String localName, final AxArtifactKey fieldSchemaKey, final boolean optional) { + super(); + Assertions.argumentNotNull(localName, "localName may not be null"); + Assertions.argumentNotNull(fieldSchemaKey, FIELD_SCHEMA_KEY_MAY_NOT_BE_NULL); + + key = new AxReferenceKey(); + key.setLocalName(localName); + this.fieldSchemaKey = fieldSchemaKey; + this.optional = optional; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKey() + */ + @Override + public AxReferenceKey getKey() { + return key; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#getKeys() + */ + @Override + public List getKeys() { + final List keyList = key.getKeys(); + keyList.add(new AxKeyUse(fieldSchemaKey)); + return keyList; + } + + /** + * Sets the reference key of the field. + * + * @param key the field reference key + */ + public void setKey(final AxReferenceKey key) { + Assertions.argumentNotNull(key, KEY_MAY_NOT_BE_NULL); + this.key = key; + } + + /** + * Gets the key of the field schema. + * + * @return the field schema key + */ + public AxArtifactKey getSchema() { + return fieldSchemaKey; + } + + /** + * Sets the key of the field schema. + * + * @param schema the field schema key + */ + public void setSchema(final AxArtifactKey schema) { + Assertions.argumentNotNull(schema, "schema may not be null"); + this.fieldSchemaKey = schema; + } + + /** + * Gets the optionality of the field. + * + * @return the field optional flag + */ + public boolean getOptional() { + return optional; + } + + /** + * Sets the optionality of the field. + * + * @param optional the optionality of the field + */ + public void setOptional(final boolean optional) { + this.optional = optional; + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#validate(org.onap.policy.apex.model.basicmodel.concepts. + * AxValidationResult) + */ + @Override + public AxValidationResult validate(final AxValidationResult resultIn) { + AxValidationResult result = resultIn; + + if (key.equals(AxReferenceKey.getNullKey())) { + result.addValidationMessage( + new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key")); + } + + result = key.validate(result); + + if (fieldSchemaKey.equals(AxArtifactKey.getNullKey())) { + result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "fieldSchemaKey is a null key: " + fieldSchemaKey)); + } + return fieldSchemaKey.validate(result); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#clean() + */ + @Override + public void clean() { + key.clean(); + fieldSchemaKey.clean(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#toString() + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append(this.getClass().getSimpleName()); + builder.append(":("); + builder.append("key="); + builder.append(key); + builder.append(",fieldSchemaKey="); + builder.append(fieldSchemaKey); + builder.append(",optional="); + builder.append(optional); + builder.append(")"); + return builder.toString(); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.model.basicmodel.concepts.AxConcept#copyTo(org.onap.policy.apex.model.basicmodel.concepts. + * AxConcept) + */ + @Override + public AxConcept copyTo(final AxConcept targetObject) { + Assertions.argumentNotNull(targetObject, "target may not be null"); + + final Object copyObject = targetObject; + Assertions.instanceOf(copyObject, AxField.class); + + final AxField copy = ((AxField) copyObject); + copy.setKey(new AxReferenceKey(key)); + copy.setSchema(new AxArtifactKey(fieldSchemaKey)); + copy.setOptional(optional); + return copy; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + key.hashCode(); + result = prime * result + fieldSchemaKey.hashCode(); + result = prime * result + (optional ? HASH_PRIME_0 : HASH_PRIME_1); + return result; + } + + /* + * (nonJavadoc) + * + * @see org.onap.policy.apex.model.basicmodel.concepts.AxConcept#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (obj == null) { + return false; + } + if (this == obj) { + return true; + } + + if (!(obj instanceof AxField)) { + return false; + } + + final AxField other = (AxField) obj; + if (!key.getLocalName().equals(other.key.getLocalName())) { + return false; + } + if (optional != other.optional) { + return false; + } + return fieldSchemaKey.equals(other.fieldSchemaKey); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Comparable#compareTo(java.lang.Object) + */ + @Override + public int compareTo(final AxConcept otherObj) { + if (otherObj == null) { + return 1; + } + if (this == otherObj) { + return 0; + } + if (!(otherObj instanceof AxField)) { + return this.hashCode() - otherObj.hashCode(); + } + + final AxField other = (AxField) otherObj; + if (!key.getLocalName().equals(other.key.getLocalName())) { + return key.getLocalName().compareTo(other.key.getLocalName()); + } + if (optional != other.optional) { + return (optional ? 1 : -1); + } + return fieldSchemaKey.compareTo(other.fieldSchemaKey); + } +} diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxInputField.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxInputField.java new file mode 100644 index 000000000..e7a9a2af5 --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxInputField.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; + +/** + * This class specializes the {@link AxField} class for use as input fields on events. + */ +@Entity +@Table(name = "AxInputField") +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexInputField", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxInputField", namespace = "http://www.onap.org/policy/apex-pdp") + +public class AxInputField extends AxField { + private static final long serialVersionUID = 2090324845463750391L; + + /** + * The default constructor creates a field with a null artifact and schema key. + */ + public AxInputField() { + super(); + } + + /** + * The default constructor creates a field with the given artifact key and a null schema key. + * + * @param key the field key + */ + public AxInputField(final AxReferenceKey key) { + super(key); + } + + /** + * Constructor to create the field with both its keys defined. + * + * @param key the field key + * @param fieldSchemaKey the key of the field schema to use for this field + */ + public AxInputField(final AxReferenceKey key, final AxArtifactKey fieldSchemaKey) { + super(key, fieldSchemaKey); + } + + /** + * Constructor to create the field with both its keys defined and optional flag specified. + * + * @param key the field key + * @param fieldSchemaKey the key of the field schema to use for this field + * @param optional true if the task field is optional, false otherwise + */ + public AxInputField(final AxReferenceKey key, final AxArtifactKey fieldSchemaKey, final boolean optional) { + super(key, fieldSchemaKey, optional); + } + + /** + * Constructor to create the field with the local name of its reference key defined and its schema key defined. + * + * @param localName the local name of the field reference key + * @param fieldSchemaKey the key of the field schema to use for this field + */ + public AxInputField(final String localName, final AxArtifactKey fieldSchemaKey) { + super(localName, fieldSchemaKey); + } + + /** + * Copy constructor, create an input field as a copy of another input field. + * + * @param field the input field to copy from + */ + public AxInputField(final AxInputField field) { + super(new AxReferenceKey(field.getKey()), new AxArtifactKey(field.getSchema())); + } +} diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxOutputField.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxOutputField.java new file mode 100644 index 000000000..1dd2ecb7a --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/AxOutputField.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import javax.persistence.Entity; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; + +/** + * This class specializes the {@link AxField} class for use as output fields on events. + */ +@Entity +@Table(name = "AxOutputField") +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "apexOutputField", namespace = "http://www.onap.org/policy/apex-pdp") +@XmlType(name = "AxOutputField", namespace = "http://www.onap.org/policy/apex-pdp") + +public class AxOutputField extends AxField { + private static final long serialVersionUID = 2090324845463750391L; + + /** + * The default constructor creates a field with a null artifact and schema key. + */ + public AxOutputField() { + super(); + } + + /** + * The default constructor creates a field with the given artifact key and a null schema key. + * + * @param key the field key + */ + public AxOutputField(final AxReferenceKey key) { + super(key); + } + + /** + * Constructor to create the field with both its keys defined. + * + * @param key the field key + * @param fieldSchemaKey the key of the field schema to use for this field + */ + public AxOutputField(final AxReferenceKey key, final AxArtifactKey fieldSchemaKey) { + super(key, fieldSchemaKey); + } + + /** + * Constructor to create the field with both its keys defined and optional flag specified. + * + * @param key the field key + * @param fieldSchemaKey the key of the field schema to use for this field + * @param optional true if the task field is optional, false otherwise + */ + public AxOutputField(final AxReferenceKey key, final AxArtifactKey fieldSchemaKey, final boolean optional) { + super(key, fieldSchemaKey, optional); + } + + /** + * Constructor to create the field with the local name of its reference key defined and its schema key defined. + * + * @param localName the local name of the field reference key + * @param fieldSchemaKey the key of the field schema to use for this field + */ + public AxOutputField(final String localName, final AxArtifactKey fieldSchemaKey) { + super(localName, fieldSchemaKey); + } + + /** + * Copy constructor, create an output field as a copy of another output field. + * + * @param field the output field to copy from + */ + public AxOutputField(final AxOutputField field) { + super(new AxReferenceKey(field.getKey()), new AxArtifactKey(field.getSchema())); + } +} diff --git a/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/package-info.java b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/package-info.java new file mode 100644 index 000000000..7b20b3939 --- /dev/null +++ b/model/event-model/src/main/java/org/onap/policy/apex/model/eventmodel/concepts/package-info.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Contains the concepts required to manage events in APEX. It defines the main Apex concepts of events and fields. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +@XmlSchema(namespace = "http://www.onap.org/policy/apex-pdp", elementFormDefault = XmlNsForm.QUALIFIED, + xmlns = { @XmlNs(namespaceURI = "http://www.onap.org/policy/apex-pdp", prefix = "") }) + +package org.onap.policy.apex.model.eventmodel.concepts; + +import javax.xml.bind.annotation.XmlNs; +import javax.xml.bind.annotation.XmlNsForm; +import javax.xml.bind.annotation.XmlSchema; diff --git a/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEventModel.java b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEventModel.java new file mode 100644 index 000000000..dbff0666d --- /dev/null +++ b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEventModel.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.eventmodel.concepts.AxEventModel; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestEventModel { + + @Test + public void testEventModel() { + assertNotNull(new AxEventModel()); + assertNotNull(new AxEventModel(new AxArtifactKey())); + assertNotNull( + new AxEventModel(new AxArtifactKey(), new AxContextSchemas(), new AxKeyInformation(), new AxEvents())); + + final AxArtifactKey modelKey = new AxArtifactKey("ModelKey", "0.0.1"); + final AxArtifactKey schemasKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxArtifactKey eventsKey = new AxArtifactKey("EventsKey", "0.0.1"); + final AxArtifactKey keyInfoKey = new AxArtifactKey("SchemasKey", "0.0.1"); + final AxEventModel model = new AxEventModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxEvents(eventsKey)); + model.register(); + + model.clean(); + assertNotNull(model); + assertEquals("AxEventModel:(AxEventModel:(key=AxArtifactKey:(nam", model.toString().substring(0, 50)); + + final AxEventModel clonedModel = new AxEventModel(model); + + assertFalse(model.hashCode() == 0); + + assertTrue(model.equals(model)); + assertTrue(model.equals(clonedModel)); + assertFalse(model.equals("Hello")); + assertFalse(model.equals(new AxEventModel(new AxArtifactKey()))); + assertFalse(model.equals(new AxEventModel(modelKey, new AxContextSchemas(), new AxKeyInformation(keyInfoKey), + new AxEvents(eventsKey)))); + assertFalse(model.equals(new AxEventModel(modelKey, new AxContextSchemas(schemasKey), new AxKeyInformation(), + new AxEvents(eventsKey)))); + assertFalse(model.equals(new AxEventModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxEvents()))); + assertTrue(model.equals(new AxEventModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxEvents(eventsKey)))); + + assertEquals(0, model.compareTo(model)); + assertEquals(0, model.compareTo(clonedModel)); + assertNotEquals(0, model.compareTo(new AxArtifactKey())); + assertNotEquals(0, model.compareTo(new AxEventModel(modelKey, new AxContextSchemas(), + new AxKeyInformation(keyInfoKey), new AxEvents(eventsKey)))); + assertNotEquals(0, model.compareTo(new AxEventModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(), new AxEvents(eventsKey)))); + assertNotEquals(0, model.compareTo(new AxEventModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxEvents()))); + assertEquals(0, model.compareTo(new AxEventModel(modelKey, new AxContextSchemas(schemasKey), + new AxKeyInformation(keyInfoKey), new AxEvents(eventsKey)))); + } +} diff --git a/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEvents.java b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEvents.java new file mode 100644 index 000000000..5456dfad8 --- /dev/null +++ b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestEvents.java @@ -0,0 +1,298 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.TreeMap; +import java.util.TreeSet; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestEvents { + + @Test + public void testEvents() { + final TreeMap parameterMap = new TreeMap<>(); + final TreeMap parameterMapEmpty = new TreeMap<>(); + + assertNotNull(new AxEvent()); + assertNotNull(new AxEvent(new AxArtifactKey())); + assertNotNull(new AxEvent(new AxArtifactKey(), "namespace")); + assertNotNull(new AxEvent(new AxArtifactKey(), "namespace", "source", "target")); + assertNotNull(new AxEvent(new AxArtifactKey(), "namespace", "source", "target")); + assertNotNull(new AxEvent(new AxArtifactKey(), "namespace", "source", "target", parameterMap)); + + final AxEvent event = new AxEvent(); + + final AxArtifactKey eventKey = new AxArtifactKey("EventName", "0.0.1"); + event.setKey(eventKey); + assertEquals("EventName:0.0.1", event.getKey().getID()); + assertEquals("EventName:0.0.1", event.getKeys().get(0).getID()); + + event.setNameSpace("namespace"); + assertEquals("namespace", event.getNameSpace()); + + event.setSource("source"); + assertEquals("source", event.getSource()); + + event.setTarget("target"); + assertEquals("target", event.getTarget()); + + event.setParameterMap(parameterMap); + assertEquals(0, event.getParameterMap().size()); + + final AxField eventField = + new AxField(new AxReferenceKey(eventKey, "Field0"), new AxArtifactKey("Field0Schema", "0.0.1")); + event.getParameterMap().put(eventField.getKey().getLocalName(), eventField); + assertEquals(1, event.getParameterMap().size()); + + final AxField eventFieldBadParent = + new AxField(new AxReferenceKey(new AxArtifactKey("OtherEvent", "0.0.01"), "Field0"), + new AxArtifactKey("Field0Schema", "0.0.1")); + + final AxArtifactKey newEventKey = new AxArtifactKey("NewEventName", "0.0.1"); + event.setKey(newEventKey); + assertEquals("NewEventName:0.0.1", event.getKey().getID()); + assertEquals("NewEventName:0.0.1", event.getKeys().get(0).getID()); + assertEquals("NewEventName:0.0.1", + event.getParameterMap().get("Field0").getKey().getParentArtifactKey().getID()); + event.setKey(eventKey); + assertEquals("EventName:0.0.1", event.getKey().getID()); + assertEquals("EventName:0.0.1", event.getKeys().get(0).getID()); + + assertTrue("Field0", event.getFields().contains(eventField)); + assertTrue(event.hasFields(new TreeSet(parameterMap.values()))); + + AxValidationResult result = new AxValidationResult(); + result = event.validate(result); + assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); + + event.setKey(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + event.setKey(eventKey); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.setNameSpace(""); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.WARNING, result.getValidationResult()); + + event.setNameSpace("namespace"); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.setSource(""); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.OBSERVATION, result.getValidationResult()); + + event.setSource("source"); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.setTarget(""); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.OBSERVATION, result.getValidationResult()); + + event.setTarget("target"); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.getParameterMap().put(AxKey.NULL_KEY_NAME, null); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + event.getParameterMap().remove(AxKey.NULL_KEY_NAME); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.getParameterMap().put("NullField", null); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + event.getParameterMap().remove("NullField"); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.getParameterMap().put("NullField", eventField); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + event.getParameterMap().remove("NullField"); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.getParameterMap().put("BadParent", eventFieldBadParent); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + event.getParameterMap().remove("BadParent"); + result = new AxValidationResult(); + result = event.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + event.clean(); + event.afterUnmarshal(null, null); + + final AxEvent clonedEvent = new AxEvent(event); + assertEquals("AxEvent:(key=AxArtifactKey:(name=EventName,version=0.0.1),nameSpace=namespace", + clonedEvent.toString().substring(0, 77)); + + assertFalse(event.hashCode() == 0); + + assertTrue(event.equals(event)); + assertTrue(event.equals(clonedEvent)); + assertFalse(event.equals(null)); + assertFalse(event.equals("Hello")); + assertFalse( + event.equals(new AxEvent(AxArtifactKey.getNullKey(), "namespace", "source", "target", parameterMap))); + assertFalse(event.equals(new AxEvent(eventKey, "namespace1", "source", "target", parameterMap))); + assertFalse(event.equals(new AxEvent(eventKey, "namespace", "source2", "target", parameterMap))); + assertFalse(event.equals(new AxEvent(eventKey, "namespace", "source", "target3", parameterMap))); + assertFalse(event.equals(new AxEvent(eventKey, "namespace", "source", "target", parameterMapEmpty))); + assertTrue(event.equals(new AxEvent(eventKey, "namespace", "source", "target", parameterMap))); + + assertEquals(0, event.compareTo(event)); + assertEquals(0, event.compareTo(clonedEvent)); + assertNotEquals(0, event.compareTo(new AxArtifactKey())); + assertNotEquals(0, event.compareTo(null)); + assertNotEquals(0, event + .compareTo(new AxEvent(AxArtifactKey.getNullKey(), "namespace", "source", "target", parameterMap))); + assertNotEquals(0, event.compareTo(new AxEvent(eventKey, "namespace1", "source", "target", parameterMap))); + assertNotEquals(0, event.compareTo(new AxEvent(eventKey, "namespace", "source2", "target", parameterMap))); + assertNotEquals(0, event.compareTo(new AxEvent(eventKey, "namespace", "source", "target3", parameterMap))); + assertNotEquals(0, event.compareTo(new AxEvent(eventKey, "namespace", "source", "target", parameterMapEmpty))); + assertEquals(0, event.compareTo(new AxEvent(eventKey, "namespace", "source", "target", parameterMap))); + + assertNotNull(event.getKeys()); + + final AxEvents events = new AxEvents(); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + // Invalid, no events in event map + events.setKey(new AxArtifactKey("EventsKey", "0.0.1")); + assertEquals("EventsKey:0.0.1", events.getKey().getID()); + + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + events.getEventMap().put(eventKey, event); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + events.getEventMap().put(AxArtifactKey.getNullKey(), null); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + events.getEventMap().remove(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + events.getEventMap().put(new AxArtifactKey("NullValueKey", "0.0.1"), null); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + events.getEventMap().remove(new AxArtifactKey("NullValueKey", "0.0.1")); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + events.getEventMap().put(new AxArtifactKey("BadEventKey", "0.0.1"), event); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + events.getEventMap().remove(new AxArtifactKey("BadEventKey", "0.0.1")); + result = new AxValidationResult(); + result = events.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + events.clean(); + events.afterUnmarshal(null, null); + + final AxEvents clonedEvents = new AxEvents(events); + assertEquals("AxEvents:(key=AxArtifactKey:(name=EventsKey,version=0.0.1),e", + clonedEvents.toString().substring(0, 60)); + + assertFalse(events.hashCode() == 0); + + assertTrue(events.equals(events)); + assertTrue(events.equals(clonedEvents)); + assertFalse(events.equals(null)); + assertFalse(events.equals("Hello")); + assertFalse(events.equals(new AxEvents(new AxArtifactKey()))); + + assertEquals(0, events.compareTo(events)); + assertEquals(0, events.compareTo(clonedEvents)); + assertNotEquals(0, events.compareTo(null)); + assertNotEquals(0, events.compareTo(new AxArtifactKey())); + assertNotEquals(0, events.compareTo(new AxEvents(new AxArtifactKey()))); + + clonedEvents.get(eventKey).setSource("AnotherSource"); + assertNotEquals(0, events.compareTo(clonedEvents)); + + assertEquals(events.getKey(), events.getKeys().get(0)); + + assertEquals("EventName", events.get("EventName").getKey().getName()); + assertEquals("EventName", events.get("EventName", "0.0.1").getKey().getName()); + assertEquals(1, events.getAll("EventName", "0.0.1").size()); + assertEquals(0, events.getAll("NonExistantEventsName").size()); + } +} diff --git a/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestField.java b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestField.java new file mode 100644 index 000000000..11b8b745e --- /dev/null +++ b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/concepts/TestField.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; +import org.onap.policy.apex.model.eventmodel.concepts.AxInputField; +import org.onap.policy.apex.model.eventmodel.concepts.AxOutputField; + +/** + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestField { + + @Test + public void testField() { + assertNotNull(new AxField()); + assertNotNull(new AxField(new AxReferenceKey())); + assertNotNull(new AxField(new AxReferenceKey(), new AxArtifactKey())); + assertNotNull(new AxField(new AxReferenceKey(), new AxArtifactKey(), false)); + assertNotNull(new AxField("LocalName", new AxArtifactKey(), false)); + assertNotNull(new AxField("LocalName", new AxArtifactKey())); + assertNotNull(new AxField("LocalName", new AxArtifactKey(), false)); + + assertNotNull(new AxInputField()); + assertNotNull(new AxInputField(new AxReferenceKey())); + assertNotNull(new AxInputField(new AxReferenceKey(), new AxArtifactKey())); + assertNotNull(new AxInputField(new AxReferenceKey(), new AxArtifactKey(), true)); + assertNotNull(new AxInputField("LocalName", new AxArtifactKey())); + assertNotNull(new AxInputField(new AxInputField())); + + assertNotNull(new AxOutputField()); + assertNotNull(new AxOutputField(new AxReferenceKey())); + assertNotNull(new AxOutputField(new AxReferenceKey(), new AxArtifactKey())); + assertNotNull(new AxOutputField(new AxReferenceKey(), new AxArtifactKey(), false)); + assertNotNull(new AxOutputField("LocalName", new AxArtifactKey())); + assertNotNull(new AxOutputField(new AxOutputField())); + + final AxField field = new AxField(); + + final AxReferenceKey fieldKey = new AxReferenceKey("FieldName", "0.0.1", "PLN", "LN"); + field.setKey(fieldKey); + assertEquals("FieldName:0.0.1:PLN:LN", field.getKey().getID()); + assertEquals("FieldName:0.0.1:PLN:LN", field.getKeys().get(0).getID()); + + final AxArtifactKey schemaKey = new AxArtifactKey("SchemaName", "0.0.1"); + field.setSchema(schemaKey); + assertEquals("SchemaName:0.0.1", field.getSchema().getID()); + + assertEquals(false, field.getOptional()); + field.setOptional(true); + assertEquals(true, field.getOptional()); + + AxValidationResult result = new AxValidationResult(); + result = field.validate(result); + assertEquals(AxValidationResult.ValidationResult.VALID, result.getValidationResult()); + + field.setKey(AxReferenceKey.getNullKey()); + result = new AxValidationResult(); + result = field.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + field.setKey(fieldKey); + result = new AxValidationResult(); + result = field.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + field.setSchema(AxArtifactKey.getNullKey()); + result = new AxValidationResult(); + result = field.validate(result); + assertEquals(ValidationResult.INVALID, result.getValidationResult()); + + field.setSchema(schemaKey); + result = new AxValidationResult(); + result = field.validate(result); + assertEquals(ValidationResult.VALID, result.getValidationResult()); + + field.clean(); + + final AxField clonedField = new AxField(field); + assertEquals( + "AxField:(key=AxReferenceKey:(parentKeyName=FieldName,parentKeyVersion=0.0.1,parentLocalName=PLN,localName=LN),fieldSchemaKey=AxArtifactKey:(name=SchemaName,version=0.0.1),optional=true)", + clonedField.toString()); + + assertFalse(field.hashCode() == 0); + + assertTrue(field.equals(field)); + assertTrue(field.equals(clonedField)); + assertFalse(field.equals(null)); + assertFalse(field.equals("Hello")); + assertFalse(field.equals(new AxField(AxReferenceKey.getNullKey(), AxArtifactKey.getNullKey(), false))); + assertFalse(field.equals(new AxField(fieldKey, AxArtifactKey.getNullKey(), false))); + assertFalse(field.equals(new AxField(fieldKey, schemaKey, false))); + assertTrue(field.equals(new AxField(fieldKey, schemaKey, true))); + + assertEquals(0, field.compareTo(field)); + assertEquals(0, field.compareTo(clonedField)); + assertNotEquals(0, field.compareTo(new AxArtifactKey())); + assertNotEquals(0, field.compareTo(null)); + assertNotEquals(0, + field.compareTo(new AxField(AxReferenceKey.getNullKey(), AxArtifactKey.getNullKey(), false))); + assertNotEquals(0, field.compareTo(new AxField(fieldKey, AxArtifactKey.getNullKey(), false))); + assertNotEquals(0, field.compareTo(new AxField(fieldKey, schemaKey, false))); + assertEquals(0, field.compareTo(new AxField(fieldKey, schemaKey, true))); + + assertNotNull(field.getKeys()); + } +} diff --git a/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModel.java b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModel.java new file mode 100644 index 000000000..ee2638a54 --- /dev/null +++ b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModel.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.handling; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DAOParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.eventmodel.concepts.AxEventModel; + +public class TestApexEventModel { + private Connection connection; + TestApexModel testApexModel; + + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel(AxEventModel.class, new TestApexEventModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testApexModelVaidateObservation() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateObservation(); + assertTrue(result.toString().equals(OBSERVATION_MODEL_STRING)); + } + + @Test + public void testApexModelVaidateWarning() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateWarning(); + assertTrue(result.toString().equals(WARNING_MODEL_STRING)); + } + + @Test + public void testModelVaidateInvalidModel() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateInvalidModel(); + assertTrue(result.toString().equals(INVALID_MODEL_STRING)); + } + + @Test + public void testModelVaidateMalstructured() throws Exception { + final AxValidationResult result = testApexModel.testApexModelVaidateMalstructured(); + assertTrue(result.toString().equals(INVALID_MODEL_MALSTRUCTURED_STRING)); + } + + @Test + public void testModelWriteReadXML() throws Exception { + testApexModel.testApexModelWriteReadXML(); + } + + @Test + public void testModelWriteReadJSON() throws Exception { + testApexModel.testApexModelWriteReadJSON(); + } + + @Test + public void testModelWriteReadJPA() throws Exception { + final DAOParameters daoParameters = new DAOParameters(); + daoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + daoParameters.setPersistenceUnit("DAOTest"); + + testApexModel.testApexModelWriteReadJPA(daoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; + + private static final String OBSERVATION_MODEL_STRING = "\n" + + "***observations noted during validation of model***\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event2,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event2,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "********************************"; + + private static final String WARNING_MODEL_STRING = "\n" + "***warnings issued during validation of model***\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:WARNING:nameSpace on event is blank\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:WARNING:nameSpace on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event2,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:WARNING:nameSpace on event is blank\n" + + "AxArtifactKey:(name=event2,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event2,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "********************************"; + + private static final String INVALID_MODEL_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation:INVALID:keyInfoMap may not be empty\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=smallEventModel,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=Schemas,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=BigIntType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=BooleanType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=IntType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=MapType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=SetType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=StringType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=smallEventMap,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=event0,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par0)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par2)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par3)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par4)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par5)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=par6)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=event1,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:duplicate key AxArtifactKey:(name=event1,version=0.0.1) found\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=event1,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:duplicate key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar) found\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar)\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event0,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:INVALID:parent key on parameter field AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar) does not equal event key\n" + + "AxArtifactKey:(name=smallEventMap,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvents:INVALID:key on event entry key AxArtifactKey:(name=event2,version=0.0.1) does not equal event value key AxArtifactKey:(name=event1,version=0.0.1)\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:INVALID:parent key on parameter field AxReferenceKey:(parentKeyName=event0,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar) does not equal event key\n" + + "********************************"; + + private static final String INVALID_MODEL_MALSTRUCTURED_STRING = "\n" + "***validation of model failed***\n" + + "AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1):org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation:INVALID:keyInfoMap may not be empty\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=smallEventModel,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=KeyInfoMapKey,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=Schemas,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=SetType,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=smallEventMap,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=event1,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event1,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:duplicate key AxArtifactKey:(name=event1,version=0.0.1) found\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for key AxArtifactKey:(name=event1,version=0.0.1)\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:duplicate key AxReferenceKey:(parentKeyName=event1,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar) found\n" + + "AxArtifactKey:(name=smallEventModel,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEventModel:INVALID:key information not found for parent key of key AxReferenceKey:(parentKeyName=event1,parentKeyVersion=0.0.1,parentLocalName=NULL,localName=theOnlyPar)\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "AxArtifactKey:(name=smallEventMap,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvents:INVALID:key on event entry key AxArtifactKey:(name=event2,version=0.0.1) does not equal event value key AxArtifactKey:(name=event1,version=0.0.1)\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:source on event is blank\n" + + "AxArtifactKey:(name=event1,version=0.0.1):org.onap.policy.apex.model.eventmodel.concepts.AxEvent:OBSERVATION:target on event is blank\n" + + "********************************"; +} diff --git a/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModelCreator.java b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModelCreator.java new file mode 100644 index 000000000..039d2305b --- /dev/null +++ b/model/event-model/src/test/java/org/onap/policy/apex/model/eventmodel/handling/TestApexEventModelCreator.java @@ -0,0 +1,309 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.model.eventmodel.handling; + +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEventModel; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; + +public class TestApexEventModelCreator implements TestApexModelCreator { + + @Override + public AxEventModel getModel() { + final AxContextSchema axSchema0 = + new AxContextSchema(new AxArtifactKey("BooleanType", "0.0.1"), "Java", "java.lang.Boolean"); + final AxContextSchema axSchema1 = + new AxContextSchema(new AxArtifactKey("IntType", "0.0.1"), "Java", "java.lang.Integer"); + final AxContextSchema axSchema2 = + new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", "java.lang.String"); + final AxContextSchema axSchema3 = new AxContextSchema(new AxArtifactKey("KeyType", "0.0.1"), "Java", + "org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey"); + final AxContextSchema axSchema4 = new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", + "org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation"); + final AxContextSchema axSchema5 = + new AxContextSchema(new AxArtifactKey("BigIntType", "0.0.1"), "Java", "java.math.BigInteger"); + final AxContextSchema axSchema6 = new AxContextSchema(new AxArtifactKey("ModelType", "0.0.1"), "Java", + "org.onap.policy.apex.model.basicmodel.concepts.AxModel"); + + final AxContextSchemas dataTypes = new AxContextSchemas(new AxArtifactKey("Schemas", "0.0.1")); + dataTypes.getSchemasMap().put(axSchema0.getKey(), axSchema0); + dataTypes.getSchemasMap().put(axSchema1.getKey(), axSchema1); + dataTypes.getSchemasMap().put(axSchema2.getKey(), axSchema2); + dataTypes.getSchemasMap().put(axSchema3.getKey(), axSchema3); + dataTypes.getSchemasMap().put(axSchema4.getKey(), axSchema4); + dataTypes.getSchemasMap().put(axSchema5.getKey(), axSchema5); + dataTypes.getSchemasMap().put(axSchema6.getKey(), axSchema6); + + final AxEvents eventMap = new AxEvents(new AxArtifactKey("smallEventMap", "0.0.1")); + + final AxEvent event0 = new AxEvent(new AxArtifactKey("event0", "0.0.1"), + "org.onap.policy.apex.model.eventmodel.events", "Source", "Target"); + event0.getParameterMap().put("par0", + new AxField(new AxReferenceKey(event0.getKey(), "par0"), axSchema0.getKey())); + event0.getParameterMap().put("par1", + new AxField(new AxReferenceKey(event0.getKey(), "par1"), axSchema1.getKey())); + event0.getParameterMap().put("par2", + new AxField(new AxReferenceKey(event0.getKey(), "par2"), axSchema2.getKey())); + event0.getParameterMap().put("par3", + new AxField(new AxReferenceKey(event0.getKey(), "par3"), axSchema6.getKey())); + event0.getParameterMap().put("par4", + new AxField(new AxReferenceKey(event0.getKey(), "par4"), axSchema4.getKey())); + event0.getParameterMap().put("par5", + new AxField(new AxReferenceKey(event0.getKey(), "par5"), axSchema5.getKey())); + event0.getParameterMap().put("par6", + new AxField(new AxReferenceKey(event0.getKey(), "par6"), axSchema5.getKey())); + eventMap.getEventMap().put(event0.getKey(), event0); + + final AxEvent event1 = new AxEvent(new AxArtifactKey("event1", "0.0.1"), + "org.onap.policy.apex.model.eventmodel.events", "Source", "Target"); + event1.getParameterMap().put("theOnlyPar", + new AxField(new AxReferenceKey(event1.getKey(), "theOnlyPar"), axSchema3.getKey())); + eventMap.getEventMap().put(event1.getKey(), event1); + + final AxEvent event2 = new AxEvent(new AxArtifactKey("event2", "0.0.1"), + "org.onap.policy.apex.model.eventmodel.events", "Source", "Target"); + eventMap.getEventMap().put(event2.getKey(), event2); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); + + final AxEventModel eventModel = + new AxEventModel(new AxArtifactKey("EventModel", "0.0.1"), dataTypes, keyInformation, eventMap); + keyInformation.generateKeyInfo(eventModel); + + eventModel.validate(new AxValidationResult()); + return eventModel; + } + + @Override + public AxEventModel getInvalidModel() { + final AxContextSchema axSchema0 = + new AxContextSchema(new AxArtifactKey("BooleanType", "0.0.1"), "Java", "java.lang.Zoolean"); + final AxContextSchema axSchema1 = + new AxContextSchema(new AxArtifactKey("IntType", "0.0.1"), "Java", "java.lang.Integer"); + final AxContextSchema axSchema2 = + new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", "java.lang.String"); + final AxContextSchema axSchema3 = + new AxContextSchema(new AxArtifactKey("SetType", "0.0.1"), "Java", "java.util.Set"); + final AxContextSchema axSchema4 = + new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", "java.util.Map"); + final AxContextSchema axSchema5 = + new AxContextSchema(new AxArtifactKey("BigIntType", "0.0.1"), "Java", "java.math.BigInteger"); + + final AxContextSchemas dataTypes = new AxContextSchemas(new AxArtifactKey("Schemas", "0.0.1")); + dataTypes.getSchemasMap().put(axSchema0.getKey(), axSchema0); + dataTypes.getSchemasMap().put(axSchema1.getKey(), axSchema1); + dataTypes.getSchemasMap().put(axSchema2.getKey(), axSchema2); + dataTypes.getSchemasMap().put(axSchema3.getKey(), axSchema3); + dataTypes.getSchemasMap().put(axSchema4.getKey(), axSchema4); + dataTypes.getSchemasMap().put(axSchema5.getKey(), axSchema5); + + final AxEvents eventMap = new AxEvents(new AxArtifactKey("smallEventMap", "0.0.1")); + + final AxEvent event0 = + new AxEvent(new AxArtifactKey("event0", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + event0.getParameterMap().put("par0", + new AxField(new AxReferenceKey(event0.getKey(), "par0"), axSchema0.getKey())); + event0.getParameterMap().put("par1", + new AxField(new AxReferenceKey(event0.getKey(), "par1"), axSchema1.getKey())); + event0.getParameterMap().put("par2", + new AxField(new AxReferenceKey(event0.getKey(), "par2"), axSchema2.getKey())); + event0.getParameterMap().put("par3", + new AxField(new AxReferenceKey(event0.getKey(), "par3"), axSchema3.getKey())); + event0.getParameterMap().put("par4", + new AxField(new AxReferenceKey(event0.getKey(), "par4"), axSchema4.getKey())); + event0.getParameterMap().put("par5", + new AxField(new AxReferenceKey(event0.getKey(), "par5"), axSchema5.getKey())); + event0.getParameterMap().put("par6", + new AxField(new AxReferenceKey(event0.getKey(), "par6"), axSchema5.getKey())); + eventMap.getEventMap().put(event0.getKey(), event0); + + final AxEvent event1 = + new AxEvent(new AxArtifactKey("event1", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + event1.getParameterMap().put("theOnlyPar", + new AxField(new AxReferenceKey(event0.getKey(), "theOnlyPar"), axSchema3.getKey())); + eventMap.getEventMap().put(event1.getKey(), event1); + + final AxEvent event2 = + new AxEvent(new AxArtifactKey("event2", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + eventMap.getEventMap().put(event2.getKey(), event1); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); + + final AxEventModel eventModel = + new AxEventModel(new AxArtifactKey("smallEventModel", "0.0.1"), dataTypes, keyInformation, eventMap); + + return eventModel; + } + + @Override + public AxEventModel getMalstructuredModel() { + final AxContextSchema axSchema3 = + new AxContextSchema(new AxArtifactKey("SetType", "0.0.1"), "Java", "java.util.Set"); + final AxContextSchemas dataTypes = new AxContextSchemas(new AxArtifactKey("Schemas", "0.0.1")); + dataTypes.getSchemasMap().put(axSchema3.getKey(), axSchema3); + + final AxEvents eventMap = new AxEvents(new AxArtifactKey("smallEventMap", "0.0.1")); + + final AxEvent event1 = + new AxEvent(new AxArtifactKey("event1", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + event1.getParameterMap().put("theOnlyPar", + new AxField(new AxReferenceKey(event1.getKey(), "theOnlyPar"), axSchema3.getKey())); + eventMap.getEventMap().put(event1.getKey(), event1); + + final AxEvent event2 = + new AxEvent(new AxArtifactKey("event2", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + eventMap.getEventMap().put(event2.getKey(), event1); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); + + final AxEventModel eventModel = + new AxEventModel(new AxArtifactKey("smallEventModel", "0.0.1"), dataTypes, keyInformation, eventMap); + + eventModel.validate(new AxValidationResult()); + + return eventModel; + } + + @Override + public AxEventModel getWarningModel() { + final AxContextSchema axSchema0 = + new AxContextSchema(new AxArtifactKey("BooleanType", "0.0.1"), "Java", "java.lang.Boolean"); + final AxContextSchema axSchema1 = + new AxContextSchema(new AxArtifactKey("IntType", "0.0.1"), "Java", "java.lang.Integer"); + final AxContextSchema axSchema2 = + new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", "java.lang.String"); + final AxContextSchema axSchema3 = + new AxContextSchema(new AxArtifactKey("SetType", "0.0.1"), "Java", "java.util.Set"); + final AxContextSchema axSchema4 = + new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", "java.util.Map"); + final AxContextSchema axSchema5 = + new AxContextSchema(new AxArtifactKey("BigIntType", "0.0.1"), "Java", "java.math.BigInteger"); + final AxContextSchemas dataTypes = new AxContextSchemas(new AxArtifactKey("Schemas", "0.0.1")); + dataTypes.getSchemasMap().put(axSchema0.getKey(), axSchema0); + dataTypes.getSchemasMap().put(axSchema1.getKey(), axSchema1); + dataTypes.getSchemasMap().put(axSchema2.getKey(), axSchema2); + dataTypes.getSchemasMap().put(axSchema3.getKey(), axSchema3); + dataTypes.getSchemasMap().put(axSchema4.getKey(), axSchema4); + dataTypes.getSchemasMap().put(axSchema5.getKey(), axSchema5); + + final AxEvents eventMap = new AxEvents(new AxArtifactKey("smallEventMap", "0.0.1")); + + final AxEvent event0 = new AxEvent(new AxArtifactKey("event0", "0.0.1"), ""); + event0.getParameterMap().put("par0", + new AxField(new AxReferenceKey(event0.getKey(), "par0"), axSchema0.getKey())); + event0.getParameterMap().put("par1", + new AxField(new AxReferenceKey(event0.getKey(), "par1"), axSchema1.getKey())); + event0.getParameterMap().put("par2", + new AxField(new AxReferenceKey(event0.getKey(), "par2"), axSchema2.getKey())); + event0.getParameterMap().put("par3", + new AxField(new AxReferenceKey(event0.getKey(), "par3"), axSchema3.getKey())); + event0.getParameterMap().put("par4", + new AxField(new AxReferenceKey(event0.getKey(), "par4"), axSchema4.getKey())); + event0.getParameterMap().put("par5", + new AxField(new AxReferenceKey(event0.getKey(), "par5"), axSchema5.getKey())); + eventMap.getEventMap().put(event0.getKey(), event0); + + final AxEvent event1 = new AxEvent(new AxArtifactKey("event1", "0.0.1"), ""); + event1.getParameterMap().put("theOnlyPar", + new AxField(new AxReferenceKey(event1.getKey(), "theOnlyPar"), axSchema3.getKey())); + eventMap.getEventMap().put(event1.getKey(), event1); + + final AxEvent event2 = new AxEvent(new AxArtifactKey("event2", "0.0.1"), ""); + eventMap.getEventMap().put(event2.getKey(), event2); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); + + final AxEventModel eventModel = + new AxEventModel(new AxArtifactKey("smallEventModel", "0.0.1"), dataTypes, keyInformation, eventMap); + eventModel.getKeyInformation().generateKeyInfo(eventModel); + eventModel.validate(new AxValidationResult()); + + return eventModel; + } + + @Override + public AxEventModel getObservationModel() { + final AxContextSchema axSchema0 = + new AxContextSchema(new AxArtifactKey("BooleanType", "0.0.1"), "Java", "java.lang.Boolean"); + final AxContextSchema axSchema1 = + new AxContextSchema(new AxArtifactKey("IntType", "0.0.1"), "Java", "java.lang.Integer"); + final AxContextSchema axSchema2 = + new AxContextSchema(new AxArtifactKey("StringType", "0.0.1"), "Java", "java.lang.String"); + final AxContextSchema axSchema3 = + new AxContextSchema(new AxArtifactKey("SetType", "0.0.1"), "Java", "java.util.Set"); + final AxContextSchema axSchema4 = + new AxContextSchema(new AxArtifactKey("MapType", "0.0.1"), "Java", "java.util.Map"); + final AxContextSchema axSchema5 = + new AxContextSchema(new AxArtifactKey("BigIntType", "0.0.1"), "Java", "java.math.BigInteger"); + final AxContextSchemas schemas = new AxContextSchemas(new AxArtifactKey("Schemas", "0.0.1")); + schemas.getSchemasMap().put(axSchema0.getKey(), axSchema0); + schemas.getSchemasMap().put(axSchema1.getKey(), axSchema1); + schemas.getSchemasMap().put(axSchema2.getKey(), axSchema2); + schemas.getSchemasMap().put(axSchema3.getKey(), axSchema3); + schemas.getSchemasMap().put(axSchema4.getKey(), axSchema4); + schemas.getSchemasMap().put(axSchema5.getKey(), axSchema5); + + final AxEvents eventMap = new AxEvents(new AxArtifactKey("smallEventMap", "0.0.1")); + + final AxEvent event0 = + new AxEvent(new AxArtifactKey("event0", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + event0.getParameterMap().put("par0", + new AxField(new AxReferenceKey(event0.getKey(), "par0"), axSchema0.getKey())); + event0.getParameterMap().put("par1", + new AxField(new AxReferenceKey(event0.getKey(), "par1"), axSchema1.getKey())); + event0.getParameterMap().put("par2", + new AxField(new AxReferenceKey(event0.getKey(), "par2"), axSchema2.getKey())); + event0.getParameterMap().put("par3", + new AxField(new AxReferenceKey(event0.getKey(), "par3"), axSchema3.getKey())); + event0.getParameterMap().put("par4", + new AxField(new AxReferenceKey(event0.getKey(), "par4"), axSchema4.getKey())); + event0.getParameterMap().put("par5", + new AxField(new AxReferenceKey(event0.getKey(), "par5"), axSchema5.getKey())); + eventMap.getEventMap().put(event0.getKey(), event0); + + final AxEvent event1 = + new AxEvent(new AxArtifactKey("event1", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + event1.getParameterMap().put("theOnlyPar", + new AxField(new AxReferenceKey(event1.getKey(), "theOnlyPar"), axSchema3.getKey())); + eventMap.getEventMap().put(event1.getKey(), event1); + + final AxEvent event2 = + new AxEvent(new AxArtifactKey("event2", "0.0.1"), "org.onap.policy.apex.model.eventmodel.events"); + eventMap.getEventMap().put(event2.getKey(), event2); + + final AxKeyInformation keyInformation = new AxKeyInformation(new AxArtifactKey("KeyInfoMapKey", "0.0.1")); + + final AxEventModel eventModel = + new AxEventModel(new AxArtifactKey("smallEventModel", "0.0.1"), schemas, keyInformation, eventMap); + eventModel.getKeyInformation().generateKeyInfo(eventModel); + eventModel.validate(new AxValidationResult()); + + return eventModel; + } +} diff --git a/model/event-model/src/test/resources/META-INF/persistence.xml b/model/event-model/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..db32612ab --- /dev/null +++ b/model/event-model/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,56 @@ + + + + + + org.eclipse.persistence.jpa.PersistenceProvider + + org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner + org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String + org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey + org.onap.policy.apex.model.basicmodel.concepts.AxConcept + org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo + org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation + org.onap.policy.apex.model.basicmodel.concepts.AxModel + org.onap.policy.apex.model.basicmodel.concepts.TestEntity + org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema + org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas + org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum + org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums + org.onap.policy.apex.model.contextmodel.concepts.AxContextModel + org.onap.policy.apex.model.eventmodel.concepts.AxField + org.onap.policy.apex.model.eventmodel.concepts.AxInputField + org.onap.policy.apex.model.eventmodel.concepts.AxOutputField + org.onap.policy.apex.model.eventmodel.concepts.AxEvent + org.onap.policy.apex.model.eventmodel.concepts.AxEvents + org.onap.policy.apex.model.eventmodel.concepts.AxEventModel + + + + + + + + + + + + diff --git a/model/event-model/src/test/resources/logback-test.xml b/model/event-model/src/test/resources/logback-test.xml new file mode 100644 index 000000000..dfafb04d9 --- /dev/null +++ b/model/event-model/src/test/resources/logback-test.xml @@ -0,0 +1,74 @@ + + + + + + Apex + + + + + + + %d %contextName [%t] %level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + ${LOG_DIR}/apex.log + + %d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full} + + + + + ${LOG_DIR}/apex_ctxt.log + + %d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full} + + + + + + + + + + + diff --git a/model/pom.xml b/model/pom.xml index 722a44276..5e6a52ad5 100644 --- a/model/pom.xml +++ b/model/pom.xml @@ -25,7 +25,7 @@ apex-pdp 2.0.0-SNAPSHOT - + org.onap.policy.apex-pdp.model model pom @@ -33,9 +33,19 @@ ${project.artifactId} The model for Apex, it comtains definitions of all Apex concepts and also has handling for Apex models. + + + org.apache.derby + derby + ${version.derby} + test + + + utilities basic-model context-model + event-model \ No newline at end of file diff --git a/pom.xml b/pom.xml index 24ac99feb..fecf5e8af 100644 --- a/pom.xml +++ b/pom.xml @@ -33,12 +33,13 @@ 2.0.0-SNAPSHOT pom - Apex PDP engine + policy-apex-pdp Packaging for all the Apex components, the engine, the WAR service, and the editor. UTF-8 UTF-8 + 10.13.1.1 -- cgit 1.2.3-korg