diff options
141 files changed, 5261 insertions, 1177 deletions
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java b/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java index 65a28cffe..2576aab0a 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java @@ -33,6 +33,7 @@ import java.util.TreeMap; import javax.persistence.CascadeType; import javax.persistence.EmbeddedId; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.ws.rs.core.Response; @@ -69,7 +70,7 @@ public class PfConceptContainer<C extends PfConcept, A extends PfNameVersion> ex @EmbeddedId private PfConceptKey key; - @ManyToMany(cascade = CascadeType.ALL) + @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) private Map<PfConceptKey, C> conceptMap; /** diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfObjectFilter.java b/models-base/src/main/java/org/onap/policy/models/base/PfObjectFilter.java index 10ce4ea60..f4e457192 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfObjectFilter.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfObjectFilter.java @@ -24,8 +24,9 @@ package org.onap.policy.models.base; import java.util.ArrayList; import java.util.Collections; import java.util.List; - -import lombok.NonNull; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Pattern; /** * Interface for filtering a list of concepts. @@ -43,14 +44,74 @@ public interface PfObjectFilter<T extends Comparable<T>> { public List<T> filter(final List<T> originalList); /** - * Check if a value matches a regular expression. + * Check if a value exactly equals some text. * * @param value the incoming value to check - * @param pattern the pattern to check against + * @param text the desired text to check against * @return match or not */ - public default boolean filterString(final String value, final String pattern) { - return value == null || pattern == null || value.equals(pattern); + public default boolean filterString(final String value, final String text) { + return value == null || text == null || value.equals(text); + } + + /** + * Gets a predicate used to filter an item in a list by exactly matching an extracted value + * with some text. + * + * @param text the desired text to check against, or {@code null} if to accept everything + * @param extractor function to extract the value, to be matched, from a list item + * @return a predicate to match a value from a list item + */ + public default Predicate<T> filterStringPred(final String text, Function<T, String> extractor) { + // if null text, then everything matches + if (text == null) { + return item -> true; + } + + return item -> text.equals(extractor.apply(item)); + } + + /** + * Gets a predicate used to filter an item in a list by comparing the start of an + * extracted value with a prefix. + * + * @param prefix the desired prefix to check against, or {@code null} if to accept + * everything + * @param extractor function to extract the value, to be matched, from a list item + * @return a predicate to match a prefix with a value from a list item + */ + public default Predicate<T> filterPrefixPred(final String prefix, Function<T, String> extractor) { + // if null prefix, then everything matches + if (prefix == null) { + return item -> true; + } + + return item -> { + String value = extractor.apply(item); + return (value != null && value.startsWith(prefix)); + }; + } + + /** + * Gets a predicate used to filter an item in a list by matching an extracted value + * with a regular expression. + * + * @param pattern regular expression to match, or {@code null} if to accept everything + * @param extractor function to extract the value, to be matched, from a list item + * @return a predicate to match a value from a list item using a regular expression + */ + public default Predicate<T> filterRegexpPred(final String pattern, Function<T, String> extractor) { + // if null pattern, then everything matches + if (pattern == null) { + return item -> true; + } + + Pattern pat = Pattern.compile(pattern); + + return item -> { + String value = extractor.apply(item); + return (value != null && pat.matcher(value).matches()); + }; } /** diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java index c13140726..291a7d402 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java +++ b/models-base/src/test/java/org/onap/policy/models/base/PfObjectFilterTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. @@ -20,14 +21,15 @@ package org.onap.policy.models.base; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; - +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; import org.junit.Test; import org.onap.policy.models.base.testconcepts.DummyPfObject; @@ -101,5 +103,51 @@ public class PfObjectFilterTest { latestVersionList.remove(1); List<DummyPfObject> newestVersionList = dof.latestVersionFilter(latestVersionList); assertEquals(latestVersionList, newestVersionList); + + MyFilter filter = new MyFilter(); + + assertEquals(true, filter.filterString(null, "Hello")); + + DummyPfObject doNullVersion = new DummyPfObject(); + do5.setName("bbbbb"); + + assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, doNullVersion, "1.0.0")); + assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, "1")); + assertEquals(false, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, "2.0.0")); + assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, doNullVersion, null)); + assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, null)); + assertEquals(true, filter(filter::filterStringPred, DummyPfObject::getVersion, do0, "1.0.0")); + + assertEquals(false, filter(filter::filterPrefixPred, DummyPfObject::getVersion, doNullVersion, "1.")); + assertEquals(false, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.1")); + assertEquals(false, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.1")); + assertEquals(false, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "2")); + assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, doNullVersion, null)); + assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, null)); + assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.")); + assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.0.")); + assertEquals(true, filter(filter::filterPrefixPred, DummyPfObject::getVersion, do0, "1.0.0")); + + assertEquals(false, filter(filter::filterRegexpPred, DummyPfObject::getVersion, doNullVersion, "1[.].*")); + assertEquals(false, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, "2[.].*")); + assertEquals(true, filter(filter::filterRegexpPred, DummyPfObject::getVersion, doNullVersion, null)); + assertEquals(true, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, null)); + assertEquals(true, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, "1[.].*")); + assertEquals(true, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, "1[.]0[.].*")); + assertEquals(true, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, "1[.]0[.]0")); + assertEquals(true, filter(filter::filterRegexpPred, DummyPfObject::getVersion, do0, "1....")); + } + + private boolean filter(BiFunction<String, Function<DummyPfObject, String>, Predicate<DummyPfObject>> predMaker, + Function<DummyPfObject, String> extractor, DummyPfObject dpo, String text) { + Predicate<DummyPfObject> pred = predMaker.apply(text, extractor); + return pred.test(dpo); + } + + private static class MyFilter implements PfObjectFilter<DummyPfObject> { + @Override + public List<DummyPfObject> filter(List<DummyPfObject> originalList) { + return null; + } } } diff --git a/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java b/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java index 182017693..c44d05fe2 100644 --- a/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java +++ b/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java @@ -173,7 +173,7 @@ public class DefaultPfDao implements PfDao { mg.getTransaction().begin(); mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass) .setParameter(NAME, key.getName()) - .setParameter("version", key.getVersion()) + .setParameter(VERSION, key.getVersion()) .executeUpdate(); mg.getTransaction().commit(); // @formatter:on @@ -250,7 +250,7 @@ public class DefaultPfDao implements PfDao { for (final PfConceptKey key : keys) { deletedCount += mg.createQuery(setQueryTable(DELETE_BY_CONCEPT_KEY, someClass), someClass) .setParameter(NAME, key.getName()) - .setParameter("version", key.getVersion()) + .setParameter(VERSION, key.getVersion()) .executeUpdate(); } mg.getTransaction().commit(); diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java b/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java index 4bf39a059..74d06369a 100644 --- a/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java +++ b/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java @@ -26,16 +26,14 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.sql.Connection; -import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; +import java.util.Properties; import java.util.Set; import java.util.TreeSet; import java.util.UUID; -import org.junit.After; -import org.junit.Before; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; @@ -49,23 +47,22 @@ import org.onap.policy.models.dao.impl.DefaultPfDao; * JUnit test class. */ public class EntityTest { - private Connection connection; private PfDao pfDao; - @Before - public void setup() throws Exception { - connection = DriverManager.getConnection("jdbc:h2:mem:test"); - } - - @After - public void teardown() throws Exception { - connection.close(); - } - @Test public void testEntityTestSanity() throws PfModelException { final DaoParameters daoParameters = new DaoParameters(); + Properties jdbcProperties = new Properties(); + // @formatter:off + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "sa"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, ""); + // @formatter:on + + daoParameters.setJdbcProperties(jdbcProperties); + pfDao = new PfDaoFactory().createPfDao(daoParameters); try { @@ -101,10 +98,19 @@ public class EntityTest { @Test public void testEntityTestAllOpsJpa() throws PfModelException { + final DaoParameters daoParameters = new DaoParameters(); daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); daoParameters.setPersistenceUnit("DaoTest"); + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty("javax.persistence.jdbc.driver", "org.h2.Driver"); + jdbcProperties.setProperty("javax.persistence.jdbc.url", "jdbc:h2:mem:testdb"); + jdbcProperties.setProperty("javax.persistence.jdbc.user", "sa"); + jdbcProperties.setProperty("javax.persistence.jdbc.password", ""); + + daoParameters.setJdbcProperties(jdbcProperties); + pfDao = new PfDaoFactory().createPfDao(daoParameters); pfDao.init(daoParameters); diff --git a/models-dao/src/test/resources/META-INF/persistence.xml b/models-dao/src/test/resources/META-INF/persistence.xml index 25858caba..5314ebbdb 100644 --- a/models-dao/src/test/resources/META-INF/persistence.xml +++ b/models-dao/src/test/resources/META-INF/persistence.xml @@ -30,10 +30,6 @@ <class>org.onap.policy.models.dao.DummyReferenceEntity</class> <properties> - <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" /> - <property name="javax.persistence.jdbc.user" value="sa" /> - <property name="javax.persistence.jdbc.password" value="" /> <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> <property name="eclipselink.logging.level" value="INFO" /> diff --git a/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java b/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java index b4f288685..b0b21d2c2 100644 --- a/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java +++ b/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java @@ -20,7 +20,6 @@ package org.onap.policy.models.decisions.concepts; -import java.util.List; import java.util.Map; import lombok.Data; @@ -36,5 +35,5 @@ public class DecisionResponse { private String status; private Map<String, Object> advice; private Map<String, Object> obligations; - private List<Map<String, Object>> policies; + private Map<String, Object> policies; } diff --git a/models-interactions/model-impl/aai/pom.xml b/models-interactions/model-impl/aai/pom.xml index e52b443d0..971209679 100644 --- a/models-interactions/model-impl/aai/pom.xml +++ b/models-interactions/model-impl/aai/pom.xml @@ -69,6 +69,12 @@ <groupId>org.onap.aai.schema-service</groupId> <artifactId>aai-schema</artifactId> <version>1.0.1</version> + <exclusions> + <exclusion> + <groupId>commons-beanutils</groupId> + <artifactId>commons-beanutils</artifactId> + </exclusion> + </exclusions> </dependency> </dependencies> </project> diff --git a/models-interactions/model-simulators/pom.xml b/models-interactions/model-simulators/pom.xml index 41faf89b8..52025f4b4 100644 --- a/models-interactions/model-simulators/pom.xml +++ b/models-interactions/model-simulators/pom.xml @@ -63,10 +63,15 @@ <artifactId>gson</artifactId> <scope>provided</scope> </dependency> - <dependency> - <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> - <artifactId>sdnc</artifactId> - <version>${project.version}</version> - </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> + <artifactId>sdnc</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.models</groupId> + <artifactId>policy-models-decisions</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java index e79b563df..25606eef1 100644 --- a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java +++ b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java @@ -21,34 +21,49 @@ package org.onap.policy.simulators; +import java.util.Collections; +import java.util.Map; + import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.json.JSONObject; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; -@Path("/pdp/api") +@Path("/policy/pdpx/v1") public class GuardSimulatorJaxRs { public static final String DENY_CLNAME = "denyGuard"; /** * Get a guard decision. - * + * * @param req the request * @return the response */ @POST - @Path("/getDecision") + @Path("/decision") @Consumes(MediaType.APPLICATION_JSON) @Produces("application/json") - public String getGuardDecision(String req) { - String clName = new JSONObject(req).getJSONObject("decisionAttributes").getString("clname"); + public DecisionResponse getGuardDecision(DecisionRequest req) { + @SuppressWarnings("unchecked") + Map<String, String> guard = (Map<String, String>) req.getResource().get("guard"); + String clName = guard.get("clName"); + DecisionResponse response = new DecisionResponse(); if (DENY_CLNAME.equals(clName)) { - return "{\"decision\": \"DENY\", \"details\": \"Decision Deny. You asked for it\"}"; + response.setStatus("Deny"); + response.setAdvice(Collections.emptyMap()); + response.setObligations(Collections.emptyMap()); + response.setPolicies(Collections.emptyMap()); + return response; } else { - return "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}"; + response.setStatus("Permit"); + response.setAdvice(Collections.emptyMap()); + response.setObligations(Collections.emptyMap()); + response.setPolicies(Collections.emptyMap()); + return response; } } } diff --git a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java index 99f9017a2..e5ee65004 100644 --- a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java +++ b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java @@ -24,6 +24,7 @@ package org.onap.policy.simulators; import java.io.IOException; import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.gson.GsonMessageBodyHandler; import org.onap.policy.common.utils.network.NetworkUtil; public class Util { @@ -38,7 +39,7 @@ public class Util { public static final int VFCSIM_SERVER_PORT = 6668; public static final int GUARDSIM_SERVER_PORT = 6669; public static final int SDNCSIM_SERVER_PORT = 6670; - + private static final String CANNOT_CONNECT = "cannot connect to port "; private static final String LOCALHOST = "localhost"; @@ -48,7 +49,7 @@ public class Util { /** * Build an A&AI simulator. - * + * * @return the simulator * @throws InterruptedException if a thread is interrupted * @throws IOException if an IO errror occurs @@ -85,7 +86,7 @@ public class Util { /** * Build an SO simulator. - * + * * @return the simulator * @throws InterruptedException if a thread is interrupted * @throws IOException if an IO errror occurs @@ -103,7 +104,7 @@ public class Util { /** * Build a VFC simulator. - * + * * @return the simulator * @throws InterruptedException if a thread is interrupted * @throws IOException if an IO errror occurs @@ -121,7 +122,7 @@ public class Util { /** * Build a guard simulator. - * + * * @return the simulator * @throws InterruptedException if a thread is interrupted * @throws IOException if an IO errror occurs @@ -129,6 +130,7 @@ public class Util { public static HttpServletServer buildGuardSim() throws InterruptedException, IOException { HttpServletServer testServer = HttpServletServer.factory.build(GUARDSIM_SERVER_NAME, LOCALHOST, GUARDSIM_SERVER_PORT, "/", false, true); + testServer.setSerializationProvider(GsonMessageBodyHandler.class.getName()); testServer.addServletClass("/*", GuardSimulatorJaxRs.class.getName()); testServer.waitedStart(5000); if (!NetworkUtil.isTcpPortOpen(LOCALHOST, testServer.getPort(), 5, 10000L)) { diff --git a/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java b/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java index c99798077..58f748dd5 100644 --- a/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java +++ b/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java @@ -8,9 +8,9 @@ * 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. @@ -25,14 +25,22 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; +import java.util.HashMap; +import java.util.Map; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; import org.onap.policy.rest.RestManager; import org.onap.policy.rest.RestManager.Pair; public class GuardSimulatorTest { + private static final StandardCoder coder = new StandardCoder(); /** * Set up test class. @@ -52,26 +60,38 @@ public class GuardSimulatorTest { } @Test - public void testGuard() { + public void testGuard() throws CoderException { String request = makeRequest("test_actor_id", "test_op_id", "test_target", "test_clName"); - String url = "http://localhost:" + Util.GUARDSIM_SERVER_PORT + "/pdp/api/getDecision"; + String url = "http://localhost:" + Util.GUARDSIM_SERVER_PORT + "/policy/pdpx/v1/decision"; Pair<Integer, String> response = new RestManager().post(url, "testUname", "testPass", null, "application/json", request); assertNotNull(response); assertNotNull(response.first); assertNotNull(response.second); - assertEquals("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}", response.second); + + DecisionResponse decision = coder.decode(response.second, DecisionResponse.class); + assertEquals("Permit", decision.getStatus()); request = makeRequest("test_actor_id", "test_op_id", "test_target", "denyGuard"); response = new RestManager().post(url, "testUname", "testPass", null, "application/json", request); assertNotNull(response); assertNotNull(response.first); assertNotNull(response.second); - assertEquals("{\"decision\": \"DENY\", \"details\": \"Decision Deny. You asked for it\"}", response.second); + decision = coder.decode(response.second, DecisionResponse.class); + assertEquals("Deny", decision.getStatus()); } - private static String makeRequest(String actor, String recipe, String target, String clName) { - return "{\"decisionAttributes\": {\"actor\": \"" + actor + "\", \"recipe\": \"" + recipe + "\"" - + ", \"target\": \"" + target + "\", \"clname\": \"" + clName + "\"}, \"onapName\": \"PDPD\"}"; + private static String makeRequest(String actor, String recipe, String target, String clName) throws CoderException { + Map<String, String> guard = new HashMap<String, String>(); + guard.put("actor", actor); + guard.put("recipe", recipe); + guard.put("target", target); + guard.put("clName", clName); + Map<String, Object> resource = new HashMap<String, Object>(); + resource.put("guard", guard); + DecisionRequest request = new DecisionRequest(); + request.setResource(resource); + + return coder.encode(request); } } diff --git a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java index 2b05d2858..4bf1dbea4 100644 --- a/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java +++ b/models-interactions/model-yaml/src/main/java/org/onap/policy/controlloop/policy/TargetType.java @@ -27,7 +27,7 @@ public enum TargetType { PNF("PNF"), VFC("VFC"), VNF("VNF"), - VFMODULE("VFModule") + VFMODULE("VFMODULE") ; private String target; diff --git a/models-pdp/pom.xml b/models-pdp/pom.xml index 029c76b8f..a3146fa75 100644 --- a/models-pdp/pom.xml +++ b/models-pdp/pom.xml @@ -45,8 +45,9 @@ <version>${project.version}</version> </dependency> <dependency> - <groupId>org.mariadb.jdbc</groupId> - <artifactId>mariadb-java-client</artifactId> + <groupId>org.onap.policy.common</groupId> + <artifactId>common-parameters</artifactId> + <version>${policy.common.version}</version> </dependency> <dependency> <groupId>com.h2database</groupId> diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java index 9665fd472..4e7fc4117 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java @@ -1,7 +1,7 @@ -/* +/*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,37 +21,42 @@ package org.onap.policy.models.pdp.concepts; +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - +import java.util.stream.Collectors; import lombok.Data; import lombok.NoArgsConstructor; - +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ObjectValidationResult; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfNameVersion; import org.onap.policy.models.base.PfUtils; import org.onap.policy.models.pdp.enums.PdpState; /** - * Class to represent a PDPGroup, which groups multiple PDPSubGroup entities together for - * a particular domain. + * Class to represent a PDPGroup, which groups multiple PDPSubGroup entities together for a particular domain. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @Data @NoArgsConstructor public class PdpGroup implements PfNameVersion, Comparable<PdpGroup> { + private static final String SUBGROUP_FIELD = "pdpSubgroups"; + private String name; - private String version; private String description; private PdpState pdpGroupState; private Map<String, String> properties; private List<PdpSubGroup> pdpSubgroups; /* - * Note: removed "@NotNull" annotation from the constructor argument, because it - * cannot be covered by a junit test, as the superclass does the check and throws an - * exception first. + * Note: removed "@NotNull" annotation from the constructor argument, because it cannot be covered by a junit test, + * as the superclass does the check and throws an exception first. */ /** @@ -61,7 +66,6 @@ public class PdpGroup implements PfNameVersion, Comparable<PdpGroup> { */ public PdpGroup(PdpGroup source) { this.name = source.name; - this.version = source.version; this.description = source.description; this.pdpGroupState = source.pdpGroupState; this.properties = (source.properties == null ? null : new LinkedHashMap<>(source.properties)); @@ -72,4 +76,63 @@ public class PdpGroup implements PfNameVersion, Comparable<PdpGroup> { public int compareTo(final PdpGroup other) { return compareNameVersion(this, other); } + + /** + * Validates that appropriate fields are populated for an incoming call to the PAP REST API. + * + * @return the validation result + */ + public ValidationResult validatePapRest() { + BeanValidationResult result = new BeanValidationResult("group", this); + + /* + * Don't care about state, because we override it. Ok if description is null. + */ + + result.validateNotNull("name", name); + result.validateNotNullList(SUBGROUP_FIELD, pdpSubgroups, PdpSubGroup::validatePapRest); + + if (pdpSubgroups != null && pdpSubgroups.isEmpty()) { + result.addResult(new ObjectValidationResult(SUBGROUP_FIELD, pdpSubgroups, ValidationStatus.INVALID, + "is empty")); + } + + checkDuplicateSubgroups(result); + + return result; + } + + /** + * Checks for duplicate subgroups. + * + * @param result where to place validation results + */ + private void checkDuplicateSubgroups(BeanValidationResult result) { + if (pdpSubgroups == null || !result.isValid()) { + return; + } + + // verify that the same subgroup doesn't appear more than once + List<String> pdpTypes = pdpSubgroups.stream().map(PdpSubGroup::getPdpType).collect(Collectors.toList()); + if (pdpSubgroups.size() == new HashSet<>(pdpTypes).size()) { + return; + } + + // different sizes implies duplicates + result.addResult(new ObjectValidationResult(SUBGROUP_FIELD, pdpTypes, ValidationStatus.INVALID, + "duplicate subgroups")); + } + + @Override + @JsonIgnore + public String getVersion() { + // We need to pass a version for keying in the database + return PfKey.NULL_KEY_VERSION; + } + + @Override + @JsonIgnore + public void setVersion(String version) { + // Just ignore any version that is set + } } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroupFilter.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroupFilter.java index 0f86c6890..d67f2d4cb 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroupFilter.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroupFilter.java @@ -41,14 +41,9 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifi @Builder @Data public class PdpGroupFilter implements PfObjectFilter<PdpGroup> { - public static final String LATEST_VERSION = "LATEST"; - // Name to find private String name; - // Version to find, set to LATEST_VERSION to get the latest version - private String version; - // State to find private PdpState groupState; @@ -76,10 +71,8 @@ public class PdpGroupFilter implements PfObjectFilter<PdpGroup> { public List<PdpGroup> filter(@NonNull final List<PdpGroup> originalList) { // @formatter:off - List<PdpGroup> returnList = originalList.stream() + return originalList.stream() .filter(p -> filterString(p.getName(), name)) - .filter(p -> LATEST_VERSION.equals(version) - || filterString(p.getVersion(), version)) .filter(p -> groupState == null || ObjectUtils.compare(p.getPdpGroupState(), groupState) == 0) .filter(p -> filterOnPdpType(p, pdpType)) .filter(p -> filterOnPolicyTypeList(p, policyTypeList, matchPolicyTypesExactly)) @@ -87,12 +80,6 @@ public class PdpGroupFilter implements PfObjectFilter<PdpGroup> { .filter(p -> filterOnPdpState(p, pdpState)) .collect(Collectors.toList()); // @formatter:on - - if (LATEST_VERSION.equals(version)) { - returnList = this.latestVersionFilter(returnList); - } - - return returnList; } /** diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java index 32e0b1a29..06194eaba 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java @@ -21,34 +21,65 @@ package org.onap.policy.models.pdp.concepts; import java.util.Collections; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - +import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ObjectValidationResult; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; /** - * Request deploy or update a set of groups via the PDP Group deployment - * REST API. + * Request deploy or update a set of groups via the PDP Group deployment REST API. */ @Getter @Setter @ToString public class PdpGroups { + private static final String GROUPS_FIELD = "groups"; + private List<PdpGroup> groups; /** * Get the contents of this class as a list of PDP group maps. + * * @return the PDP groups in a list of maps */ public List<Map<String, PdpGroup>> toMapList() { final Map<String, PdpGroup> pdpGroupMap = new LinkedHashMap<>(); for (PdpGroup pdpGroup : groups) { - pdpGroupMap.put(pdpGroup.getName() + ':' + pdpGroup.getVersion() , pdpGroup); + pdpGroupMap.put(pdpGroup.getName() + ':' + pdpGroup.getVersion(), pdpGroup); } return Collections.singletonList(pdpGroupMap); } + + /** + * Validates that appropriate fields are populated for an incoming call to the PAP + * REST API. + * + * @return the validation result + */ + public ValidationResult validatePapRest() { + BeanValidationResult result = new BeanValidationResult(GROUPS_FIELD, this); + + result.validateNotNullList(GROUPS_FIELD, groups, PdpGroup::validatePapRest); + if (!result.isValid()) { + return result; + } + + // verify that the same group doesn't appear more than once + List<String> names = groups.stream().map(PdpGroup::getName).collect(Collectors.toList()); + if (groups.size() == new HashSet<>(names).size()) { + return result; + } + + // different sizes implies duplicates + return new ObjectValidationResult(GROUPS_FIELD, names, ValidationStatus.INVALID, "duplicate group names"); + } } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpResponseDetails.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpResponseDetails.java index c28d01a3e..6b5bd6cea 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpResponseDetails.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpResponseDetails.java @@ -22,6 +22,7 @@ package org.onap.policy.models.pdp.concepts; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.onap.policy.models.pdp.enums.PdpResponseStatus; @@ -34,10 +35,22 @@ import org.onap.policy.models.pdp.enums.PdpResponseStatus; @Getter @Setter @ToString +@NoArgsConstructor public class PdpResponseDetails { // The responseTo field should match the original request id in the request. private String responseTo; private PdpResponseStatus responseStatus; private String responseMessage; + + /** + * Constructs the object, making a deep copy. + * + * @param source source from which to copy + */ + public PdpResponseDetails(PdpResponseDetails source) { + this.responseMessage = source.responseMessage; + this.responseStatus = source.responseStatus; + this.responseTo = source.responseTo; + } } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatistics.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatistics.java index 36e8d00f8..1847eed77 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatistics.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatistics.java @@ -22,6 +22,7 @@ package org.onap.policy.models.pdp.concepts; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @@ -33,6 +34,7 @@ import lombok.ToString; @Getter @Setter @ToString +@NoArgsConstructor public class PdpStatistics { private String pdpInstanceId; @@ -42,4 +44,19 @@ public class PdpStatistics { private long policyExecutedCount; private long policyExecutedSuccessCount; private long policyExecutedFailCount; + + /** + * Constructs the object, making a deep copy. + * + * @param source source from which to copy + */ + public PdpStatistics(PdpStatistics source) { + this.pdpInstanceId = source.pdpInstanceId; + this.policyDeployCount = source.policyDeployCount; + this.policyDeployFailCount = source.policyDeployFailCount; + this.policyDeploySuccessCount = source.policyDeploySuccessCount; + this.policyExecutedCount = source.policyExecutedCount; + this.policyExecutedFailCount = source.policyExecutedFailCount; + this.policyExecutedSuccessCount = source.policyExecutedSuccessCount; + } } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java index 5858b6acd..3655aa796 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java @@ -25,6 +25,7 @@ import java.util.List; import lombok.Getter; import lombok.Setter; import lombok.ToString; +import org.onap.policy.models.base.PfUtils; import org.onap.policy.models.pdp.enums.PdpHealthStatus; import org.onap.policy.models.pdp.enums.PdpMessageType; import org.onap.policy.models.pdp.enums.PdpState; @@ -64,4 +65,24 @@ public class PdpStatus extends PdpMessage { public PdpStatus() { super(PdpMessageType.PDP_STATUS); } + + /** + * Constructs the object, making a deep copy. + * + * @param source source from which to copy + */ + public PdpStatus(PdpStatus source) { + super(source); + + this.pdpType = source.pdpType; + this.state = source.state; + this.healthy = source.healthy; + this.description = source.description; + this.supportedPolicyTypes = PfUtils.mapList(source.supportedPolicyTypes, ToscaPolicyTypeIdentifier::new); + this.policies = PfUtils.mapList(source.policies, ToscaPolicyIdentifier::new); + this.deploymentInstanceInfo = source.deploymentInstanceInfo; + this.properties = source.properties; + this.statistics = (source.statistics == null ? null : new PdpStatistics(source.statistics)); + this.response = (source.response == null ? null : new PdpResponseDetails(source.response)); + } } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java index 405408946..2618a5017 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java @@ -24,16 +24,19 @@ package org.onap.policy.models.pdp.concepts; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import lombok.Data; import lombok.NonNull; - +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ObjectValidationResult; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; import org.onap.policy.models.base.PfUtils; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; /** - * Class to represent a group of all PDP's of the same pdp type running for a particular domain. + * Class to represent a group of all PDP's of the same pdp type running for a particular + * domain. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @@ -68,4 +71,31 @@ public class PdpSubGroup { this.properties = (source.properties == null ? null : new LinkedHashMap<>(source.properties)); this.pdpInstances = PfUtils.mapList(source.pdpInstances, Pdp::new); } + + /** + * Validates that appropriate fields are populated for an incoming call to the PAP + * REST API. + * + * @return the validation result + */ + public ValidationResult validatePapRest() { + BeanValidationResult result = new BeanValidationResult("group", this); + + result.validateNotNull("pdpType", pdpType); + result.validateNotNullList("supportedPolicyTypes", supportedPolicyTypes, + ToscaPolicyTypeIdentifier::validatePapRest); + result.validateNotNullList("policies", policies, ToscaPolicyIdentifier::validatePapRest); + + if (supportedPolicyTypes != null && supportedPolicyTypes.isEmpty()) { + result.addResult(new ObjectValidationResult("supportedPolicyTypes", supportedPolicyTypes, + ValidationStatus.INVALID, "empty list")); + } + + if (desiredInstanceCount <= 0) { + result.addResult(new ObjectValidationResult("desiredInstanceCount", desiredInstanceCount, + ValidationStatus.INVALID, "non-positive")); + } + + return result; + } } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpUpdate.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpUpdate.java index 5d0e225c3..c42f1db09 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpUpdate.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpUpdate.java @@ -21,6 +21,7 @@ package org.onap.policy.models.pdp.concepts; +import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import lombok.Getter; @@ -54,7 +55,7 @@ public class PdpUpdate extends PdpMessage { * listed. Note: this list may be empty, as a PDP may remain attached to a subgroup * even if all of the policies are removed from the subgroup. */ - private List<ToscaPolicy> policies; + private List<ToscaPolicy> policies = new LinkedList<>(); /** * Constructor for instantiating PdpUpdate class with message name. diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdp.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdp.java index 627641825..528d6fbe7 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdp.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdp.java @@ -193,7 +193,7 @@ public class JpaPdp extends PfConcept implements PfAuthorative<Pdp>, Serializabl "PDP health status may not be null")); } - if (StringUtils.isBlank(message)) { + if (message != null && StringUtils.isBlank(message)) { result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "message may not be blank")); } diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroup.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroup.java index d0fc216c2..1e77c099d 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroup.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroup.java @@ -238,16 +238,7 @@ public class JpaPdpGroup extends PfConcept implements PfAuthorative<PdpGroup> { } if (properties != null) { - for (Entry<String, String> propertyEntry : properties.entrySet()) { - if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getKey())) { - result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "a property key may not be null or blank")); - } - if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getValue())) { - result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, - "a property value may not be null or blank")); - } - } + result = validateProperties(result); } if (pdpSubGroups == null) { @@ -262,6 +253,29 @@ public class JpaPdpGroup extends PfConcept implements PfAuthorative<PdpGroup> { return result; } + /** + * Validate the properties. + * + * @param resultIn the incoming validation results so far + * @return the revalidation results including the property validation results + */ + private PfValidationResult validateProperties(PfValidationResult resultIn) { + PfValidationResult result = resultIn; + + for (Entry<String, String> propertyEntry : properties.entrySet()) { + if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getKey())) { + result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "a property key may not be null or blank")); + } + if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getValue())) { + result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, + "a property value may not be null or blank")); + } + } + + return result; + } + @Override public int compareTo(final PfConcept otherConcept) { if (otherConcept == null) { diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java index bfdeda984..efdf5f2c8 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpProvider.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. @@ -28,6 +29,7 @@ import javax.ws.rs.core.Response; import lombok.NonNull; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.base.PfReferenceKey; @@ -60,14 +62,12 @@ public class PdpProvider { * * @param dao the DAO to use to access the database * @param name the name of the PDP group to get, null to get all PDP groups - * @param version the version of the policy to get, null to get all versions of a PDP group * @return the PDP groups found * @throws PfModelException on errors getting PDP groups */ - public List<PdpGroup> getPdpGroups(@NonNull final PfDao dao, final String name, final String version) - throws PfModelException { + public List<PdpGroup> getPdpGroups(@NonNull final PfDao dao, final String name) throws PfModelException { - return asPdpGroupList(dao.getFiltered(JpaPdpGroup.class, name, version)); + return asPdpGroupList(dao.getFiltered(JpaPdpGroup.class, name, PfKey.NULL_KEY_VERSION)); } /** @@ -80,9 +80,8 @@ public class PdpProvider { */ public List<PdpGroup> getFilteredPdpGroups(@NonNull final PfDao dao, @NonNull final PdpGroupFilter filter) { - List<JpaPdpGroup> jpaPdpGroupList = dao.getAll(JpaPdpGroup.class); - - return filter.filter(asPdpGroupList(jpaPdpGroupList)); + return filter.filter( + asPdpGroupList(dao.getFiltered(JpaPdpGroup.class, filter.getName(), PfKey.NULL_KEY_VERSION))); } /** @@ -115,7 +114,7 @@ public class PdpProvider { for (PdpGroup pdpGroup : pdpGroups) { JpaPdpGroup jpaPdpGroup = - dao.get(JpaPdpGroup.class, new PfConceptKey(pdpGroup.getName(), pdpGroup.getVersion())); + dao.get(JpaPdpGroup.class, new PfConceptKey(pdpGroup.getName(), PfKey.NULL_KEY_VERSION)); returnPdpGroups.add(jpaPdpGroup.toAuthorative()); } @@ -152,7 +151,7 @@ public class PdpProvider { for (PdpGroup pdpGroup : pdpGroups) { JpaPdpGroup jpaPdpGroup = - dao.get(JpaPdpGroup.class, new PfConceptKey(pdpGroup.getName(), pdpGroup.getVersion())); + dao.get(JpaPdpGroup.class, new PfConceptKey(pdpGroup.getName(), PfKey.NULL_KEY_VERSION)); returnPdpGroups.add(jpaPdpGroup.toAuthorative()); } @@ -164,14 +163,14 @@ public class PdpProvider { * * @param dao the DAO to use to access the database * @param pdpGroupName the name of the PDP group of the PDP subgroup - * @param pdpGroupVersion the version of the PDP group of the PDP subgroup * @param pdpSubGroup the PDP subgroup to be updated * @throws PfModelException on errors updating PDP subgroups */ public void updatePdpSubGroup(@NonNull final PfDao dao, @NonNull final String pdpGroupName, - @NonNull final String pdpGroupVersion, @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException { + @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException { - final PfReferenceKey subGroupKey = new PfReferenceKey(pdpGroupName, pdpGroupVersion, pdpSubGroup.getPdpType()); + final PfReferenceKey subGroupKey = + new PfReferenceKey(pdpGroupName, PfKey.NULL_KEY_VERSION, pdpSubGroup.getPdpType()); final JpaPdpSubGroup jpaPdpSubgroup = new JpaPdpSubGroup(subGroupKey); jpaPdpSubgroup.fromAuthorative(pdpSubGroup); @@ -190,16 +189,15 @@ public class PdpProvider { * * @param dao the DAO to use to access the database * @param pdpGroupName the name of the PDP group of the PDP subgroup - * @param pdpGroupVersion the version of the PDP group of the PDP subgroup * @param pdpSubGroup the PDP subgroup to be updated * @param pdp the PDP to be updated * @throws PfModelException on errors updating PDP subgroups */ public void updatePdp(@NonNull final PfDao dao, @NonNull final String pdpGroupName, - @NonNull final String pdpGroupVersion, @NonNull final String pdpSubGroup, @NonNull final Pdp pdp) { + @NonNull final String pdpSubGroup, @NonNull final Pdp pdp) { final PfReferenceKey pdpKey = - new PfReferenceKey(pdpGroupName, pdpGroupVersion, pdpSubGroup, pdp.getInstanceId()); + new PfReferenceKey(pdpGroupName, PfKey.NULL_KEY_VERSION, pdpSubGroup, pdp.getInstanceId()); final JpaPdp jpaPdp = new JpaPdp(pdpKey); jpaPdp.fromAuthorative(pdp); @@ -218,14 +216,12 @@ public class PdpProvider { * * @param dao the DAO to use to access the database * @param name the name of the policy to get, null to get all PDP groups - * @param version the version of the policy to get, null to get all versions of a PDP group * @return the PDP group deleted * @throws PfModelException on errors deleting PDP groups */ - public PdpGroup deletePdpGroup(@NonNull final PfDao dao, @NonNull final String name, - @NonNull final String version) { + public PdpGroup deletePdpGroup(@NonNull final PfDao dao, @NonNull final String name) { - PfConceptKey pdpGroupKey = new PfConceptKey(name, version); + PfConceptKey pdpGroupKey = new PfConceptKey(name, PfKey.NULL_KEY_VERSION); JpaPdpGroup jpaDeletePdpGroup = dao.get(JpaPdpGroup.class, pdpGroupKey); @@ -245,12 +241,10 @@ public class PdpProvider { * * @param dao the DAO to use to access the database * @param name the name of the PDP group to get statistics for, null to get all PDP groups - * @param version the version of the PDP group to get statistics for, null to get all versions of a PDP group * @return the statistics found * @throws PfModelException on errors getting statistics */ - public List<PdpStatistics> getPdpStatistics(@NonNull final PfDao dao, final String name, final String version) - throws PfModelException { + public List<PdpStatistics> getPdpStatistics(@NonNull final PfDao dao, final String name) throws PfModelException { return new ArrayList<>(); } @@ -259,14 +253,13 @@ public class PdpProvider { * * @param dao the DAO to use to access the database * @param pdpGroupName the name of the PDP group containing the PDP that the statistics are for - * @param pdpGroupVersion the version of the PDP group containing the PDP that the statistics are for * @param pdpType the PDP type of the subgroup containing the PDP that the statistics are for * @param pdpInstanceId the instance ID of the PDP to update statistics for * @param pdpStatistics the statistics to update * @throws PfModelException on errors updating statistics */ public void updatePdpStatistics(@NonNull final PfDao dao, @NonNull final String pdpGroupName, - @NonNull final String pdpGroupVersion, @NonNull final String pdpType, @NonNull final String pdpInstanceId, + @NonNull final String pdpType, @NonNull final String pdpInstanceId, @NonNull final PdpStatistics pdpStatistics) throws PfModelException { // Not implemented yet } diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/ModelsTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/ModelsTest.java index d22642d98..743839362 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/ModelsTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/ModelsTest.java @@ -21,12 +21,12 @@ package org.onap.policy.models.pdp.concepts; +import com.openpojo.reflection.filters.FilterClassName; import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; - import org.junit.Test; import org.onap.policy.common.utils.validation.ToStringTester; @@ -36,11 +36,16 @@ import org.onap.policy.common.utils.validation.ToStringTester; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ public class ModelsTest { + private static final String POJO_PACKAGE = "org.onap.policy.models.pdp.concepts"; @Test public void testPdpModels() { final Validator validator = ValidatorBuilder.create().with(new ToStringTester()).with(new SetterTester()) - .with(new GetterTester()).build(); - validator.validate(ModelsTest.class.getPackage().getName(), new FilterPackageInfo()); + .with(new GetterTester()).build(); + + // exclude Test classes and PdpMessage + validator.validate(POJO_PACKAGE, new FilterPackageInfo(), + new FilterClassName("^((?!Test$).)*$"), + new FilterClassName("^((?!" + PdpMessage.class.getName() + ").)*$")); } } diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java index 75ec4d169..89ee5b90d 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupFilterTest.java @@ -74,38 +74,28 @@ public class PdpGroupFilterTest { } @Test - public void testFilterLatestVersion() { - PdpGroupFilter filter = PdpGroupFilter.builder().version(PdpGroupFilter.LATEST_VERSION).build(); - - List<PdpGroup> filteredList = filter.filter(pdpGroupList); - assertEquals(2, filteredList.size()); - assertEquals("1.2.4", filteredList.get(0).getVersion()); - assertEquals("1.2.3", filteredList.get(1).getVersion()); - } - - @Test - public void testFilterNameVersion() { + public void testFilterName() { PdpGroupFilter filter = PdpGroupFilter.builder().name("PdpGroup0").build(); List<PdpGroup> filteredList = filter.filter(pdpGroupList); - assertEquals(3, filteredList.size()); + assertEquals(1, filteredList.size()); filter = PdpGroupFilter.builder().name("PdpGroup1").build(); filteredList = filter.filter(pdpGroupList); - assertEquals(2, filteredList.size()); + assertEquals(1, filteredList.size()); - filter = PdpGroupFilter.builder().name("PdpGroup2").build(); + filter = PdpGroupFilter.builder().name("PdpGroup20").build(); filteredList = filter.filter(pdpGroupList); - assertEquals(0, filteredList.size()); + assertEquals(1, filteredList.size()); - filter = PdpGroupFilter.builder().version("1.2.3").build(); + filter = PdpGroupFilter.builder().build(); filteredList = filter.filter(pdpGroupList); - assertEquals(2, filteredList.size()); + assertEquals(5, filteredList.size()); - filter = PdpGroupFilter.builder().name("PdpGroup0").version("1.2.3").build(); + filter = PdpGroupFilter.builder().name("PdpGroup0").build(); filteredList = filter.filter(pdpGroupList); assertEquals(1, filteredList.size()); - filter = PdpGroupFilter.builder().name("PdpGroup1").version("1.2.9").build(); + filter = PdpGroupFilter.builder().name("PdpGroup19").build(); filteredList = filter.filter(pdpGroupList); assertEquals(0, filteredList.size()); } diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java index 77666b228..a717dc2d8 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupTest.java @@ -23,20 +23,30 @@ package org.onap.policy.models.pdp.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; /** - * Test the copy constructor, as {@link ModelsTest} tests the other methods. + * Test methods not tested by {@link ModelsTest}. */ public class PdpGroupTest { + private static final String NAME = "my-name"; + private static final String PDP_TYPE1 = "type-1"; + private static final String PDP_TYPE2 = "type-2"; + private static final String PDP_TYPE3 = "type-3"; @Test public void testCopyConstructor() { @@ -45,12 +55,12 @@ public class PdpGroupTest { PdpGroup orig = new PdpGroup(); // verify with null values - assertEquals("PdpGroup(name=null, version=null, description=null, pdpGroupState=null, " - + "properties=null, pdpSubgroups=[])", new PdpGroup(orig).toString()); + assertEquals("PdpGroup(name=null, description=null, pdpGroupState=null, " + "properties=null, pdpSubgroups=[])", + new PdpGroup(orig).toString()); // verify with all values orig.setDescription("my-descript"); - orig.setName("my-name"); + orig.setName(NAME); orig.setVersion("1.2.3"); orig.setDescription("my-description"); orig.setPdpGroupState(PdpState.SAFE); @@ -66,12 +76,12 @@ public class PdpGroupTest { props.put("key-B", "value-B"); orig.setProperties(props); - assertEquals("PdpGroup(name=my-name, version=1.2.3, description=my-description, " - + "pdpGroupState=SAFE, properties={key-A=value-A, key-B=value-B}, " - + "pdpSubgroups=[PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], " - + "currentInstanceCount=10, desiredInstanceCount=0, properties=null, pdpInstances=[]), " - + "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], currentInstanceCount=11, " - + "desiredInstanceCount=0, properties=null, pdpInstances=[])])", new PdpGroup(orig).toString()); + assertEquals("PdpGroup(name=my-name, description=my-description, " + + "pdpGroupState=SAFE, properties={key-A=value-A, key-B=value-B}, " + + "pdpSubgroups=[PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], " + + "currentInstanceCount=10, desiredInstanceCount=0, properties=null, pdpInstances=[]), " + + "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], currentInstanceCount=11, " + + "desiredInstanceCount=0, properties=null, pdpInstances=[])])", new PdpGroup(orig).toString()); } @Test @@ -108,4 +118,69 @@ public class PdpGroupTest { assertEquals(1, mapList.size()); assertEquals(1, mapList.get(0).size()); } + + @Test + public void testValidatePapRest() { + PdpGroup group = new PdpGroup(); + group.setName(NAME); + + PdpSubGroup subgroup1 = new PdpSubGroup(); + subgroup1.setDesiredInstanceCount(1); + subgroup1.setPdpType(PDP_TYPE1); + subgroup1.setSupportedPolicyTypes(Arrays.asList(new ToscaPolicyTypeIdentifier("a-type-name", "3.2.1"))); + subgroup1.setPolicies(Collections.emptyList()); + + PdpSubGroup subgroup2 = new PdpSubGroup(subgroup1); + subgroup2.setPdpType(PDP_TYPE2); + + PdpSubGroup subgroup3 = new PdpSubGroup(subgroup1); + subgroup3.setPdpType(PDP_TYPE3); + + group.setPdpSubgroups(Arrays.asList(subgroup1, subgroup2, subgroup3)); + + // valid + ValidationResult result = group.validatePapRest(); + assertNotNull(result); + assertTrue(result.isValid()); + assertNull(result.getResult()); + + // null name + PdpGroup group2 = new PdpGroup(group); + group2.setName(null); + assertInvalid(group2); + + // null subgroup list + group2 = new PdpGroup(group); + group2.setPdpSubgroups(null); + assertInvalid(group2); + + // empty subgroup list + group2 = new PdpGroup(group); + group2.setPdpSubgroups(Collections.emptyList()); + assertInvalid(group2); + + // null subgroup + group2 = new PdpGroup(group); + group2.setPdpSubgroups(Arrays.asList(subgroup1, null)); + assertInvalid(group2); + + // invalid subgroup + group2 = new PdpGroup(group); + PdpSubGroup subgroupX = new PdpSubGroup(subgroup1); + subgroupX.setPdpType(null); + group2.setPdpSubgroups(Arrays.asList(subgroupX)); + assertInvalid(group2); + + // duplicate PDP type + group2 = new PdpGroup(group); + group2.setPdpSubgroups(Arrays.asList(subgroup1, subgroup2, subgroup1)); + assertInvalid(group2); + } + + private void assertInvalid(PdpGroup group) { + ValidationResult result = group.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + } } diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupsTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupsTest.java new file mode 100644 index 000000000..bd98f18c3 --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpGroupsTest.java @@ -0,0 +1,106 @@ +/* + * ============LICENSE_START======================================================= + * ONAP Policy Models + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.pdp.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; + +public class PdpGroupsTest { + + @Test + public void testValidatePapRest_toMapList() { + PdpGroup group1 = new PdpGroup(); + group1.setName("group-1"); + + PdpSubGroup subgrp = new PdpSubGroup(); + subgrp.setDesiredInstanceCount(1); + subgrp.setPdpType("pdp-type"); + subgrp.setSupportedPolicyTypes(Arrays.asList(new ToscaPolicyTypeIdentifier("policy-type", "9.8.7"))); + subgrp.setPolicies(Collections.emptyList()); + + group1.setPdpSubgroups(Arrays.asList(subgrp)); + + PdpGroup group2 = new PdpGroup(); + group2.setName("group-2"); + group2.setPdpSubgroups(Arrays.asList(subgrp)); + + PdpGroups groups = new PdpGroups(); + groups.setGroups(Arrays.asList(group1, group2)); + + // valid + ValidationResult result = groups.validatePapRest(); + assertNotNull(result); + assertTrue(result.isValid()); + assertNull(result.getResult()); + + // check toMapList() + List<Map<String, PdpGroup>> lst = groups.toMapList(); + assertEquals(1, lst.size()); + + Map<String, PdpGroup> map = lst.get(0); + assertEquals(2, map.size()); + + Iterator<PdpGroup> iter = map.values().iterator(); + assertSame(group1, iter.next()); + assertSame(group2, iter.next()); + + // null group list + groups = new PdpGroups(); + groups.setGroups(null); + assertInvalid(groups); + + // null group + groups = new PdpGroups(); + groups.setGroups(Arrays.asList(group1, null)); + assertInvalid(groups); + + // invalid group + PdpGroup groupX = new PdpGroup(group1); + groupX.setName(null); + groups.setGroups(Arrays.asList(group1, groupX)); + assertInvalid(groups); + + // duplicate groups + groups = new PdpGroups(); + groups.setGroups(Arrays.asList(group1, group2, group1)); + assertInvalid(groups); + } + + private void assertInvalid(PdpGroups groups) { + ValidationResult result = groups.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + } +} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java index bc90f649b..10f31312c 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpMessageTest.java @@ -29,9 +29,6 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; import org.onap.policy.models.pdp.enums.PdpMessageType; -/** - * Tests methods not already tested by {@link TestModels}. - */ public class PdpMessageTest { private static final String PDP_NAME = "pdpA"; private static final String PDP_GROUP = "groupA"; diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpResponseDetailsTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpResponseDetailsTest.java new file mode 100644 index 000000000..f21a0a5bb --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpResponseDetailsTest.java @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * ONAP Policy Models + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.pdp.concepts; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.onap.policy.models.pdp.concepts.PdpMessageUtils.removeVariableFields; + +import org.junit.Test; +import org.onap.policy.models.pdp.enums.PdpResponseStatus; + +public class PdpResponseDetailsTest { + + @Test + public void testCopyConstructor() { + assertThatThrownBy(() -> new PdpResponseDetails(null)).isInstanceOf(NullPointerException.class); + + PdpResponseDetails orig = new PdpResponseDetails(); + + // verify with null values + assertEquals(removeVariableFields(orig.toString()), + removeVariableFields(new PdpResponseDetails(orig).toString())); + + // verify with all values + orig.setResponseMessage("my-message"); + orig.setResponseStatus(PdpResponseStatus.FAIL); + orig.setResponseTo("original-request-id"); + + assertEquals(removeVariableFields(orig.toString()), + removeVariableFields(new PdpResponseDetails(orig).toString())); + } +} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpStatisticsTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpStatisticsTest.java new file mode 100644 index 000000000..08098cc28 --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpStatisticsTest.java @@ -0,0 +1,53 @@ +/* + * ============LICENSE_START======================================================= + * ONAP Policy Models + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.pdp.concepts; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.onap.policy.models.pdp.concepts.PdpMessageUtils.removeVariableFields; + +import org.junit.Test; + +public class PdpStatisticsTest { + + @Test + public void testCopyConstructor() { + assertThatThrownBy(() -> new PdpStatistics(null)).isInstanceOf(NullPointerException.class); + + PdpStatistics orig = new PdpStatistics(); + + // verify with null values + assertEquals(removeVariableFields(orig.toString()), removeVariableFields(new PdpStatistics(orig).toString())); + + // verify with all values + orig.setPdpInstanceId("my-instance"); + + int count = 1; + orig.setPolicyDeployCount(count++); + orig.setPolicyDeployFailCount(count++); + orig.setPolicyDeploySuccessCount(count++); + orig.setPolicyExecutedCount(count++); + orig.setPolicyExecutedFailCount(count++); + orig.setPolicyExecutedSuccessCount(count++); + + assertEquals(removeVariableFields(orig.toString()), removeVariableFields(new PdpStatistics(orig).toString())); + } +} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpStatusTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpStatusTest.java new file mode 100644 index 000000000..3284d95ff --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpStatusTest.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START======================================================= + * ONAP Policy Models + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.pdp.concepts; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.onap.policy.models.pdp.concepts.PdpMessageUtils.removeVariableFields; + +import java.util.Arrays; +import java.util.Collections; +import org.junit.Test; +import org.onap.policy.models.pdp.enums.PdpHealthStatus; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; + +public class PdpStatusTest { + + @Test + public void testCopyConstructor() { + assertThatThrownBy(() -> new PdpStatus(null)).isInstanceOf(NullPointerException.class); + + PdpStatus orig = new PdpStatus(); + + // verify with null values + orig.setSupportedPolicyTypes(Collections.emptyList()); + orig.setPolicies(Collections.emptyList()); + assertEquals(removeVariableFields(orig.toString()), removeVariableFields(new PdpStatus(orig).toString())); + + // verify with all values + orig.setDeploymentInstanceInfo("my-deployment"); + orig.setDescription("my-description"); + orig.setHealthy(PdpHealthStatus.NOT_HEALTHY); + orig.setName("my-name"); + orig.setPdpGroup("my-group"); + orig.setPdpSubgroup("my-subgroup"); + orig.setPdpType("my-type"); + orig.setPolicies(Arrays.asList(new ToscaPolicyIdentifier("policy-A", "1.0.0"))); + orig.setProperties("my-properties"); + + PdpResponseDetails resp = new PdpResponseDetails(); + resp.setResponseMessage("my-response"); + + orig.setResponse(resp); + orig.setState(PdpState.SAFE); + + PdpStatistics stats = new PdpStatistics(); + stats.setPdpInstanceId("my-pdp-id"); + + orig.setStatistics(stats); + orig.setSupportedPolicyTypes(Arrays.asList(new ToscaPolicyTypeIdentifier("type-A", "2.0.0"))); + + assertEquals(removeVariableFields(orig.toString()), removeVariableFields(new PdpStatus(orig).toString())); + } +} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpSubGroupTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpSubGroupTest.java index 4284f71c4..7a7babecc 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpSubGroupTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpSubGroupTest.java @@ -23,19 +23,28 @@ package org.onap.policy.models.pdp.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.Arrays; +import java.util.Collections; import java.util.Map; import java.util.TreeMap; - import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; /** - * Test the copy constructor, as {@link ModelsTest} tests the other methods. + * Test methods not tested by {@link ModelsTest}. */ public class PdpSubGroupTest { + private static final Coder coder = new StandardCoder(); @Test public void testCopyConstructor() { @@ -44,10 +53,9 @@ public class PdpSubGroupTest { final PdpSubGroup orig = new PdpSubGroup(); // verify with null values - assertEquals( - "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], " + assertEquals("PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], " + "currentInstanceCount=0, desiredInstanceCount=0, properties=null, pdpInstances=[])", - new PdpSubGroup(orig).toString()); + new PdpSubGroup(orig).toString()); // verify with all values orig.setCurrentInstanceCount(10); @@ -80,4 +88,113 @@ public class PdpSubGroupTest { assertEquals(orig.toString(), new PdpSubGroup(orig).toString()); } + + @Test + public void testValidatePapRest() throws Exception { + PdpSubGroup subgrp = new PdpSubGroup(); + + subgrp.setDesiredInstanceCount(1); + subgrp.setPdpType("pdp-type"); + subgrp.setSupportedPolicyTypes(Arrays.asList(makeIdent("type-X", "3.0.0", ToscaPolicyTypeIdentifier.class))); + subgrp.setPolicies(Arrays.asList(makeIdent("policy-X", "4.0.0", ToscaPolicyIdentifier.class))); + + // valid + ValidationResult result = subgrp.validatePapRest(); + assertNotNull(result); + assertTrue(result.isValid()); + assertNull(result.getResult()); + + // zero count + PdpSubGroup sub2 = new PdpSubGroup(subgrp); + sub2.setDesiredInstanceCount(0); + assertInvalid(sub2); + + // negative count + sub2 = new PdpSubGroup(subgrp); + sub2.setDesiredInstanceCount(-1); + assertInvalid(sub2); + + // null pdp type + sub2 = new PdpSubGroup(subgrp); + sub2.setPdpType(null); + assertInvalid(sub2); + + // null policy types + sub2 = new PdpSubGroup(subgrp); + sub2.setSupportedPolicyTypes(null); + assertInvalid(sub2); + + // empty policy types + sub2 = new PdpSubGroup(subgrp); + sub2.setSupportedPolicyTypes(Collections.emptyList()); + assertInvalid(sub2); + + // null policy type item + sub2 = new PdpSubGroup(subgrp); + sub2.getSupportedPolicyTypes().set(0, null); + assertInvalid(sub2); + + // invalid policy type item + sub2 = new PdpSubGroup(subgrp); + sub2.getSupportedPolicyTypes().set(0, makeIdent(null, "3.0.0", ToscaPolicyTypeIdentifier.class)); + assertInvalid(sub2); + + // null policies + sub2 = new PdpSubGroup(subgrp); + sub2.setPolicies(null); + assertInvalid(sub2); + + // null policy item + sub2 = new PdpSubGroup(subgrp); + sub2.getPolicies().set(0, null); + assertInvalid(sub2); + + // invalid policy item + sub2 = new PdpSubGroup(subgrp); + sub2.getPolicies().set(0, makeIdent(null, "3.0.0", ToscaPolicyIdentifier.class)); + assertInvalid(sub2); + } + + private void assertInvalid(PdpSubGroup sub2) { + ValidationResult result = sub2.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + } + + /** + * Makes an identifier. Uses JSON which does no error checking. + * + * @param name name to put into the identifier + * @param version version to put into the identifier + * @param clazz type of identifier to create + * @return a new identifier + * @throws CoderException if the JSON cannot be decoded + */ + public <T> T makeIdent(String name, String version, Class<T> clazz) throws CoderException { + StringBuilder bldr = new StringBuilder(); + bldr.append("{"); + + if (name != null) { + bldr.append("'name':'"); + bldr.append(name); + bldr.append("'"); + } + + if (version != null) { + if (name != null) { + bldr.append(','); + } + + bldr.append("'version':'"); + bldr.append(version); + bldr.append("'"); + } + + bldr.append("}"); + + String json = bldr.toString().replace('\'', '"'); + + return coder.decode(json, clazz); + } } diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpUpdateTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpUpdateTest.java index 8889e483f..2dfcb30fe 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpUpdateTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/PdpUpdateTest.java @@ -41,6 +41,7 @@ public class PdpUpdateTest { assertThatThrownBy(() -> new PdpUpdate(null)).isInstanceOf(NullPointerException.class); PdpUpdate orig = new PdpUpdate(); + orig.setPolicies(null); // verify with null values assertEquals(removeVariableFields(orig.toString()), removeVariableFields(new PdpUpdate(orig).toString())); diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java index e75743e40..c0545fa36 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpGroupTest.java @@ -98,16 +98,8 @@ public class JpaPdpGroupTest { JpaPdpGroup testJpaPdpGroup = new JpaPdpGroup(); testJpaPdpGroup.setKey(null); - assertThatThrownBy(() -> { - testJpaPdpGroup.fromAuthorative(testPdpGroup); - }).hasMessage("version is marked @NonNull but is null"); - testJpaPdpGroup.setKey(new PfConceptKey()); - assertThatThrownBy(() -> { - testJpaPdpGroup.fromAuthorative(testPdpGroup); - }).hasMessage("version is marked @NonNull but is null"); - testPdpGroup.setVersion("1.0.0"); testJpaPdpGroup.fromAuthorative(testPdpGroup); diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java index 5a27210fc..ebdf31c2f 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpTest.java @@ -149,6 +149,8 @@ public class JpaPdpTest { testJpaPdp.setKey(savedKey); assertTrue(testJpaPdp.validate(new PfValidationResult()).isOk()); + testJpaPdp.setMessage(null); + assertTrue(testJpaPdp.validate(new PfValidationResult()).isOk()); testJpaPdp.setMessage(""); assertFalse(testJpaPdp.validate(new PfValidationResult()).isOk()); testJpaPdp.setMessage("Valid Message"); diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java index bc77e4bb8..f0af69ea4 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpProviderTest.java @@ -26,11 +26,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; -import java.sql.Connection; -import java.sql.DriverManager; import java.util.ArrayList; import java.util.List; +import java.util.Properties; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -60,7 +60,6 @@ import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; * @author Liam Fallon (liam.fallon@est.tech) */ public class PdpProviderTest { - private Connection connection; private PfDao pfDao; private StandardCoder standardCoder; @@ -72,17 +71,21 @@ public class PdpProviderTest { */ @Before public void setupDao() throws Exception { - // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database - // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance - connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); - final DaoParameters daoParameters = new DaoParameters(); daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); - // Use the persistence unit ToscaConceptTest to test towards the h2 database - // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance daoParameters.setPersistenceUnit("ToscaConceptTest"); + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); + + // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + + daoParameters.setJdbcProperties(jdbcProperties ); + pfDao = new PfDaoFactory().createPfDao(daoParameters); pfDao.init(daoParameters); } @@ -98,21 +101,16 @@ public class PdpProviderTest { @After public void teardown() throws Exception { pfDao.close(); - connection.close(); } @Test public void testGroupsGet() throws Exception { assertThatThrownBy(() -> { - new PdpProvider().getPdpGroups(null, null, null); + new PdpProvider().getPdpGroups(null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().getPdpGroups(null, null, "version"); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().getPdpGroups(null, "name", "version"); + new PdpProvider().getPdpGroups(null, "name"); }).hasMessage("dao is marked @NonNull but is null"); String originalJson = ResourceUtils.getResourceAsString("testdata/PdpGroups0.json"); @@ -124,7 +122,7 @@ public class PdpProviderTest { assertEquals(originalJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0")); String gotJson = standardCoder.encode(gotPdpGroups0); @@ -160,7 +158,6 @@ public class PdpProviderTest { final PdpGroupFilter filter = PdpGroupFilter.builder() .groupState(PdpState.PASSIVE) .name("PdpGroup0") - .version("1.2.3") .matchPoliciesExactly(false) .matchPolicyTypesExactly(false) .pdpState(PdpState.PASSIVE) @@ -195,7 +192,7 @@ public class PdpProviderTest { assertEquals(originalJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0")); String gotJson = standardCoder.encode(gotPdpGroups0); assertEquals(originalJson.replaceAll("\\s+", ""), gotJson.replaceAll("\\s+", "")); @@ -221,7 +218,7 @@ public class PdpProviderTest { assertEquals(originalTweakedJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "TestPdpGroup", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "TestPdpGroup")); String gotJson = standardCoder.encode(gotPdpGroups0); assertEquals(originalTweakedJson.replaceAll("\\s+", ""), gotJson.replaceAll("\\s+", "")); @@ -250,7 +247,7 @@ public class PdpProviderTest { assertEquals(originalJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0")); String gotJson = standardCoder.encode(gotPdpGroups0); assertEquals(originalJson.replaceAll("\\s+", ""), gotJson.replaceAll("\\s+", "")); @@ -274,32 +271,20 @@ public class PdpProviderTest { @Test public void testPoliciesDelete() throws Exception { assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(null, null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(null, null, "version"); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(null, "name", null); + new PdpProvider().deletePdpGroup(null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(null, "name", "version"); + new PdpProvider().deletePdpGroup(null, "name"); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(pfDao, null, "version"); + new PdpProvider().deletePdpGroup(pfDao, null); }).hasMessage("name is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(pfDao, "name", null); - }).hasMessage("version is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(pfDao, "name", "version"); - }).hasMessage("delete of PDP group \"name:version\" failed, PDP group does not exist"); + new PdpProvider().deletePdpGroup(pfDao, "name"); + }).hasMessage("delete of PDP group \"name:0.0.0\" failed, PDP group does not exist"); String originalJson = ResourceUtils.getResourceAsString("testdata/PdpGroups0.json"); PdpGroups pdpGroups0 = standardCoder.decode(originalJson, PdpGroups.class); @@ -310,82 +295,54 @@ public class PdpProviderTest { assertEquals(originalJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0")); String gotJson = standardCoder.encode(gotPdpGroups0); assertEquals(originalJson.replaceAll("\\s+", ""), gotJson.replaceAll("\\s+", "")); - PdpGroup deletedPdpGroup = new PdpProvider().deletePdpGroup(pfDao, "PdpGroup0", "1.2.3"); + PdpGroup deletedPdpGroup = new PdpProvider().deletePdpGroup(pfDao, "PdpGroup0"); assertEquals(createdPdpGroups0.getGroups().get(0), deletedPdpGroup); - assertEquals(0, new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3").size()); + assertEquals(0, new PdpProvider().getPdpGroups(pfDao, "PdpGroup0").size()); assertThatThrownBy(() -> { - new PdpProvider().deletePdpGroup(pfDao, "PdpGroup0", "1.2.3"); - }).hasMessage("delete of PDP group \"PdpGroup0:1.2.3\" failed, PDP group does not exist"); + new PdpProvider().deletePdpGroup(pfDao, "PdpGroup0"); + }).hasMessage("delete of PDP group \"PdpGroup0:0.0.0\" failed, PDP group does not exist"); } @Test public void testPdpSubgroupUpdate() throws Exception { assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, null, null, null); + new PdpProvider().updatePdpSubGroup(null, null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, null, null, new PdpSubGroup()); + new PdpProvider().updatePdpSubGroup(null, null, new PdpSubGroup()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, null, "version", null); + new PdpProvider().updatePdpSubGroup(null, "name", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, null, "version", new PdpSubGroup()); + new PdpProvider().updatePdpSubGroup(null, "name", new PdpSubGroup()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, "name", null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, "name", null, new PdpSubGroup()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, "name", "version", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(null, "name", "version", new PdpSubGroup()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, null, null, new PdpSubGroup()); + new PdpProvider().updatePdpSubGroup(pfDao, null, null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, null, "version", null); + new PdpProvider().updatePdpSubGroup(pfDao, null, new PdpSubGroup()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, null, "version", new PdpSubGroup()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, "name", null, null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, "name", null, new PdpSubGroup()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, "name", "version", null); + new PdpProvider().updatePdpSubGroup(pfDao, "name", null); }).hasMessage("pdpSubGroup is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, "name", "version", new PdpSubGroup()); + new PdpProvider().updatePdpSubGroup(pfDao, "name", new PdpSubGroup()); }).hasMessage("parameter \"localName\" is null"); String originalJson = ResourceUtils.getResourceAsString("testdata/PdpGroups0.json"); @@ -397,7 +354,7 @@ public class PdpProviderTest { assertEquals(originalJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0")); String gotJson = standardCoder.encode(gotPdpGroups0); assertEquals(originalJson.replaceAll("\\s+", ""), gotJson.replaceAll("\\s+", "")); @@ -405,154 +362,83 @@ public class PdpProviderTest { PdpSubGroup existingSubGroup = gotPdpGroups0.getGroups().get(0).getPdpSubgroups().get(0); existingSubGroup.setCurrentInstanceCount(10); existingSubGroup.setDesiredInstanceCount(10); - new PdpProvider().updatePdpSubGroup(pfDao, "PdpGroup0", "1.2.3", existingSubGroup); + new PdpProvider().updatePdpSubGroup(pfDao, "PdpGroup0", existingSubGroup); - List<PdpGroup> afterUpdatePdpGroups = new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3"); + List<PdpGroup> afterUpdatePdpGroups = new PdpProvider().getPdpGroups(pfDao, "PdpGroup0"); assertEquals(10, afterUpdatePdpGroups.get(0).getPdpSubgroups().get(0).getCurrentInstanceCount()); assertEquals(10, afterUpdatePdpGroups.get(0).getPdpSubgroups().get(0).getDesiredInstanceCount()); existingSubGroup.setDesiredInstanceCount(-1); assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, "PdpGroup0", "1.2.3", existingSubGroup); + new PdpProvider().updatePdpSubGroup(pfDao, "PdpGroup0", existingSubGroup); }).hasMessageContaining("INVALID:the desired instance count of a PDP sub group may not be negative"); existingSubGroup.setDesiredInstanceCount(10); - - existingSubGroup.setPdpType("Loooooooooooooooooooooooooooooooooooooooo" - + "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooongKey"); - assertThatThrownBy(() -> { - new PdpProvider().updatePdpSubGroup(pfDao, "PdpGroup0", "1.2.3", existingSubGroup); - }).hasMessageContaining("Value too long for column"); - existingSubGroup.setPdpType("APEX"); } @Test public void testPdpUpdate() throws Exception { assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, null, null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, null, null, new Pdp()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, null, "TYPE", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, null, "TYPE", new Pdp()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, "version", null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, "version", null, new Pdp()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, "version", "TYPE", null); + new PdpProvider().updatePdp(null, null, null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, null, "version", "TYPE", new Pdp()); + new PdpProvider().updatePdp(null, null, null, new Pdp()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", null, null, null); + new PdpProvider().updatePdp(null, null, "TYPE", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", null, null, new Pdp()); + new PdpProvider().updatePdp(null, null, "TYPE", new Pdp()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", null, "TYPE", null); + new PdpProvider().updatePdp(null, "name", null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", null, "TYPE", new Pdp()); + new PdpProvider().updatePdp(null, "name", null, new Pdp()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", "version", null, null); + new PdpProvider().updatePdp(null, "name", "TYPE", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", "version", null, new Pdp()); + new PdpProvider().updatePdp(null, "name", "TYPE", new Pdp()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", "version", "TYPE", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(null, "name", "version", "TYPE", new Pdp()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, null, null, null); + new PdpProvider().updatePdp(pfDao, null, null, null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, null, null, new Pdp()); + new PdpProvider().updatePdp(pfDao, null, null, new Pdp()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, null, "TYPE", null); + new PdpProvider().updatePdp(pfDao, null, "TYPE", null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, null, "TYPE", new Pdp()); + new PdpProvider().updatePdp(pfDao, null, "TYPE", new Pdp()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, "version", null, null); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, "version", null, new Pdp()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, "version", "TYPE", null); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, null, "version", "TYPE", new Pdp()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", null, null, null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", null, null, new Pdp()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", null, "TYPE", null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", null, "TYPE", new Pdp()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", "version", null, null); + new PdpProvider().updatePdp(pfDao, "name", null, null); }).hasMessage("pdpSubGroup is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", "version", null, new Pdp()); + new PdpProvider().updatePdp(pfDao, "name", null, new Pdp()); }).hasMessage("pdpSubGroup is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", "version", "TYPE", null); + new PdpProvider().updatePdp(pfDao, "name", "TYPE", null); }).hasMessage("pdp is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "name", "version", "TYPE", new Pdp()); + new PdpProvider().updatePdp(pfDao, "name", "TYPE", new Pdp()); }).hasMessage("parameter \"localName\" is null"); String originalJson = ResourceUtils.getResourceAsString("testdata/PdpGroups0.json"); @@ -564,7 +450,7 @@ public class PdpProviderTest { assertEquals(originalJson.replaceAll("\\s+", ""), createdJson.replaceAll("\\s+", "")); PdpGroups gotPdpGroups0 = new PdpGroups(); - gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3")); + gotPdpGroups0.setGroups(new PdpProvider().getPdpGroups(pfDao, "PdpGroup0")); String gotJson = standardCoder.encode(gotPdpGroups0); assertEquals(originalJson.replaceAll("\\s+", ""), gotJson.replaceAll("\\s+", "")); @@ -572,9 +458,9 @@ public class PdpProviderTest { Pdp existingPdp = gotPdpGroups0.getGroups().get(0).getPdpSubgroups().get(0).getPdpInstances().get(0); existingPdp.setPdpState(PdpState.TEST); existingPdp.setHealthy(PdpHealthStatus.TEST_IN_PROGRESS); - new PdpProvider().updatePdp(pfDao, "PdpGroup0", "1.2.3", "APEX", existingPdp); + new PdpProvider().updatePdp(pfDao, "PdpGroup0", "APEX", existingPdp); - List<PdpGroup> afterUpdatePdpGroups = new PdpProvider().getPdpGroups(pfDao, "PdpGroup0", "1.2.3"); + List<PdpGroup> afterUpdatePdpGroups = new PdpProvider().getPdpGroups(pfDao, "PdpGroup0"); assertEquals(PdpState.TEST, afterUpdatePdpGroups.get(0).getPdpSubgroups().get(0).getPdpInstances().get(0).getPdpState()); assertEquals(PdpHealthStatus.TEST_IN_PROGRESS, @@ -582,7 +468,7 @@ public class PdpProviderTest { existingPdp.setMessage(""); assertThatThrownBy(() -> { - new PdpProvider().updatePdp(pfDao, "PdpGroup0", "1.2.3", "APEX", existingPdp); + new PdpProvider().updatePdp(pfDao, "PdpGroup0", "APEX", existingPdp); }).hasMessageContaining("INVALID:message may not be blank"); existingPdp.setMessage("A Message"); } @@ -590,274 +476,142 @@ public class PdpProviderTest { @Test public void testGetPdpStatistics() throws PfModelException { assertThatThrownBy(() -> { - new PdpProvider().getPdpStatistics(null, null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().getPdpStatistics(null, null, "version"); + new PdpProvider().getPdpStatistics(null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().getPdpStatistics(null, "name", null); + new PdpProvider().getPdpStatistics(null, "name"); }).hasMessage("dao is marked @NonNull but is null"); - assertEquals(0, new PdpProvider().getPdpStatistics(pfDao, "name", "version").size()); + assertEquals(0, new PdpProvider().getPdpStatistics(pfDao, "name").size()); } @Test public void testUpdatePdpStatistics() throws PfModelException { assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, null, null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, null, null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, null, null, null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, null, "inst", null); + new PdpProvider().updatePdpStatistics(null, null, null, null, new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, null, "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, null, null, "inst", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, "TYPE", null, null); + new PdpProvider().updatePdpStatistics(null, null, null, "inst", new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, "TYPE", null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, null, "TYPE", null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, "TYPE", "inst", null); + new PdpProvider().updatePdpStatistics(null, null, "TYPE", null, new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, null, "TYPE", "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, null, "TYPE", "inst", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", null, null, null); + new PdpProvider().updatePdpStatistics(null, null, "TYPE", "inst", new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", null, null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, "name", null, null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", null, "inst", null); + new PdpProvider().updatePdpStatistics(null, "name", null, null, new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", null, "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, "name", null, "inst", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", "TYPE", null, null); + new PdpProvider().updatePdpStatistics(null, "name", null, "inst", new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", "TYPE", null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, "name", "TYPE", null, null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", "TYPE", "inst", null); + new PdpProvider().updatePdpStatistics(null, "name", "TYPE", null, new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, null, "version", "TYPE", "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(null, "name", "TYPE", "inst", null); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, null, null, null); + new PdpProvider().updatePdpStatistics(null, "name", "TYPE", "inst", new PdpStatistics()); }).hasMessage("dao is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, null, null, new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, null, "inst", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, null, "inst", new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, "TYPE", null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, "TYPE", null, new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, "TYPE", "inst", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", null, "TYPE", "inst", new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", null, null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", null, null, new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", null, "inst", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", null, "inst", new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", "TYPE", null, null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", "TYPE", null, new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", "TYPE", "inst", null); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(null, "name", "version", "TYPE", "inst", new PdpStatistics()); - }).hasMessage("dao is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, null, null, null); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, null, null, new PdpStatistics()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, null, "inst", null); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, null, "inst", new PdpStatistics()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, "TYPE", null, null); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, "TYPE", null, new PdpStatistics()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, "TYPE", "inst", null); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, null, "TYPE", "inst", new PdpStatistics()); - }).hasMessage("pdpGroupName is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", null, null, null); + new PdpProvider().updatePdpStatistics(pfDao, null, null, null, null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", null, null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, null, null, null, new PdpStatistics()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", null, "inst", null); + new PdpProvider().updatePdpStatistics(pfDao, null, null, "inst", null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", null, "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, null, null, "inst", new PdpStatistics()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", "TYPE", null, null); + new PdpProvider().updatePdpStatistics(pfDao, null, "TYPE", null, null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", "TYPE", null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, null, "TYPE", null, new PdpStatistics()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", "TYPE", "inst", null); + new PdpProvider().updatePdpStatistics(pfDao, null, "TYPE", "inst", null); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, null, "version", "TYPE", "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, null, "TYPE", "inst", new PdpStatistics()); }).hasMessage("pdpGroupName is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, null, null, null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, null, null, new PdpStatistics()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, null, "inst", null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, null, "inst", new PdpStatistics()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, "TYPE", null, null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, "TYPE", null, new PdpStatistics()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, "TYPE", "inst", null); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", null, "TYPE", "inst", new PdpStatistics()); - }).hasMessage("pdpGroupVersion is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", null, null, null); + new PdpProvider().updatePdpStatistics(pfDao, "name", null, null, null); }).hasMessage("pdpType is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", null, null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, "name", null, null, new PdpStatistics()); }).hasMessage("pdpType is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", null, "inst", null); + new PdpProvider().updatePdpStatistics(pfDao, "name", null, "inst", null); }).hasMessage("pdpType is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", null, "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, "name", null, "inst", new PdpStatistics()); }).hasMessage("pdpType is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", "TYPE", null, null); + new PdpProvider().updatePdpStatistics(pfDao, "name", "TYPE", null, null); }).hasMessage("pdpInstanceId is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", "TYPE", null, new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, "name", "TYPE", null, new PdpStatistics()); }).hasMessage("pdpInstanceId is marked @NonNull but is null"); assertThatThrownBy(() -> { - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", "TYPE", "inst", null); + new PdpProvider().updatePdpStatistics(pfDao, "name", "TYPE", "inst", null); }).hasMessage("pdpStatistics is marked @NonNull but is null"); - new PdpProvider().updatePdpStatistics(pfDao, "name", "version", "TYPE", "inst", new PdpStatistics()); + new PdpProvider().updatePdpStatistics(pfDao, "name", "TYPE", "inst", new PdpStatistics()); } } diff --git a/models-pdp/src/test/resources/META-INF/persistence.xml b/models-pdp/src/test/resources/META-INF/persistence.xml index 079ba4993..9d78e3abd 100644 --- a/models-pdp/src/test/resources/META-INF/persistence.xml +++ b/models-pdp/src/test/resources/META-INF/persistence.xml @@ -33,34 +33,9 @@ <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdp</class> <properties> - <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" /> - <property name="javax.persistence.jdbc.user" value="policy" /> - <property name="javax.persistence.jdbc.password" value="P01icY" /> <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> <property name="eclipselink.logging.level" value="INFO" /> - </properties> - </persistence-unit> - - <persistence-unit name="ToscaConceptMariaDBTest" transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - - <class>org.onap.policy.models.dao.converters.CDataConditioner</class> - <class>org.onap.policy.models.dao.converters.Uuid2String</class> - <class>org.onap.policy.models.base.PfConceptKey</class> - <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class> - <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdp</class> - - <properties> - <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/policy" /> - <property name="javax.persistence.jdbc.user" value="policy" /> - <property name="javax.persistence.jdbc.password" value="P01icY" /> - <property name="javax.persistence.schema-generation.database.action" value="create" /> <property name="eclipselink.logging.level" value="ALL" /> <property name="eclipselink.logging.level.jpa" value="ALL" /> @@ -72,10 +47,6 @@ <property name="eclipselink.logging.level.server" value="ALL" /> <property name="eclipselink.logging.level.query" value="ALL" /> <property name="eclipselink.logging.level.properties" value="ALL" /> - - <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> - <property name="eclipselink.ddl-generation.output-mode" value="database" /> - <property name="eclipselink.logging.level" value="INFO" /> </properties> </persistence-unit> </persistence> diff --git a/models-pdp/src/test/resources/testdata/PdpGroups0.json b/models-pdp/src/test/resources/testdata/PdpGroups0.json index 6ebdd6c7a..01e140cd8 100644 --- a/models-pdp/src/test/resources/testdata/PdpGroups0.json +++ b/models-pdp/src/test/resources/testdata/PdpGroups0.json @@ -2,7 +2,6 @@ "groups": [ { "name": "PdpGroup0", - "version": "1.2.3", "description": "group description", "pdpGroupState": "PASSIVE", "properties": { diff --git a/models-pdp/src/test/resources/testdata/PdpGroups0Update.json b/models-pdp/src/test/resources/testdata/PdpGroups0Update.json index a54ec53ea..05594fa47 100644 --- a/models-pdp/src/test/resources/testdata/PdpGroups0Update.json +++ b/models-pdp/src/test/resources/testdata/PdpGroups0Update.json @@ -2,7 +2,6 @@ "groups": [ { "name": "PdpGroup0", - "version": "1.2.3", "description": "group description", "pdpGroupState": "PASSIVE", "properties": { diff --git a/models-pdp/src/test/resources/testdata/PdpGroupsForFiltering.json b/models-pdp/src/test/resources/testdata/PdpGroupsForFiltering.json index f9c822b06..f1d4378fd 100644 --- a/models-pdp/src/test/resources/testdata/PdpGroupsForFiltering.json +++ b/models-pdp/src/test/resources/testdata/PdpGroupsForFiltering.json @@ -2,7 +2,6 @@ "groups": [ { "name": "PdpGroup0", - "version": "1.2.3", "description": "group description", "pdpGroupState": "PASSIVE", "properties": { @@ -70,8 +69,7 @@ ] }, { - "name": "PdpGroup0", - "version": "1.2.4", + "name": "PdpGroup10", "description": "group description", "pdpGroupState": "ACTIVE", "properties": { @@ -117,8 +115,7 @@ ] }, { - "name": "PdpGroup0", - "version": "1.2.1", + "name": "PdpGroup20", "description": "group description", "pdpGroupState": "SAFE", "properties": { @@ -193,7 +190,6 @@ }, { "name": "PdpGroup1", - "version": "1.2.1", "description": "group description", "pdpGroupState": "PASSIVE", "properties": { @@ -235,8 +231,7 @@ ] }, { - "name": "PdpGroup1", - "version": "1.2.3", + "name": "PdpGroup11", "description": "group description", "pdpGroupState": "TEST", "properties": { diff --git a/models-provider/pom.xml b/models-provider/pom.xml index fb0e302dd..41a5a2cfe 100644 --- a/models-provider/pom.xml +++ b/models-provider/pom.xml @@ -69,12 +69,6 @@ </dependency> <dependency> - <groupId>org.mariadb.jdbc</groupId> - <artifactId>mariadb-java-client</artifactId> - <scope>test</scope> - </dependency> - - <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <scope>test</scope> diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java b/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java index cf40a57f9..a7d414533 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java @@ -278,11 +278,10 @@ public interface PolicyModelsProvider extends AutoCloseable { * Get PDP groups. * * @param name the name of the policy to get, null to get all PDP groups - * @param version the version of the policy to get, null to get all versions of a PDP group * @return the PDP groups found * @throws PfModelException on errors getting PDP groups */ - public List<PdpGroup> getPdpGroups(final String name, final String version) throws PfModelException; + public List<PdpGroup> getPdpGroups(final String name) throws PfModelException; /** * Get filtered PDP groups. @@ -315,55 +314,50 @@ public interface PolicyModelsProvider extends AutoCloseable { * Update a PDP subgroup. * * @param pdpGroupName the name of the PDP group of the PDP subgroup - * @param pdpGroupVersion the version of the PDP group of the PDP subgroup * @param pdpSubGroup the PDP subgroup to be updated * @throws PfModelException on errors updating PDP subgroups */ - public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException; + public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup) + throws PfModelException; /** * Update a PDP. * * @param pdpGroupName the name of the PDP group of the PDP subgroup - * @param pdpGroupVersion the version of the PDP group of the PDP subgroup * @param pdpSubGroup the PDP subgroup to be updated * @param pdp the PDP to be updated * @throws PfModelException on errors updating PDP subgroups */ - public void updatePdp(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final String pdpSubGroup, @NonNull final Pdp pdp) throws PfModelException; + public void updatePdp(@NonNull final String pdpGroupName, @NonNull final String pdpSubGroup, @NonNull final Pdp pdp) + throws PfModelException; /** * Delete a PDP group. * * @param name the name of the policy to get, null to get all PDP groups - * @param version the version of the policy to get, null to get all versions of a PDP group * @return the PDP group deleted * @throws PfModelException on errors deleting PDP groups */ - public PdpGroup deletePdpGroup(@NonNull final String name, @NonNull final String version) throws PfModelException; + public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException; /** * Get PDP statistics. * * @param name the name of the PDP group to get statistics for, null to get all PDP groups - * @param version the version of the PDP group to get statistics for, null to get all versions of a PDP group * @return the statistics found * @throws PfModelException on errors getting statistics */ - public List<PdpStatistics> getPdpStatistics(final String name, final String version) throws PfModelException; + public List<PdpStatistics> getPdpStatistics(final String name) throws PfModelException; /** * Update PDP statistics for a PDP. * * @param pdpGroupName the name of the PDP group containing the PDP that the statistics are for - * @param pdpGroupVersion the version of the PDP group containing the PDP that the statistics are for * @param pdpType the PDP type of the subgroup containing the PDP that the statistics are for * @param pdpInstanceId the instance ID of the PDP to update statistics for + * @param pdpStatistics the PDP statistics * @throws PfModelException on errors updating statistics */ - public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final String pdpType, @NonNull final String pdpInstanceId, - @NonNull final PdpStatistics pdppStatistics) throws PfModelException; + public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpType, + @NonNull final String pdpInstanceId, @NonNull final PdpStatistics pdpStatistics) throws PfModelException; } diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProviderParameters.java b/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProviderParameters.java index 5abafed22..65aa72eb2 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProviderParameters.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProviderParameters.java @@ -55,6 +55,7 @@ public class PolicyModelsProviderParameters implements ParameterGroup { private String name; private String implementation = DEFAULT_IMPLEMENTATION; + private String databaseDriver; private String databaseUrl; private String databaseUser; private String databasePassword; @@ -73,6 +74,11 @@ public class PolicyModelsProviderParameters implements ParameterGroup { "a PolicyModelsProvider implementation must be specified"); } + if (!ParameterValidationUtils.validateStringParameter(databaseDriver)) { + validationResult.setResult("databaseUrl", ValidationStatus.INVALID, + "a driver must be specified for the JDBC connection to the database"); + } + if (!ParameterValidationUtils.validateStringParameter(databaseUrl)) { validationResult.setResult("databaseUrl", ValidationStatus.INVALID, "a URL must be specified for the JDBC connection to the database"); diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java index 2fe52e935..a6e8f325b 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java @@ -20,16 +20,16 @@ package org.onap.policy.models.provider.impl; -import java.sql.Connection; -import java.sql.DriverManager; import java.util.Base64; import java.util.List; import java.util.Map; +import java.util.Properties; import javax.ws.rs.core.Response; import lombok.NonNull; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.dao.DaoParameters; @@ -64,12 +64,12 @@ import org.slf4j.LoggerFactory; * @author Liam Fallon (liam.fallon@est.tech) */ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultPfDao.class); private final PolicyModelsProviderParameters parameters; // Database connection and the DAO for reading and writing Policy Framework concepts - private Connection connection; private PfDao pfDao; /** @@ -86,30 +86,31 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { LOGGER.debug("opening the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(), parameters.getPersistenceUnit()); - if (connection != null || pfDao != null) { + if (pfDao != null) { String errorMessage = "provider is already initialized"; LOGGER.warn(errorMessage); throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage); } - // Decode the password using Base64 - String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword())); - - // Connect to the database, call does not implement AutoCloseable for try-with-resources - try { - connection = DriverManager.getConnection(parameters.getDatabaseUrl(), parameters.getDatabaseUser(), - decodedPassword); - } catch (Exception exc) { - String errorMessage = "could not connect to database with URL \"" + parameters.getDatabaseUrl() + "\""; - LOGGER.warn(errorMessage, exc); - throw new PfModelException(Response.Status.NOT_ACCEPTABLE, errorMessage, exc); - } - // Parameters for the DAO final DaoParameters daoParameters = new DaoParameters(); daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); daoParameters.setPersistenceUnit(parameters.getPersistenceUnit()); + // Decode the password using Base64 + String decodedPassword = new String(Base64.getDecoder().decode(parameters.getDatabasePassword())); + + // @formatter:off + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, parameters.getDatabaseDriver()); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, parameters.getDatabaseUrl()); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, parameters.getDatabaseUser()); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, decodedPassword); + // @formatter:on + + daoParameters.setJdbcProperties(jdbcProperties); + + pfDao = new PfDaoFactory().createPfDao(daoParameters); try { pfDao = new PfDaoFactory().createPfDao(daoParameters); pfDao.init(daoParameters); @@ -133,20 +134,6 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { pfDao = null; } - if (connection != null) { - try { - connection.close(); - } catch (Exception exc) { - - String errorMessage = - "could not close connection to database with URL \"" + parameters.getDatabaseUrl() + "\""; - LOGGER.warn(errorMessage, exc); - throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, exc); - } finally { - connection = null; - } - } - LOGGER.debug("closed the database connection to {} using persistence unit {}", parameters.getDatabaseUrl(), parameters.getPersistenceUnit()); } @@ -297,9 +284,9 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { } @Override - public List<PdpGroup> getPdpGroups(final String name, final String version) throws PfModelException { + public List<PdpGroup> getPdpGroups(final String name) throws PfModelException { assertInitilized(); - return new PdpProvider().getPdpGroups(pfDao, name, version); + return new PdpProvider().getPdpGroups(pfDao, name); } @Override @@ -321,37 +308,36 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { } @Override - public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException { + public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final PdpSubGroup pdpSubGroup) + throws PfModelException { assertInitilized(); - new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpGroupVersion, pdpSubGroup); + new PdpProvider().updatePdpSubGroup(pfDao, pdpGroupName, pdpSubGroup); } @Override - public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion, - @NonNull String pdpSubGroup, @NonNull Pdp pdp) throws PfModelException { - new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpGroupVersion, pdpSubGroup, pdp); + public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp) + throws PfModelException { + new PdpProvider().updatePdp(pfDao, pdpGroupName, pdpSubGroup, pdp); } @Override - public PdpGroup deletePdpGroup(@NonNull final String name, @NonNull final String version) throws PfModelException { + public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException { assertInitilized(); - return new PdpProvider().deletePdpGroup(pfDao, name, version); + return new PdpProvider().deletePdpGroup(pfDao, name); } @Override - public List<PdpStatistics> getPdpStatistics(final String name, final String version) throws PfModelException { + public List<PdpStatistics> getPdpStatistics(final String name) throws PfModelException { assertInitilized(); - return new PdpProvider().getPdpStatistics(pfDao, name, version); + return new PdpProvider().getPdpStatistics(pfDao, name); } @Override - public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final String pdpType, @NonNull final String pdpInstanceId, - @NonNull final PdpStatistics pdppStatistics) throws PfModelException { + public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpType, + @NonNull final String pdpInstanceId, @NonNull final PdpStatistics pdpStatistics) throws PfModelException { assertInitilized(); - new PdpProvider().updatePdpStatistics(pfDao, pdpGroupName, pdpGroupVersion, pdpType, pdpInstanceId, - pdppStatistics); + new PdpProvider().updatePdpStatistics(pfDao, pdpGroupName, pdpType, pdpInstanceId, + pdpStatistics); } /** @@ -364,13 +350,4 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); } } - - /** - * Hook for unit test mocking of database connection. - * - * @param client the mocked client - */ - protected void setConnection(final Connection connection) { - this.connection = connection; - } } diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java index 0bf529730..9b1ca7669 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java @@ -27,7 +27,6 @@ import java.util.List; import java.util.Map; import javax.ws.rs.core.Response; -import lombok.NonNull; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; @@ -61,7 +60,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { * * @param parameters the parameters for the provider */ - public DummyPolicyModelsProviderImpl(@NonNull final PolicyModelsProviderParameters parameters) {} + public DummyPolicyModelsProviderImpl(final PolicyModelsProviderParameters parameters) {} @Override public void init() throws PfModelException { @@ -84,30 +83,27 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { } @Override - public ToscaServiceTemplate getFilteredPolicyTypes(@NonNull ToscaPolicyTypeFilter filter) throws PfModelException { - return null; + public ToscaServiceTemplate getFilteredPolicyTypes(ToscaPolicyTypeFilter filter) throws PfModelException { + return getDummyResponse("dummyimpl/DummyToscaPolicyTypeGetResponse.json"); } @Override - public List<ToscaPolicyType> getFilteredPolicyTypeList(@NonNull ToscaPolicyTypeFilter filter) { + public List<ToscaPolicyType> getFilteredPolicyTypeList(ToscaPolicyTypeFilter filter) { return new ArrayList<>(); } @Override - public ToscaServiceTemplate createPolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate) - throws PfModelException { + public ToscaServiceTemplate createPolicyTypes(final ToscaServiceTemplate serviceTemplate) throws PfModelException { return serviceTemplate; } @Override - public ToscaServiceTemplate updatePolicyTypes(@NonNull final ToscaServiceTemplate serviceTemplate) - throws PfModelException { + public ToscaServiceTemplate updatePolicyTypes(final ToscaServiceTemplate serviceTemplate) throws PfModelException { return serviceTemplate; } @Override - public ToscaServiceTemplate deletePolicyType(@NonNull final String name, @NonNull final String version) - throws PfModelException { + public ToscaServiceTemplate deletePolicyType(final String name, final String version) throws PfModelException { return getDummyResponse("dummyimpl/DummyToscaPolicyTypeDeleteResponse.json"); } @@ -122,125 +118,118 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { } @Override - public ToscaServiceTemplate getFilteredPolicies(@NonNull ToscaPolicyFilter filter) throws PfModelException { - return null; + public ToscaServiceTemplate getFilteredPolicies(ToscaPolicyFilter filter) throws PfModelException { + return getDummyResponse("dummyimpl/DummyToscaPolicyGetResponse.json"); } @Override - public List<ToscaPolicy> getFilteredPolicyList(@NonNull ToscaPolicyFilter filter) throws PfModelException { + public List<ToscaPolicy> getFilteredPolicyList(ToscaPolicyFilter filter) throws PfModelException { return new ArrayList<>(); } @Override - public ToscaServiceTemplate createPolicies(@NonNull final ToscaServiceTemplate serviceTemplate) - throws PfModelException { + public ToscaServiceTemplate createPolicies(final ToscaServiceTemplate serviceTemplate) throws PfModelException { return serviceTemplate; } @Override - public ToscaServiceTemplate updatePolicies(@NonNull final ToscaServiceTemplate serviceTemplate) - throws PfModelException { + public ToscaServiceTemplate updatePolicies(final ToscaServiceTemplate serviceTemplate) throws PfModelException { return serviceTemplate; } @Override - public ToscaServiceTemplate deletePolicy(@NonNull final String name, @NonNull final String version) - throws PfModelException { + public ToscaServiceTemplate deletePolicy(final String name, final String version) throws PfModelException { return getDummyResponse("dummyimpl/DummyToscaPolicyDeleteResponse.json"); } @Override - public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException { + public LegacyOperationalPolicy getOperationalPolicy(final String policyId) throws PfModelException { return new LegacyOperationalPolicy(); } @Override - public LegacyOperationalPolicy createOperationalPolicy( - @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { + public LegacyOperationalPolicy createOperationalPolicy(final LegacyOperationalPolicy legacyOperationalPolicy) + throws PfModelException { return legacyOperationalPolicy; } @Override - public LegacyOperationalPolicy updateOperationalPolicy( - @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { + public LegacyOperationalPolicy updateOperationalPolicy(final LegacyOperationalPolicy legacyOperationalPolicy) + throws PfModelException { return legacyOperationalPolicy; } @Override - public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException { + public LegacyOperationalPolicy deleteOperationalPolicy(final String policyId) throws PfModelException { return new LegacyOperationalPolicy(); } @Override - public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(@NonNull final String policyId) throws PfModelException { + public Map<String, LegacyGuardPolicyOutput> getGuardPolicy(final String policyId) throws PfModelException { return new HashMap<>(); } @Override - public Map<String, LegacyGuardPolicyOutput> createGuardPolicy( - @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException { + public Map<String, LegacyGuardPolicyOutput> createGuardPolicy(final LegacyGuardPolicyInput legacyGuardPolicy) + throws PfModelException { return new HashMap<>(); } @Override - public Map<String, LegacyGuardPolicyOutput> updateGuardPolicy( - @NonNull final LegacyGuardPolicyInput legacyGuardPolicy) throws PfModelException { + public Map<String, LegacyGuardPolicyOutput> updateGuardPolicy(final LegacyGuardPolicyInput legacyGuardPolicy) + throws PfModelException { return new HashMap<>(); } @Override - public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(@NonNull final String policyId) - throws PfModelException { + public Map<String, LegacyGuardPolicyOutput> deleteGuardPolicy(final String policyId) throws PfModelException { return new HashMap<>(); } @Override - public List<PdpGroup> getPdpGroups(final String name, final String version) throws PfModelException { + public List<PdpGroup> getPdpGroups(final String name) throws PfModelException { return new ArrayList<>(); } @Override - public List<PdpGroup> getFilteredPdpGroups(@NonNull PdpGroupFilter filter) throws PfModelException { + public List<PdpGroup> getFilteredPdpGroups(PdpGroupFilter filter) throws PfModelException { return new ArrayList<>(); } @Override - public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException { + public List<PdpGroup> createPdpGroups(final List<PdpGroup> pdpGroups) throws PfModelException { return new ArrayList<>(); } @Override - public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) throws PfModelException { + public List<PdpGroup> updatePdpGroups(final List<PdpGroup> pdpGroups) throws PfModelException { return new ArrayList<>(); } @Override - public void updatePdpSubGroup(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final PdpSubGroup pdpSubGroup) throws PfModelException { + public void updatePdpSubGroup(final String pdpGroupName, final PdpSubGroup pdpSubGroup) throws PfModelException { // Not implemented } @Override - public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion, - @NonNull String pdpSubGroup, @NonNull Pdp pdp) throws PfModelException { + public void updatePdp(String pdpGroupName, String pdpSubGroup, Pdp pdp) throws PfModelException { // Not implemented } @Override - public PdpGroup deletePdpGroup(@NonNull final String name, @NonNull final String version) throws PfModelException { + public PdpGroup deletePdpGroup(final String name) throws PfModelException { return null; } @Override - public List<PdpStatistics> getPdpStatistics(final String name, final String version) throws PfModelException { + public List<PdpStatistics> getPdpStatistics(final String name) throws PfModelException { return new ArrayList<>(); } @Override - public void updatePdpStatistics(@NonNull final String pdpGroupName, @NonNull final String pdpGroupVersion, - @NonNull final String pdpType, @NonNull final String pdpInstanceId, - @NonNull final PdpStatistics pdppStatistics) throws PfModelException { + public void updatePdpStatistics(final String pdpGroupName, final String pdpType, final String pdpInstanceId, + final PdpStatistics pdppStatistics) throws PfModelException { // Not implemented } @@ -250,7 +239,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { * @param fileName the file name containing the dummy response * @return the ToscaServiceTemplate with the dummy response */ - protected ToscaServiceTemplate getDummyResponse(@NonNull final String fileName) { + protected ToscaServiceTemplate getDummyResponse(final String fileName) { StandardCoder standardCoder = new StandardCoder(); ToscaServiceTemplate serviceTemplate; diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/PolicyModelsProviderParametersTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/PolicyModelsProviderParametersTest.java index 626d2bf5d..51771ff9a 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/PolicyModelsProviderParametersTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/PolicyModelsProviderParametersTest.java @@ -36,6 +36,7 @@ public class PolicyModelsProviderParametersTest { @Test public void testParameters() { PolicyModelsProviderParameters pars = new PolicyModelsProviderParameters(); + pars.setDatabaseDriver("MichaelsShumacher"); pars.setDatabaseUrl("jdbc://www.acmecorp/roadrunner"); pars.setPersistenceUnit("WileECoyote"); @@ -62,5 +63,12 @@ public class PolicyModelsProviderParametersTest { pars.setPersistenceUnit("WileECoyote"); result = pars.validate(); assertTrue(result.isValid()); + + pars.setDatabaseDriver(null); + result = pars.validate(); + assertFalse(result.isValid()); + pars.setDatabaseDriver("MichaelsShumacher"); + result = pars.validate(); + assertTrue(result.isValid()); } } diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java index 38a5ae114..ccdf45af4 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java @@ -27,13 +27,23 @@ import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Base64; +import java.util.List; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; +import org.onap.policy.models.pdp.concepts.Pdp; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpGroupFilter; +import org.onap.policy.models.pdp.concepts.PdpStatistics; +import org.onap.policy.models.pdp.concepts.PdpSubGroup; +import org.onap.policy.models.pdp.enums.PdpHealthStatus; +import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; @@ -56,41 +66,39 @@ public class DatabasePolicyModelsProviderTest { @Before public void setupParameters() { parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseDriver("org.h2.Driver"); parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setDatabaseUser("policy"); parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); parameters.setPersistenceUnit("ToscaConceptTest"); - } @Test public void testInitAndClose() throws Exception { + assertThatThrownBy(() -> { + new DatabasePolicyModelsProviderImpl(null); + }).hasMessage("parameters is marked @NonNull but is null"); + PolicyModelsProvider databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); parameters.setDatabaseUrl("jdbc://www.acmecorp.nonexist"); - assertThatThrownBy(() -> { - databaseProvider.close(); - databaseProvider.init(); - }).hasMessage("could not connect to database with URL \"jdbc://www.acmecorp.nonexist\""); - - parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); - try { - databaseProvider.init(); databaseProvider.close(); + databaseProvider.init(); } catch (Exception pfme) { fail("test shold not throw an exception here"); } + databaseProvider.close(); + + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setPersistenceUnit("WileECoyote"); - String errorMessage = "could not create Data Access Object (DAO) using url " - + "\"jdbc:h2:mem:testdb\" and persistence unit \"WileECoyote\""; assertThatThrownBy(() -> { databaseProvider.init(); - }).hasMessage(errorMessage); + }).hasMessageContaining("could not create Data Access Object (DAO)"); parameters.setPersistenceUnit("ToscaConceptTest"); @@ -98,40 +106,40 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.init(); databaseProvider.close(); } catch (Exception pfme) { + pfme.printStackTrace(); fail("test shold not throw an exception here"); } + assertThatThrownBy(() -> { + databaseProvider.init(); + databaseProvider.init(); + }).hasMessage("provider is already initialized"); + try { databaseProvider.close(); } catch (Exception pfme) { fail("test shold not throw an exception here"); } - assertThatThrownBy(() -> { - DatabasePolicyModelsProviderImpl databaseProviderImpl = (DatabasePolicyModelsProviderImpl) databaseProvider; - databaseProvider.init(); - databaseProviderImpl.setConnection(new DummyConnection()); + try { databaseProvider.close(); - }).hasMessage("could not close connection to database with URL \"jdbc:h2:mem:testdb\""); + } catch (Exception pfme) { + fail("test shold not throw an exception here"); + } } - @Ignore @Test public void testProviderMethodsNull() throws Exception { PolicyModelsProvider databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); assertThatThrownBy(() -> { - databaseProvider.getPolicyTypes(null, null); - }).hasMessage("name is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - databaseProvider.getPolicyTypes("aaa", null); - }).hasMessage("version is marked @NonNull but is null"); + databaseProvider.getFilteredPolicyTypes(null); + }).hasMessage("filter is marked @NonNull but is null"); assertThatThrownBy(() -> { - databaseProvider.getPolicyTypes(null, "aaa"); - }).hasMessage("name is marked @NonNull but is null"); + databaseProvider.getFilteredPolicyTypeList(null); + }).hasMessage("filter is marked @NonNull but is null"); assertThatThrownBy(() -> { databaseProvider.createPolicyTypes(null); @@ -154,16 +162,12 @@ public class DatabasePolicyModelsProviderTest { }).hasMessage("name is marked @NonNull but is null"); assertThatThrownBy(() -> { - databaseProvider.getPolicies(null, null); - }).hasMessage("name is marked @NonNull but is null"); + databaseProvider.getFilteredPolicies(null); + }).hasMessage("filter is marked @NonNull but is null"); assertThatThrownBy(() -> { - databaseProvider.getPolicies(null, "aaa"); - }).hasMessage("name is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - databaseProvider.getPolicies("aaa", null); - }).hasMessage("version is marked @NonNull but is null"); + databaseProvider.getFilteredPolicyList(null); + }).hasMessage("filter is marked @NonNull but is null"); assertThatThrownBy(() -> { databaseProvider.createPolicies(null); @@ -218,6 +222,10 @@ public class DatabasePolicyModelsProviderTest { }).hasMessage("policyId is marked @NonNull but is null"); assertThatThrownBy(() -> { + databaseProvider.getFilteredPdpGroups(null); + }).hasMessage("filter is marked @NonNull but is null"); + + assertThatThrownBy(() -> { databaseProvider.createPdpGroups(null); }).hasMessage("pdpGroups is marked @NonNull but is null"); @@ -226,11 +234,120 @@ public class DatabasePolicyModelsProviderTest { }).hasMessage("pdpGroups is marked @NonNull but is null"); assertThatThrownBy(() -> { - databaseProvider.deletePdpGroup(null, null); + databaseProvider.updatePdpSubGroup(null, null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpSubGroup(null, new PdpSubGroup()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpSubGroup("name", null); + }).hasMessage("pdpSubGroup is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpSubGroup("name", new PdpSubGroup()); + }).hasMessage("parameter \"localName\" is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp(null, null, null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp(null, null, new Pdp()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp(null, "sub", null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp(null, "sub", new Pdp()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp("name", null, null); + }).hasMessage("pdpSubGroup is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp("name", null, new Pdp()); + }).hasMessage("pdpSubGroup is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp("name", "sub", null); + }).hasMessage("pdp is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdp("name", "sub", new Pdp()); + }).hasMessage("parameter \"localName\" is null"); + + assertThatThrownBy(() -> { + databaseProvider.deletePdpGroup(null); }).hasMessage("name is marked @NonNull but is null"); - databaseProvider.close(); + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, null, null, null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, null, null, new PdpStatistics()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, null, "Instance", null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, null, "Instance", new PdpStatistics()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, "type", null, null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, "type", null, new PdpStatistics()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, "type", "Instance", null); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics(null, "type", "Instance", new PdpStatistics()); + }).hasMessage("pdpGroupName is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", null, null, null); + }).hasMessage("pdpType is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", null, null, new PdpStatistics()); + }).hasMessage("pdpType is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", null, "Instance", null); + }).hasMessage("pdpType is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", null, "Instance", new PdpStatistics()); + }).hasMessage("pdpType is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", "type", null, null); + }).hasMessage("pdpInstanceId is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", "type", null, new PdpStatistics()); + }).hasMessage("pdpInstanceId is marked @NonNull but is null"); + assertThatThrownBy(() -> { + databaseProvider.updatePdpStatistics("name", "type", "Instance", null); + }).hasMessage("pdpStatistics is marked @NonNull but is null"); + + databaseProvider.updatePdpStatistics("name", "type", "Instance", new PdpStatistics()); + + databaseProvider.close(); } @Test @@ -245,15 +362,16 @@ public class DatabasePolicyModelsProviderTest { }).hasMessage("policy models provider is not initilaized"); } - @Ignore @Test public void testProviderMethods() { try (PolicyModelsProvider databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters)) { - assertThatThrownBy(() -> { - databaseProvider.getPolicyTypes("name", "version"); - }).hasMessage("policy type not found: name:version"); + assertEquals(0, databaseProvider.getPolicyTypes("name", "version").getPolicyTypes().get(0).size()); + assertEquals(0, databaseProvider.getPolicyTypeList("name", "version").size()); + assertEquals(0, databaseProvider.getFilteredPolicyTypes(ToscaPolicyTypeFilter.builder().build()) + .getPolicyTypes().get(0).size()); + assertEquals(0, databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().build()).size()); assertThatThrownBy(() -> { databaseProvider.createPolicyTypes(new ToscaServiceTemplate()); @@ -263,13 +381,16 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.updatePolicyTypes(new ToscaServiceTemplate()); }).hasMessage("no policy types specified on service template"); - assertThatThrownBy(() -> { - databaseProvider.deletePolicyType("name", "version"); - }).hasMessage("policy type not found: name:version"); + assertEquals(0, databaseProvider.deletePolicyType("name", "version").getPolicyTypes().get(0).size()); - assertThatThrownBy(() -> { - databaseProvider.getPolicies("name", "version"); - }).hasMessage("policy not found: name:version"); + assertEquals(0, databaseProvider.deletePolicyType("name", "version").getPolicyTypes().get(0).size()); + + assertEquals(0, databaseProvider.getPolicies("name", "version").getToscaTopologyTemplate().getPolicies() + .get(0).size()); + assertEquals(0, databaseProvider.getPolicyList("name", "version").size()); + assertEquals(0, databaseProvider.getFilteredPolicies(ToscaPolicyFilter.builder().build()) + .getToscaTopologyTemplate().getPolicies().get(0).size()); + assertEquals(0, databaseProvider.getFilteredPolicyList(ToscaPolicyFilter.builder().build()).size()); assertThatThrownBy(() -> { databaseProvider.createPolicies(new ToscaServiceTemplate()); @@ -279,9 +400,8 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.updatePolicies(new ToscaServiceTemplate()); }).hasMessage("topology template not specified on service template"); - assertThatThrownBy(() -> { - databaseProvider.deletePolicy("name", "version"); - }).hasMessage("policy not found: name:version"); + assertEquals(0, databaseProvider.deletePolicy("Policy", "0.0.0").getToscaTopologyTemplate().getPolicies() + .get(0).size()); assertThatThrownBy(() -> { databaseProvider.getOperationalPolicy("policy_id"); @@ -315,15 +435,60 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.deleteGuardPolicy("policy_id"); }).hasMessage("no policy found for policy ID: policy_id"); - assertEquals(0, databaseProvider.getPdpGroups("name", "version").size()); + assertEquals(0, databaseProvider.getPdpGroups("name").size()); + assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size()); assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>())); assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>())); + PdpGroup pdpGroup = new PdpGroup(); + pdpGroup.setName("group"); + pdpGroup.setVersion("1.2.3"); + pdpGroup.setPdpGroupState(PdpState.ACTIVE); + pdpGroup.setPdpSubgroups(new ArrayList<>()); + List<PdpGroup> groupList = new ArrayList<>(); + groupList.add(pdpGroup); + + PdpSubGroup pdpSubGroup = new PdpSubGroup(); + pdpSubGroup.setPdpType("type"); + pdpSubGroup.setDesiredInstanceCount(123); + pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>()); + pdpSubGroup.getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier("type", "7.8.9")); + pdpGroup.getPdpSubgroups().add(pdpSubGroup); + + Pdp pdp = new Pdp(); + pdp.setInstanceId("type-0"); + pdp.setMessage("Hello"); + pdp.setPdpState(PdpState.ACTIVE); + pdp.setHealthy(PdpHealthStatus.UNKNOWN); + pdpSubGroup.setPdpInstances(new ArrayList<>()); + pdpSubGroup.getPdpInstances().add(pdp); + + assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0) + .getDesiredInstanceCount()); + assertEquals(1, databaseProvider.getPdpGroups("group").size()); + + pdpSubGroup.setDesiredInstanceCount(234); + databaseProvider.updatePdpSubGroup("group", pdpSubGroup); + assertEquals(234, databaseProvider.getPdpGroups("group").get(0).getPdpSubgroups() + .get(0).getDesiredInstanceCount()); + + assertEquals("Hello", databaseProvider.getPdpGroups("group").get(0).getPdpSubgroups() + .get(0).getPdpInstances().get(0).getMessage()); + pdp.setMessage("Howdy"); + databaseProvider.updatePdp("group", "type", pdp); + assertEquals("Howdy", databaseProvider.getPdpGroups("group").get(0).getPdpSubgroups() + .get(0).getPdpInstances().get(0).getMessage()); + assertThatThrownBy(() -> { - databaseProvider.deletePdpGroup("name", "version"); - }).hasMessage("delete of PDP group \"name:version\" failed, PDP group does not exist"); + databaseProvider.deletePdpGroup("name"); + }).hasMessage("delete of PDP group \"name:0.0.0\" failed, PDP group does not exist"); + + assertEquals(pdpGroup.getName(), databaseProvider.deletePdpGroup("group").getName()); + + assertEquals(0, databaseProvider.getPdpStatistics(null).size()); + databaseProvider.updatePdpStatistics("group", "type", "type-0", new PdpStatistics()); } catch (Exception exc) { LOGGER.warn("test should not throw an exception", exc); fail("test should not throw an exception"); diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java index 61f88741c..3e182c02d 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java @@ -147,7 +147,7 @@ public class DummyBadProviderImpl implements PolicyModelsProvider { } @Override - public List<PdpGroup> getPdpGroups(String name, String version) throws PfModelException { + public List<PdpGroup> getPdpGroups(String name) throws PfModelException { return null; } @@ -162,11 +162,11 @@ public class DummyBadProviderImpl implements PolicyModelsProvider { } @Override - public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion, @NonNull String pdpSubGroup, + public void updatePdp(@NonNull String pdpGroupName, @NonNull String pdpSubGroup, @NonNull Pdp pdp) throws PfModelException {} @Override - public PdpGroup deletePdpGroup(@NonNull String name, @NonNull String verison) throws PfModelException { + public PdpGroup deletePdpGroup(@NonNull String name) throws PfModelException { return null; } @@ -207,15 +207,15 @@ public class DummyBadProviderImpl implements PolicyModelsProvider { } @Override - public void updatePdpSubGroup(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion, + public void updatePdpSubGroup(@NonNull String pdpGroupName, @NonNull PdpSubGroup pdpSubGroup) throws PfModelException {} @Override - public List<PdpStatistics> getPdpStatistics(String name, String version) throws PfModelException { + public List<PdpStatistics> getPdpStatistics(String name) throws PfModelException { return null; } @Override - public void updatePdpStatistics(@NonNull String pdpGroupName, @NonNull String pdpGroupVersion, + public void updatePdpStatistics(@NonNull String pdpGroupName, @NonNull String pdpType, @NonNull String pdpInstanceId, @NonNull PdpStatistics pdppStatistics) {} } diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java index 01da44924..9f02fd7a4 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java @@ -20,7 +20,6 @@ package org.onap.policy.models.provider.impl; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -30,9 +29,15 @@ import static org.junit.Assert.fail; import java.util.ArrayList; import org.junit.Test; +import org.onap.policy.models.pdp.concepts.Pdp; +import org.onap.policy.models.pdp.concepts.PdpGroupFilter; +import org.onap.policy.models.pdp.concepts.PdpStatistics; +import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; @@ -74,11 +79,17 @@ public class DummyPolicyModelsProviderTest { dummyProvider.init(); assertNotNull(dummyProvider.getPolicyTypes("name", "version")); + assertNotNull(dummyProvider.getFilteredPolicyTypes(ToscaPolicyTypeFilter.builder().build())); + assertNotNull(dummyProvider.getPolicyTypeList("name", "version")); + assertNotNull(dummyProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().build())); assertNotNull(dummyProvider.createPolicyTypes(new ToscaServiceTemplate())); assertNotNull(dummyProvider.updatePolicyTypes(new ToscaServiceTemplate())); assertNotNull(dummyProvider.deletePolicyType("name", "version")); assertNotNull(dummyProvider.getPolicies("name", "version")); + assertNotNull(dummyProvider.getFilteredPolicies(ToscaPolicyFilter.builder().build())); + assertNotNull(dummyProvider.getPolicyList("name", "version")); + assertNotNull(dummyProvider.getFilteredPolicyList(ToscaPolicyFilter.builder().build())); assertNotNull(dummyProvider.createPolicies(new ToscaServiceTemplate())); assertNotNull(dummyProvider.updatePolicies(new ToscaServiceTemplate())); assertNotNull(dummyProvider.deletePolicy("name", "version")); @@ -93,47 +104,16 @@ public class DummyPolicyModelsProviderTest { assertNotNull(dummyProvider.updateGuardPolicy(new LegacyGuardPolicyInput())); assertNotNull(dummyProvider.deleteGuardPolicy("policy_id")); - assertTrue(dummyProvider.getPdpGroups("name", "version").isEmpty()); + assertTrue(dummyProvider.getPdpGroups("name").isEmpty()); + assertTrue(dummyProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).isEmpty()); assertTrue(dummyProvider.createPdpGroups(new ArrayList<>()).isEmpty()); assertTrue(dummyProvider.updatePdpGroups(new ArrayList<>()).isEmpty()); - assertNull(dummyProvider.deletePdpGroup("name", "version")); - - - assertThatThrownBy(() -> { - dummyProvider.getOperationalPolicy(null); - }).hasMessage("policyId is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.createOperationalPolicy(null); - }).hasMessage("legacyOperationalPolicy is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.updateOperationalPolicy(null); - }).hasMessage("legacyOperationalPolicy is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.deleteOperationalPolicy(null); - }).hasMessage("policyId is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - dummyProvider.getGuardPolicy(null); - }).hasMessage("policyId is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.createGuardPolicy(null); - }).hasMessage("legacyGuardPolicy is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.updateGuardPolicy(null); - }).hasMessage("legacyGuardPolicy is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.deleteGuardPolicy(null); - }).hasMessage("policyId is marked @NonNull but is null"); - - assertThatThrownBy(() -> { - dummyProvider.createPdpGroups(null); - }).hasMessage("pdpGroups is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.updatePdpGroups(null); - }).hasMessage("pdpGroups is marked @NonNull but is null"); - assertThatThrownBy(() -> { - dummyProvider.deletePdpGroup(null, null); - }).hasMessage("name is marked @NonNull but is null"); + assertNull(dummyProvider.deletePdpGroup("name")); + + dummyProvider.updatePdpSubGroup("name", new PdpSubGroup()); + dummyProvider.updatePdp("name", "type", new Pdp()); + dummyProvider.updatePdpStatistics("name", "type", "type-0", new PdpStatistics()); + assertTrue(dummyProvider.getPdpStatistics("name").isEmpty()); dummyProvider.close(); } @@ -159,7 +139,7 @@ public class DummyPolicyModelsProviderTest { resp.getBadDummyResponse2(); fail("test should throw an exception"); } catch (Exception npe) { - assertEquals("fileName is marked @NonNull but is null", npe.getMessage()); + assertEquals("error serializing object", npe.getMessage()); } finally { if (resp != null) { resp.close(); diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyGuardPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyGuardPersistenceTest.java index 47f099a73..741ae8998 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyGuardPersistenceTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyGuardPersistenceTest.java @@ -76,6 +76,7 @@ public class PolicyLegacyGuardPersistenceTest { @Before public void setupParameters() throws PfModelException { PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseDriver("org.h2.Driver"); parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setDatabaseUser("policy"); parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); @@ -134,6 +135,16 @@ public class PolicyLegacyGuardPersistenceTest { assertEquals(gip.getContent(), gotGopm.get(gip.getPolicyId()).getProperties().values().iterator().next()); + Map<String, LegacyGuardPolicyOutput> updatedGopm = databaseProvider.updateGuardPolicy(gip); + assertEquals(gip.getPolicyId(), updatedGopm.keySet().iterator().next()); + assertEquals(gip.getContent(), + updatedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next()); + + Map<String, LegacyGuardPolicyOutput> deletedGopm = databaseProvider.deleteGuardPolicy(gip.getPolicyId()); + assertEquals(gip.getPolicyId(), deletedGopm.keySet().iterator().next()); + assertEquals(gip.getContent(), + deletedGopm.get(gip.getPolicyId()).getProperties().values().iterator().next()); + String actualRetrievedJson = standardCoder.encode(gotGopm); // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java index 65e6a2f54..2e33a11a0 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java @@ -76,6 +76,7 @@ public class PolicyLegacyOperationalPersistenceTest { @Before public void setupParameters() throws PfModelException { PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseDriver("org.h2.Driver"); parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setDatabaseUser("policy"); parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); @@ -130,6 +131,12 @@ public class PolicyLegacyOperationalPersistenceTest { LegacyOperationalPolicy gotLop = databaseProvider.getOperationalPolicy(lop.getPolicyId()); assertEquals(gotLop, lop); + LegacyOperationalPolicy updatedLop = databaseProvider.updateOperationalPolicy(lop); + assertEquals(gotLop, updatedLop); + + LegacyOperationalPolicy deletedLop = databaseProvider.deleteOperationalPolicy(lop.getPolicyId()); + assertEquals(gotLop, deletedLop); + String actualRetrievedJson = standardCoder.encode(gotLop); // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java index 468d4d74b..668f63497 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java @@ -41,6 +41,7 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -84,6 +85,7 @@ public class PolicyPersistenceTest { @Before public void setupParameters() throws PfModelException { PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseDriver("org.h2.Driver"); parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setDatabaseUser("policy"); parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); @@ -142,13 +144,25 @@ public class PolicyPersistenceTest { assertNotNull(serviceTemplate); databaseProvider.createPolicies(serviceTemplate); + databaseProvider.updatePolicies(serviceTemplate); for (Map<String, ToscaPolicy> policyMap : serviceTemplate.getToscaTopologyTemplate().getPolicies()) { for (ToscaPolicy policy : policyMap.values()) { - ToscaServiceTemplate goToscaServiceTemplate = + ToscaServiceTemplate gotToscaServiceTemplate = databaseProvider.getPolicies(policy.getName(), policy.getVersion()); - assertEquals(goToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0) + assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0) + .get(policy.getName()).getType(), policy.getType()); + + gotToscaServiceTemplate = databaseProvider.getFilteredPolicies(ToscaPolicyFilter.builder().build()); + + assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0) + .get(policy.getName()).getType(), policy.getType()); + + gotToscaServiceTemplate = databaseProvider.getFilteredPolicies( + ToscaPolicyFilter.builder().name(policy.getName()).version(policy.getVersion()).build()); + + assertEquals(gotToscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0) .get(policy.getName()).getType(), policy.getType()); } } diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java index 8f05244b9..613c5a2c6 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java @@ -83,6 +83,7 @@ public class PolicyToscaPersistenceTest { @Before public void setupParameters() throws PfModelException { PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseDriver("org.h2.Driver"); parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setDatabaseUser("policy"); parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyTypePersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyTypePersistenceTest.java index 7f90a0b58..7b541e128 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyTypePersistenceTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyTypePersistenceTest.java @@ -41,6 +41,7 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,6 +84,7 @@ public class PolicyTypePersistenceTest { @Before public void setupParameters() throws PfModelException { PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseDriver("org.h2.Driver"); parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); parameters.setDatabaseUser("policy"); parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); @@ -105,7 +107,7 @@ public class PolicyTypePersistenceTest { } @Test - public void testPolicyPersistence() { + public void testPolicyTypePersistence() { try { for (String policyTypeResourceName : policyTypeResourceNames) { String policyTypeString = ResourceUtils.getResourceAsString(policyTypeResourceName); @@ -117,7 +119,7 @@ public class PolicyTypePersistenceTest { } } } catch (Exception exc) { - LOGGER.warn("error processing policies", exc); + LOGGER.warn("error processing policy types", exc); fail("test should not throw an exception"); } } @@ -142,11 +144,29 @@ public class PolicyTypePersistenceTest { ToscaPolicyType inPolicyType = serviceTemplate.getPolicyTypes().get(0).values().iterator().next(); databaseProvider.createPolicyTypes(serviceTemplate); + databaseProvider.updatePolicyTypes(serviceTemplate); List<ToscaPolicyType> policyTypeList = databaseProvider.getPolicyTypeList(inPolicyType.getName(), inPolicyType.getVersion()); + policyTypeList = databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder() + .name(inPolicyType.getName()).version(inPolicyType.getVersion()).build()); + + assertEquals(1, policyTypeList.size()); + assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName()); + + policyTypeList = databaseProvider + .getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().name(inPolicyType.getName()).build()); + assertEquals(1, policyTypeList.size()); assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName()); + + policyTypeList = databaseProvider.getFilteredPolicyTypeList(ToscaPolicyTypeFilter.builder().build()); + assertEquals(2, policyTypeList.size()); + assertEquals(inPolicyType.getName(), policyTypeList.get(0).getName()); + + for (ToscaPolicyType policyType: databaseProvider.getPolicyTypeList(null, null)) { + databaseProvider.deletePolicyType(policyType.getName(), policyType.getVersion()); + } } } diff --git a/models-provider/src/test/resources/META-INF/persistence.xml b/models-provider/src/test/resources/META-INF/persistence.xml index c7d6d1e4b..7b5bc14b9 100644 --- a/models-provider/src/test/resources/META-INF/persistence.xml +++ b/models-provider/src/test/resources/META-INF/persistence.xml @@ -33,34 +33,9 @@ <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdp</class> <properties> - <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" /> - <property name="javax.persistence.jdbc.user" value="policy" /> - <property name="javax.persistence.jdbc.password" value="P01icY" /> <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> <property name="eclipselink.logging.level" value="INFO" /> - </properties> - </persistence-unit> - - <persistence-unit name="ToscaConceptMariaDBTest" transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - - <class>org.onap.policy.models.dao.converters.CDataConditioner</class> - <class>org.onap.policy.models.dao.converters.Uuid2String</class> - <class>org.onap.policy.models.base.PfConceptKey</class> - <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class> - <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup</class> - <class>org.onap.policy.models.pdp.persistence.concepts.JpaPdp</class> - - <properties> - <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/policy" /> - <property name="javax.persistence.jdbc.user" value="policy" /> - <property name="javax.persistence.jdbc.password" value="P01icY" /> - <property name="javax.persistence.schema-generation.database.action" value="create" /> <!-- property name="eclipselink.logging.level" value="ALL" /> <property name="eclipselink.logging.level.jpa" value="ALL" /> @@ -72,10 +47,6 @@ <property name="eclipselink.logging.level.server" value="ALL" /> <property name="eclipselink.logging.level.query" value="ALL" /> <property name="eclipselink.logging.level.properties" value="ALL" /--> - - <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> - <property name="eclipselink.ddl-generation.output-mode" value="database" /> - <property name="eclipselink.logging.level" value="INFO" /> </properties> </persistence-unit> </persistence> diff --git a/models-sim/models-sim-dmaap/pom.xml b/models-sim/models-sim-dmaap/pom.xml new file mode 100644 index 000000000..9bfa6bec3 --- /dev/null +++ b/models-sim/models-sim-dmaap/pom.xml @@ -0,0 +1,103 @@ +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2019 Nordix Foundation. + ================================================================================ + 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========================================================= +--> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.models.sim</groupId> + <artifactId>policy-models-sim</artifactId> + <version>2.0.0-SNAPSHOT</version> + </parent> + + <artifactId>policy-models-sim-dmaap</artifactId> + + <name>${project.artifactId}</name> + <description>A module that implements a very simple DMaaP simulator.</description> + + <dependencies> + <dependency> + <groupId>commons-cli</groupId> + <artifactId>commons-cli</artifactId> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>common-parameters</artifactId> + <version>${policy.common.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>utils</artifactId> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>policy-endpoints</artifactId> + <version>${policy.common.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>gson</artifactId> + <version>${policy.common.version}</version> + </dependency> + </dependencies> + + <build> + <resources> + <!-- Output the version of the DMaaP simulator service --> + <resource> + <directory>src/main/resources</directory> + <filtering>true</filtering> + <includes> + <include>**/version.txt</include> + </includes> + </resource> + <resource> + <directory>src/main/resources</directory> + <filtering>false</filtering> + <excludes> + <exclude>**/version.txt</exclude> + </excludes> + </resource> + </resources> + + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-assembly-plugin</artifactId> + <executions> + <execution> + <id>generate-complete-tar</id> + <phase>package</phase> + <goals> + <goal>single</goal> + </goals> + <configuration> + <descriptors> + <descriptor>src/main/package/tarball/assembly.xml</descriptor> + </descriptors> + <finalName>${project.artifactId}-${project.version}</finalName> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + + </build> +</project> diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimConstants.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimConstants.java new file mode 100644 index 000000000..1682eb991 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimConstants.java @@ -0,0 +1,32 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.sim.dmaap; + +/** + * Names of various items contained in the Registry. + */ +public class DmaapSimConstants { + + // Registry keys + public static final String REG_DMAAP_SIM_ACTIVATOR = "object:activator/dmaap-sim"; + + private DmaapSimConstants() { + super(); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimException.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimException.java new file mode 100644 index 000000000..aaf8980f8 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimException.java @@ -0,0 +1,56 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap; + +/** + * This exception will be called if an error occurs in the DMaaP simulator. + */ +public class DmaapSimException extends Exception { + private static final long serialVersionUID = -8507246953751956974L; + + /** + * Instantiates a new exception with a message. + * + * @param message the message + */ + public DmaapSimException(final String message) { + super(message); + } + + /** + * Instantiates a new exception with a caused by exception. + * + * @param exp the exception that caused this exception to be thrown + */ + public DmaapSimException(final Exception exp) { + super(exp); + } + + /** + * Instantiates a new exception with a message and a caused by exception. + * + * @param message the message + * @param exp the exception that caused this exception to be thrown + */ + public DmaapSimException(final String message, final Exception exp) { + super(message, exp); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimRuntimeException.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimRuntimeException.java new file mode 100644 index 000000000..fe8b7e21b --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/DmaapSimRuntimeException.java @@ -0,0 +1,56 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap; + +/** + * This runtime exception will be called if a runtime error occurs when using the DMaaP simulator. + */ +public class DmaapSimRuntimeException extends RuntimeException { + private static final long serialVersionUID = -8507246953751956974L; + + /** + * Instantiates a new policy pap runtime exception with a message. + * + * @param message the message + */ + public DmaapSimRuntimeException(final String message) { + super(message); + } + + /** + * Instantiates a new runtime exception with a caused by exception. + * + * @param exp the exception that caused this exception to be thrown + */ + public DmaapSimRuntimeException(final Exception exp) { + super(exp); + } + + /** + * Instantiates a new runtime exception with a message and a caused by exception. + * + * @param message the message + * @param exp the exception that caused this exception to be thrown + */ + public DmaapSimRuntimeException(final String message, final Exception exp) { + super(message, exp); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/DmaapSimParameterGroup.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/DmaapSimParameterGroup.java new file mode 100644 index 000000000..caae287b8 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/DmaapSimParameterGroup.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.parameters; + +import lombok.Getter; + +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for the DMaaP simulator component. + */ +@NotNull +@NotBlank +@Getter +public class DmaapSimParameterGroup extends ParameterGroupImpl { + private RestServerParameters restServerParameters; + + /** + * Create the DMaaP simulator parameter group. + * + * @param name the parameter group name + */ + public DmaapSimParameterGroup(final String name) { + super(name); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/DmaapSimParameterHandler.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/DmaapSimParameterHandler.java new file mode 100644 index 000000000..8eb76ec00 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/DmaapSimParameterHandler.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.parameters; + +import java.io.File; + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.models.sim.dmaap.DmaapSimException; +import org.onap.policy.models.sim.dmaap.startstop.DmaapSimCommandLineArguments; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class handles reading, parsing and validating of DMaaP simulator parameters from JSON files. + */ +public class DmaapSimParameterHandler { + + private static final Logger LOGGER = LoggerFactory.getLogger(DmaapSimParameterHandler.class); + + private static final Coder CODER = new StandardCoder(); + + /** + * Read the parameters from the parameter file. + * + * @param arguments the arguments passed to DMaaP simulator + * @return the parameters read from the configuration file + * @throws DmaapSimException on parameter exceptions + */ + public DmaapSimParameterGroup getParameters(final DmaapSimCommandLineArguments arguments) throws DmaapSimException { + DmaapSimParameterGroup dmaapSimParameterGroup = null; + + // Read the parameters + try { + // Read the parameters from JSON + File file = new File(arguments.getFullConfigurationFilePath()); + dmaapSimParameterGroup = CODER.decode(file, DmaapSimParameterGroup.class); + } catch (final CoderException e) { + final String errorMessage = "error reading parameters from \"" + arguments.getConfigurationFilePath() + + "\"\n" + "(" + e.getClass().getSimpleName() + "):" + e.getMessage(); + LOGGER.error(errorMessage, e); + throw new DmaapSimException(errorMessage, e); + } + + // The JSON processing returns null if there is an empty file + if (dmaapSimParameterGroup == null) { + final String errorMessage = "no parameters found in \"" + arguments.getConfigurationFilePath() + "\""; + LOGGER.error(errorMessage); + throw new DmaapSimException(errorMessage); + } + + // validate the parameters + final GroupValidationResult validationResult = dmaapSimParameterGroup.validate(); + if (!validationResult.isValid()) { + String returnMessage = + "validation error(s) on parameters from \"" + arguments.getConfigurationFilePath() + "\"\n"; + returnMessage += validationResult.getResult(); + + LOGGER.error(returnMessage); + throw new DmaapSimException(returnMessage); + } + + return dmaapSimParameterGroup; + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/RestServerParameters.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/RestServerParameters.java new file mode 100644 index 000000000..c7269f66d --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/parameters/RestServerParameters.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.parameters; + +import lombok.Getter; +import org.onap.policy.common.parameters.ParameterGroupImpl; +import org.onap.policy.common.parameters.annotations.Min; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; + +/** + * Class to hold all parameters needed for DMaaP simulator rest server. + */ +@NotNull +@NotBlank +@Getter +public class RestServerParameters extends ParameterGroupImpl { + private String host; + + @Min(value = 1) + private int port; + + public RestServerParameters() { + super("RestServerParameters"); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProvider.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProvider.java new file mode 100644 index 000000000..9de29cdac --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/provider/DmaapSimProvider.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.provider; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.core.Response; + +import org.apache.commons.lang3.tuple.MutablePair; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.models.sim.dmaap.DmaapSimRuntimeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provider to simulate DMaaP. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class DmaapSimProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(DmaapSimProvider.class); + + // Recurring string constants + private static final String TOPIC_TAG = "Topic:"; + + // Time for a get to wait before checking of a message has come + private static final long DMAAP_SIM_WAIT_TIME = 50; + + // recurring constants + private static final String WITH_TIMEOUT = " with timeout "; + + // The map of topic messages + private static final Map<String, SortedMap<Integer, Object>> topicMessageMap = new LinkedHashMap<>(); + + // The map of topic messages + private static final Map<String, Map<String, MutablePair<Integer, String>>> consumerGroupsMap = + new LinkedHashMap<>(); + + /** + * Process a DMaaP message. + * + * @param topicName The topic name + * @param dmaapMessage the message to process + * @return a response to the message + */ + public Response processDmaapMessagePut(final String topicName, final Object dmaapMessage) { + LOGGER.debug(TOPIC_TAG + topicName + ", Received DMaaP message: " + dmaapMessage); + + synchronized (topicMessageMap) { + SortedMap<Integer, Object> messageMap = topicMessageMap.get(topicName); + if (messageMap == null) { + messageMap = new TreeMap<>(); + topicMessageMap.put(topicName, messageMap); + LOGGER.debug(TOPIC_TAG + topicName + ", created topic message map"); + } + + int nextKey = (messageMap.isEmpty() ? 0 : messageMap.lastKey() + 1); + + messageMap.put(nextKey, dmaapMessage); + LOGGER.debug(TOPIC_TAG + topicName + ", cached DMaaP message " + nextKey + ": " + dmaapMessage); + } + + return Response.status(Response.Status.OK).entity("{\n \"serverTimeMs\": 0,\n \"count\": 1\n}").build(); + } + + /** + * Wait for and return a DMaaP message. + * + * @param topicName The topic to wait on + * @param consumerGroup the consumer group that is waiting + * @param consumerId the consumer ID that is waiting + * @param timeout the length of time to wait for + * @return the DMaaP message or + */ + public Response processDmaapMessageGet(final String topicName, final String consumerGroup, final String consumerId, + final int timeout) { + + LOGGER.debug(TOPIC_TAG + topicName + ", Request for DMaaP message: " + consumerGroup + ":" + consumerId + + WITH_TIMEOUT + timeout); + + MutablePair<Integer, String> consumerGroupPair = null; + + synchronized (consumerGroupsMap) { + Map<String, MutablePair<Integer, String>> consumerGroupMap = consumerGroupsMap.get(topicName); + if (consumerGroupMap == null) { + consumerGroupMap = new LinkedHashMap<>(); + consumerGroupsMap.put(topicName, consumerGroupMap); + LOGGER.trace( + TOPIC_TAG + topicName + ", Created consumer map entry for consumer group " + consumerGroup); + } + + consumerGroupPair = consumerGroupMap.get(consumerGroup); + if (consumerGroupPair == null) { + consumerGroupPair = new MutablePair<>(-1, consumerId); + consumerGroupMap.put(consumerGroup, consumerGroupPair); + LOGGER.trace(TOPIC_TAG + topicName + ", Created consumer group entry for consumer group " + + consumerGroup + ":" + consumerId); + } + } + + long timeOfTimeout = System.currentTimeMillis() + timeout; + + do { + Object waitingMessages = getWaitingMessages(topicName, consumerGroupPair); + if (waitingMessages != null) { + LOGGER.debug(TOPIC_TAG + topicName + ", Request for DMaaP message: " + consumerGroup + ":" + consumerId + + WITH_TIMEOUT + timeout + ", returning messages " + waitingMessages); + return Response.status(Response.Status.OK).entity(waitingMessages).build(); + } + + try { + TimeUnit.MILLISECONDS.sleep(DMAAP_SIM_WAIT_TIME); + } catch (InterruptedException ie) { + String errorMessage = "Interrupt on wait on simulation of DMaaP topic " + topicName + " for request ID " + + consumerGroup + ":" + consumerId + WITH_TIMEOUT + timeout; + LOGGER.warn(errorMessage, ie); + Thread.currentThread().interrupt(); + throw new DmaapSimRuntimeException(errorMessage, ie); + } + } + while (timeOfTimeout > System.currentTimeMillis()); + + LOGGER.trace(TOPIC_TAG + topicName + ", timed out waiting for messages : " + consumerGroup + ":" + consumerId + + WITH_TIMEOUT + timeout); + return Response.status(Response.Status.REQUEST_TIMEOUT).build(); + } + + /** + * Return any messages on this topic with a message number greater than the supplied message number. + * + * @param topicName the topic name to check + * @param consumerGroupPair the pair with the information on the last message retrieved + * @return the messages or null if there are none + */ + private Object getWaitingMessages(final String topicName, final MutablePair<Integer, String> consumerGroupPair) { + String foundMessageList = "["; + + synchronized (topicMessageMap) { + SortedMap<Integer, Object> messageMap = topicMessageMap.get(topicName); + if (messageMap == null || messageMap.lastKey() <= consumerGroupPair.getLeft()) { + return null; + } + + boolean first = true; + for (Object dmaapMessage : messageMap.tailMap(consumerGroupPair.getLeft() + 1).values()) { + if (first) { + first = false; + } else { + foundMessageList += ","; + } + try { + foundMessageList += new StandardCoder().encode(dmaapMessage); + } catch (CoderException ce) { + String errorMessage = "Encoding error on message on DMaaP topic " + topicName; + LOGGER.warn(errorMessage, ce); + return null; + } + } + foundMessageList += ']'; + + LOGGER.debug(TOPIC_TAG + topicName + ", returning DMaaP messages from " + consumerGroupPair.getLeft() + + " to " + messageMap.lastKey()); + synchronized (consumerGroupsMap) { + consumerGroupPair.setLeft(messageMap.lastKey()); + } + } + + return (foundMessageList.length() < 3 ? null : foundMessageList); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/BaseRestControllerV1.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/BaseRestControllerV1.java new file mode 100644 index 000000000..bcde4b522 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/BaseRestControllerV1.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.rest; + +import io.swagger.annotations.Api; +import io.swagger.annotations.BasicAuthDefinition; +import io.swagger.annotations.Info; +import io.swagger.annotations.SecurityDefinition; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.annotations.Tag; +import java.net.HttpURLConnection; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.ResponseBuilder; + +/** + * Version v1 common superclass to provide DMaaP endpoints for the DMaaP simulator component. + */ +// @formatter:off +@Api(value = "DMaaP Simulator API") +@Produces("application/json") +@Consumes({"application/cambria", "application/json"}) +@SwaggerDefinition( + info = @Info(description = + "Simulator for DMaaP, follows API as described at " + + "\"https://onap.readthedocs.io/en/amsterdam/submodules/dmaap/messagerouter/messageservice.git/" + + "docs/message-router/message-router.html", version = "v1.0", + title = "Policy Administration"), + consumes = {MediaType.APPLICATION_JSON}, + produces = {MediaType.APPLICATION_JSON}, + schemes = {SwaggerDefinition.Scheme.HTTP, SwaggerDefinition.Scheme.HTTPS}, + tags = {@Tag(name = "dmaap-simulator", description = "DMaaP simulation")}, + securityDefinition = @SecurityDefinition(basicAuthDefinitions = {@BasicAuthDefinition(key = "basicAuth")})) +// @formatter:on +public class BaseRestControllerV1 { + public static final String EXTENSION_NAME = "interface info"; + + public static final String API_VERSION_NAME = "api-version"; + public static final String API_VERSION = "1.0.0"; + + public static final String LAST_MOD_NAME = "last-mod-release"; + public static final String LAST_MOD_RELEASE = "Dublin"; + + public static final String VERSION_MINOR_NAME = "X-MinorVersion"; + public static final String VERSION_MINOR_DESCRIPTION = + "Used to request or communicate a MINOR version back from the client" + + " to the server, and from the server back to the client"; + + public static final String VERSION_PATCH_NAME = "X-PatchVersion"; + public static final String VERSION_PATCH_DESCRIPTION = "Used only to communicate a PATCH version in a response for" + + " troubleshooting purposes only, and will not be provided by" + " the client on request"; + + public static final String VERSION_LATEST_NAME = "X-LatestVersion"; + public static final String VERSION_LATEST_DESCRIPTION = "Used only to communicate an API's latest version"; + + public static final String REQUEST_ID_NAME = "X-ONAP-RequestID"; + public static final String REQUEST_ID_HDR_DESCRIPTION = "Used to track REST transactions for logging purpose"; + public static final String REQUEST_ID_PARAM_DESCRIPTION = "RequestID for http transaction"; + + public static final String AUTHORIZATION_TYPE = "basicAuth"; + + public static final int AUTHENTICATION_ERROR_CODE = HttpURLConnection.HTTP_UNAUTHORIZED; + public static final int AUTHORIZATION_ERROR_CODE = HttpURLConnection.HTTP_FORBIDDEN; + public static final int SERVER_ERROR_CODE = HttpURLConnection.HTTP_INTERNAL_ERROR; + + public static final String AUTHENTICATION_ERROR_MESSAGE = "Authentication Error"; + public static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error"; + public static final String SERVER_ERROR_MESSAGE = "Internal Server Error"; + + /** + * Adds version headers to the response. + * + * @param respBuilder response builder + * @return the response builder, with version headers + */ + public ResponseBuilder addVersionControlHeaders(ResponseBuilder respBuilder) { + return respBuilder.header(VERSION_MINOR_NAME, "0").header(VERSION_PATCH_NAME, "0").header(VERSION_LATEST_NAME, + API_VERSION); + } + + /** + * Adds logging headers to the response. + * + * @param respBuilder response builder + * @return the response builder, with version logging + */ + public ResponseBuilder addLoggingHeaders(ResponseBuilder respBuilder, UUID requestId) { + if (requestId == null) { + // Generate a random uuid if client does not embed requestId in rest request + return respBuilder.header(REQUEST_ID_NAME, UUID.randomUUID()); + } + + return respBuilder.header(REQUEST_ID_NAME, requestId); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/CambriaMessageBodyHandler.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/CambriaMessageBodyHandler.java new file mode 100644 index 000000000..e269ac00b --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/CambriaMessageBodyHandler.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= ONAP + * ================================================================================ Copyright (C) 2019 AT&T Intellectual + * Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.sim.dmaap.rest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.Provider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provider that serializes and de-serializes JSON via gson. + */ +@Provider +@Consumes(CambriaMessageBodyHandler.MEDIA_TYPE_APPLICATION_CAMBRIA) +@Produces(CambriaMessageBodyHandler.MEDIA_TYPE_APPLICATION_CAMBRIA) +public class CambriaMessageBodyHandler implements MessageBodyReader<Object> { + // Media type for Cambria + public static final String MEDIA_TYPE_APPLICATION_CAMBRIA = "application/cambria"; + + public static final Logger logger = LoggerFactory.getLogger(CambriaMessageBodyHandler.class); + + @Override + public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return MEDIA_TYPE_APPLICATION_CAMBRIA.equals(mediaType.toString()); + } + + @Override + public String readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> httpHeaders, InputStream entityStream) + throws IOException { + + String cambriaString = ""; + try (BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(entityStream))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + cambriaString += line; + } + + return cambriaString.substring(cambriaString.indexOf('{'), cambriaString.length()); + } + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/DmaapSimRestControllerV1.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/DmaapSimRestControllerV1.java new file mode 100644 index 000000000..e3fdd4884 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/DmaapSimRestControllerV1.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.rest; + +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; + +import org.onap.policy.models.sim.dmaap.provider.DmaapSimProvider; + +/** + * Class to provide REST endpoints for DMaaP simulator component statistics. + */ +@Path("/events") +public class DmaapSimRestControllerV1 extends BaseRestControllerV1 { + + /** + * Get a DMaaP message. + * + * @param topicName topic to get message from + * @param consumerGroup consumer group that is getting the message + * @param consumerId consumer ID that is getting the message + * @param timeout timeout for the message + * @return the message + */ + @GET + @Path("{topicName}/{consumerGroup}/{consumerId}") + // @formatter:off + @ApiOperation( + value = "Get a DMaaP event on a topic", + notes = "Returns an event on a DMaaP topic", + response = Object.class, + authorizations = + @Authorization(value = AUTHORIZATION_TYPE) + ) + @ApiResponses( + value = { + @ApiResponse( + code = AUTHENTICATION_ERROR_CODE, + message = AUTHENTICATION_ERROR_MESSAGE), + @ApiResponse( + code = AUTHORIZATION_ERROR_CODE, + message = AUTHORIZATION_ERROR_MESSAGE), + @ApiResponse( + code = SERVER_ERROR_CODE, + message = SERVER_ERROR_MESSAGE) + } + ) + // @formatter:on + public Response getDmaaapMessage(@PathParam("topicName") final String topicName, + @PathParam("consumerGroup") final String consumerGroup, @PathParam("consumerId") final String consumerId, + @QueryParam("timeout") final int timeout) { + + return new DmaapSimProvider().processDmaapMessageGet(topicName, consumerGroup, consumerId, timeout); + } + + /** + * Post a DMaaP message. + * + * @param topicName topic to get message from415 + * @return the response to the post + */ + @POST + @Path("{topicName}") + // @formatter:off + @ApiOperation( + value = "Post a DMaaP event on a topic", + notes = "Returns an event on a DMaaP topic", + response = Response.class, + authorizations = + @Authorization(value = AUTHORIZATION_TYPE) + ) + @ApiResponses( + value = { + @ApiResponse( + code = AUTHENTICATION_ERROR_CODE, + message = AUTHENTICATION_ERROR_MESSAGE), + @ApiResponse( + code = AUTHORIZATION_ERROR_CODE, + message = AUTHORIZATION_ERROR_MESSAGE), + @ApiResponse( + code = SERVER_ERROR_CODE, + message = SERVER_ERROR_MESSAGE) + } + ) + // @formatter:on + public Response postDmaaapMessage(@PathParam("topicName") final String topicName, final Object dmaapMessage) { + + return new DmaapSimProvider().processDmaapMessagePut(topicName, dmaapMessage); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/DmaapSimRestServer.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/DmaapSimRestServer.java new file mode 100644 index 000000000..6853cc9dc --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/DmaapSimRestServer.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.rest; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.onap.policy.common.capabilities.Startable; +import org.onap.policy.common.endpoints.http.server.HttpServletServer; +import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties; +import org.onap.policy.models.sim.dmaap.parameters.RestServerParameters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class to manage life cycle of DMaaP Simulator rest server. + */ +public class DmaapSimRestServer implements Startable { + + private static final Logger LOGGER = LoggerFactory.getLogger(DmaapSimRestServer.class); + + private List<HttpServletServer> servers = new ArrayList<>(); + + private RestServerParameters restServerParameters; + + /** + * Constructor for instantiating DmaapSimRestServer. + * + * @param restServerParameters the rest server parameters + */ + public DmaapSimRestServer(final RestServerParameters restServerParameters) { + this.restServerParameters = restServerParameters; + } + + /** + * {@inheritDoc}. + */ + @Override + public boolean start() { + try { + servers = HttpServletServer.factory.build(getServerProperties()); + for (final HttpServletServer server : servers) { + server.start(); + } + } catch (final Exception exp) { + LOGGER.error("Failed to start DMaaP simulator http server", exp); + return false; + } + return true; + } + + /** + * Creates the server properties object using restServerParameters. + * + * @return the properties object + */ + private Properties getServerProperties() { + final Properties props = new Properties(); + props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, restServerParameters.getName()); + + final String svcpfx = + PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + restServerParameters.getName(); + + props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, restServerParameters.getHost()); + props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, + Integer.toString(restServerParameters.getPort())); + props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX, + String.join(",", DmaapSimRestControllerV1.class.getName())); + props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "false"); + props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SWAGGER_SUFFIX, "true"); + props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER, + CambriaMessageBodyHandler.class.getName() + "," + JsonMessageBodyHandler.class.getName()); + return props; + } + + /** + * {@inheritDoc}. + */ + @Override + public boolean stop() { + for (final HttpServletServer server : servers) { + try { + server.stop(); + } catch (final Exception exp) { + LOGGER.error("Failed to stop DMaaP simulator http server", exp); + } + } + return true; + } + + /** + * {@inheritDoc}. + */ + @Override + public void shutdown() { + stop(); + } + + /** + * {@inheritDoc}. + */ + @Override + public boolean isAlive() { + return !servers.isEmpty(); + } + + /** + * {@inheritDoc}. + */ + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("DmaapSimRestServer [servers="); + builder.append(servers); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/JsonMessageBodyHandler.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/JsonMessageBodyHandler.java new file mode 100644 index 000000000..a3eebda00 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/rest/JsonMessageBodyHandler.java @@ -0,0 +1,63 @@ +/* + * ============LICENSE_START======================================================= ONAP + * ================================================================================ Copyright (C) 2019 AT&T Intellectual + * Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.sim.dmaap.rest; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.Provider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Provider that serializes and de-serializes JSON via gson. + */ +@Provider +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public class JsonMessageBodyHandler implements MessageBodyReader<Object> { + public static final Logger logger = LoggerFactory.getLogger(JsonMessageBodyHandler.class); + + @Override + public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return MediaType.APPLICATION_JSON.equals(mediaType.toString()); + } + + @Override + public String readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap<String, String> httpHeaders, InputStream entityStream) + throws IOException { + + String jsonString = ""; + try (BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(entityStream))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + jsonString += line; + } + + return jsonString; + } + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/DmaapSimActivator.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/DmaapSimActivator.java new file mode 100644 index 000000000..899c0e081 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/DmaapSimActivator.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.startstop; + +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.services.ServiceManagerContainer; +import org.onap.policy.models.sim.dmaap.parameters.DmaapSimParameterGroup; +import org.onap.policy.models.sim.dmaap.rest.DmaapSimRestServer; + +/** + * This class activates the DMaaP simulator as a complete service. + */ +public class DmaapSimActivator extends ServiceManagerContainer { + /** + * The DMaaP simulator REST API server. + */ + private DmaapSimRestServer restServer; + + /** + * Instantiate the activator for the DMaaP simulator as a complete service. + * + * @param dmaapSimParameterGroup the parameters for the DMaaP simulator service + */ + public DmaapSimActivator(final DmaapSimParameterGroup dmaapSimParameterGroup) { + super("DMaaP Simulator"); + + // @formatter:off + addAction("DMaaP Simulator parameters", + () -> ParameterService.register(dmaapSimParameterGroup), + () -> ParameterService.deregister(dmaapSimParameterGroup.getName())); + + addAction("Create REST server", + () -> restServer = new DmaapSimRestServer(dmaapSimParameterGroup.getRestServerParameters()), + () -> restServer = null + ); + + addAction("REST server", + () -> restServer.start(), + () -> restServer.stop()); + // @formatter:on + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/DmaapSimCommandLineArguments.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/DmaapSimCommandLineArguments.java new file mode 100644 index 000000000..c0db8a7ed --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/DmaapSimCommandLineArguments.java @@ -0,0 +1,242 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.startstop; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URL; +import java.util.Arrays; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.sim.dmaap.DmaapSimException; +import org.onap.policy.models.sim.dmaap.DmaapSimRuntimeException; + + +/** + * This class reads and handles command line parameters for the DMaaP simulator service. + */ +public class DmaapSimCommandLineArguments { + private static final String FILE_MESSAGE_PREAMBLE = " file \""; + private static final int HELP_LINE_LENGTH = 120; + + private final Options options; + private String configurationFilePath = null; + + /** + * Construct the options for the CLI editor. + */ + public DmaapSimCommandLineArguments() { + //@formatter:off + options = new Options(); + options.addOption(Option.builder("h") + .longOpt("help") + .desc("outputs the usage of this command") + .required(false) + .type(Boolean.class) + .build()); + options.addOption(Option.builder("v") + .longOpt("version") + .desc("outputs the version of DMaaP simulator") + .required(false) + .type(Boolean.class) + .build()); + options.addOption(Option.builder("c") + .longOpt("config-file") + .desc("the full path to the configuration file to use, " + + "the configuration file must be a Json file containing the DMaaP simulator parameters") + .hasArg() + .argName("CONFIG_FILE") + .required(false) + .type(String.class) + .build()); + //@formatter:on + } + + /** + * Construct the options for the CLI editor and parse in the given arguments. + * + * @param args The command line arguments + */ + public DmaapSimCommandLineArguments(final String[] args) { + // Set up the options with the default constructor + this(); + + // Parse the arguments + try { + parse(args); + } catch (final DmaapSimException e) { + throw new DmaapSimRuntimeException("parse error on DMaaP simulator parameters", e); + } + } + + /** + * Parse the command line options. + * + * @param args The command line arguments + * @return a string with a message for help and version, or null if there is no message + * @throws DmaapSimException on command argument errors + */ + public String parse(final String[] args) throws DmaapSimException { + // Clear all our arguments + setConfigurationFilePath(null); + + CommandLine commandLine = null; + try { + commandLine = new DefaultParser().parse(options, args); + } catch (final ParseException e) { + throw new DmaapSimException("invalid command line arguments specified : " + e.getMessage()); + } + + // Arguments left over after Commons CLI does its stuff + final String[] remainingArgs = commandLine.getArgs(); + + if (remainingArgs.length > 0 && commandLine.hasOption('c') || remainingArgs.length > 0) { + throw new DmaapSimException("too many command line arguments specified : " + Arrays.toString(args)); + } + + if (remainingArgs.length == 1) { + configurationFilePath = remainingArgs[0]; + } + + if (commandLine.hasOption('h')) { + return help(Main.class.getCanonicalName()); + } + + if (commandLine.hasOption('v')) { + return version(); + } + + if (commandLine.hasOption('c')) { + setConfigurationFilePath(commandLine.getOptionValue('c')); + } + + return null; + } + + /** + * Validate the command line options. + * + * @throws DmaapSimException on command argument validation errors + */ + public void validate() throws DmaapSimException { + validateReadableFile("DMaaP simulator configuration", configurationFilePath); + } + + /** + * Print version information for DMaaP simulator. + * + * @return the version string + */ + public String version() { + return ResourceUtils.getResourceAsString("version.txt"); + } + + /** + * Print help information for DMaaP simulator. + * + * @param mainClassName the main class name + * @return the help string + */ + public String help(final String mainClassName) { + final HelpFormatter helpFormatter = new HelpFormatter(); + final StringWriter stringWriter = new StringWriter(); + final PrintWriter printWriter = new PrintWriter(stringWriter); + + helpFormatter.printHelp(printWriter, HELP_LINE_LENGTH, mainClassName + " [options...]", "options", options, 0, + 0, ""); + + return stringWriter.toString(); + } + + /** + * Gets the configuration file path. + * + * @return the configuration file path + */ + public String getConfigurationFilePath() { + return configurationFilePath; + } + + /** + * Gets the full expanded configuration file path. + * + * @return the configuration file path + */ + public String getFullConfigurationFilePath() { + return ResourceUtils.getFilePath4Resource(getConfigurationFilePath()); + } + + /** + * Sets the configuration file path. + * + * @param configurationFilePath the configuration file path + */ + public void setConfigurationFilePath(final String configurationFilePath) { + this.configurationFilePath = configurationFilePath; + + } + + /** + * Check set configuration file path. + * + * @return true, if check set configuration file path + */ + public boolean checkSetConfigurationFilePath() { + return configurationFilePath != null && configurationFilePath.length() > 0; + } + + /** + * Validate readable file. + * + * @param fileTag the file tag + * @param fileName the file name + * @throws DmaapSimException on the file name passed as a parameter + */ + private void validateReadableFile(final String fileTag, final String fileName) throws DmaapSimException { + if (fileName == null || fileName.length() == 0) { + throw new DmaapSimException(fileTag + " file was not specified as an argument"); + } + + // The file name refers to a resource on the local file system + final URL fileUrl = ResourceUtils.getUrl4Resource(fileName); + if (fileUrl == null) { + throw new DmaapSimException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + + final File theFile = new File(fileUrl.getPath()); + if (!theFile.exists()) { + throw new DmaapSimException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" does not exist"); + } + if (!theFile.isFile()) { + throw new DmaapSimException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is not a normal file"); + } + if (!theFile.canRead()) { + throw new DmaapSimException(fileTag + FILE_MESSAGE_PREAMBLE + fileName + "\" is ureadable"); + } + } +} diff --git a/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/Main.java b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/Main.java new file mode 100644 index 000000000..878d008a8 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/java/org/onap/policy/models/sim/dmaap/startstop/Main.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.sim.dmaap.startstop; + +import java.util.Arrays; + +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.sim.dmaap.DmaapSimConstants; +import org.onap.policy.models.sim.dmaap.DmaapSimException; +import org.onap.policy.models.sim.dmaap.parameters.DmaapSimParameterGroup; +import org.onap.policy.models.sim.dmaap.parameters.DmaapSimParameterHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class initiates the DMaaP simulator component. + */ +public class Main { + + private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); + + private DmaapSimActivator activator; + private DmaapSimParameterGroup parameterGroup; + + /** + * Instantiates the DMaap Simulator service. + * + * @param args the command line arguments + */ + public Main(final String[] args) { + final String argumentString = Arrays.toString(args); + LOGGER.info("Starting DMaaP simulator service with arguments - {}", argumentString); + + // Check the arguments + final DmaapSimCommandLineArguments arguments = new DmaapSimCommandLineArguments(); + try { + // The arguments return a string if there is a message to print and we should exit + final String argumentMessage = arguments.parse(args); + if (argumentMessage != null) { + LOGGER.info(argumentMessage); + return; + } + // Validate that the arguments are sane + arguments.validate(); + } catch (final DmaapSimException e) { + LOGGER.error("start of DMaaP simulator service failed", e); + return; + } + + // Read the parameters + try { + parameterGroup = new DmaapSimParameterHandler().getParameters(arguments); + } catch (final Exception e) { + LOGGER.error("start of DMaaP simulator service failed", e); + return; + } + + // Now, create the activator for the DMaaP Simulator service + activator = new DmaapSimActivator(parameterGroup); + Registry.register(DmaapSimConstants.REG_DMAAP_SIM_ACTIVATOR, activator); + + // Start the activator + try { + activator.start(); + } catch (final RuntimeException e) { + LOGGER.error("start of DMaaP simulator service failed, used parameters are {}", Arrays.toString(args), e); + Registry.unregister(DmaapSimConstants.REG_DMAAP_SIM_ACTIVATOR); + return; + } + + // Add a shutdown hook to shut everything down in an orderly manner + Runtime.getRuntime().addShutdownHook(new DmaapSimShutdownHookClass()); + LOGGER.info("Started DMaaP simulator service"); + } + + /** + * Get the parameters specified in JSON. + * + * @return the parameters + */ + public DmaapSimParameterGroup getParameters() { + return parameterGroup; + } + + /** + * Shut down Execution. + * + * @throws DmaapSimException on shutdown errors + */ + public void shutdown() throws DmaapSimException { + // clear the parameterGroup variable + parameterGroup = null; + + // clear the DMaaP simulator activator + if (activator != null) { + activator.stop(); + } + } + + /** + * The Class DmaapSimShutdownHookClass terminates the DMaaP simulator service when its run method is called. + */ + private class DmaapSimShutdownHookClass extends Thread { + /* + * (non-Javadoc) + * + * @see java.lang.Runnable#run() + */ + @Override + public void run() { + try { + // Shutdown the DMaaP simulator service and wait for everything to stop + activator.stop(); + } catch (final RuntimeException e) { + LOGGER.warn("error occured during shut down of the DMaaP simulator service", e); + } + } + } + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(final String[] args) { + new Main(args); + } +} diff --git a/models-sim/models-sim-dmaap/src/main/package/docker/Dockerfile b/models-sim/models-sim-dmaap/src/main/package/docker/Dockerfile new file mode 100644 index 000000000..fa114747d --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/package/docker/Dockerfile @@ -0,0 +1,73 @@ +# +# ============LICENSE_START======================================================= +# Copyright (C) 2019 Nordix Foundation. +# ================================================================================ +# 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========================================================= +# + +# +# Docker file to build an image that runs the DMaaP simulator on Java 8 in alpine +# + +FROM onap/policy-common-alpine:1.4.0 + +LABEL maintainer="Policy Team" + +ARG POLICY_LOGS=/var/log/onap/policy/dmaap-sim + +ENV POLICY_HOME=/opt/app/policy +ENV POLICY_LOGS=${POLICY_LOGS} + +RUN apk add --no-cache --update \ + bash \ + nss \ + procps \ + coreutils \ + findutils \ + grep \ + zip \ + unzip \ + curl \ + wget \ + openssh \ + iproute2 \ + iputils \ + vim \ + openjdk8 + +# Create DMaaP simulator user and group +# Add simulator-specific directories and set ownership as the simulator user +RUN mkdir -p ${POLICY_HOME}/dmaap-sim \ + && mkdir -p ${POLICY_HOME}/dmaap-sim/bin \ + && mkdir -p ${POLICY_LOGS} \ + && chown -R policy:policy ${POLICY_LOGS} \ + && mkdir /packages + +# Unpack the tarball +COPY policy-models-sim-dmaap-tarball.tar.gz /packages +RUN tar xvfz /packages/policy-models-sim-dmaap-tarball.tar.gz --directory ${POLICY_HOME}/dmaap-sim \ + && rm /packages/policy-models-sim-dmaap-tarball.tar.gz + +# Ensure everything has the correct permissions +# Copy examples to DMaaP simulator user area +COPY dmaap-sim.sh ${POLICY_HOME}/dmaap-sim/bin +RUN find /opt/app -type d -perm 755 \ + && find /opt/app -type f -perm 644 \ + && chmod a+x ${POLICY_HOME}/dmaap-sim/bin/* + +USER policy +ENV PATH ${POLICY_HOME}/dmaap-sim/bin:$PATH +ENTRYPOINT [ "bash", "dmaap-sim.sh" ] diff --git a/models-sim/models-sim-dmaap/src/main/package/docker/dmaap-sim.sh b/models-sim/models-sim-dmaap/src/main/package/docker/dmaap-sim.sh new file mode 100644 index 000000000..ec02d3fc1 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/package/docker/dmaap-sim.sh @@ -0,0 +1,55 @@ +#!/bin/bash +# +# ============LICENSE_START======================================================= +# Copyright (C) 2019 Nordix Foundation. +# ================================================================================ +# 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========================================================= +# + +if [ -z "$DMAAP_SIM_HOME" ] +then + DMAAP_SIM_HOME=/opt/app/policy/dmaap-sim +fi + +JAVA_HOME=/usr/lib/jvm/java-1.8-openjdk +KEYSTORE="${DMAAP_SIM_HOME}/etc/ssl/policy-keystore" +KEYSTORE_PASSWD="Pol1cy_0nap" +TRUSTSTORE="${DMAAP_SIM_HOME}/etc/ssl/policy-truststore" +TRUSTSTORE_PASSWD="Pol1cy_0nap" + +if [ "$#" -eq 1 ] +then + CONFIG_FILE=$1 +else + CONFIG_FILE=${CONFIG_FILE} +fi + +if [ -z "$CONFIG_FILE" ] +then + CONFIG_FILE="$DMAAP_SIM_HOME/etc/DefaultConfig.json" +fi + +echo "DMaaP simulation configuration file: $CONFIG_FILE" + +$JAVA_HOME/bin/java \ + -cp "$DMAAP_SIM_HOME/etc:$DMAAP_SIM_HOME/lib/*" \ + -Djavax.net.ssl.keyStore="$KEYSTORE" \ + -Djavax.net.ssl.keyStorePassword="$KEYSTORE_PASSWD" \ + -Djavax.net.ssl.trustStore="$TRUSTSTORE" \ + -Djavax.net.ssl.trustStorePassword="$TRUSTSTORE_PASSWD" \ + -Dlogback.configurationFile=$DMAAP_SIM_HOME/etc/logback.xml \ + org.onap.policy.models.sim.dmaap.startstop.Main \ + -c $CONFIG_FILE diff --git a/models-sim/models-sim-dmaap/src/main/package/docker/docker_build.sh b/models-sim/models-sim-dmaap/src/main/package/docker/docker_build.sh new file mode 100755 index 000000000..cd0148660 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/package/docker/docker_build.sh @@ -0,0 +1,66 @@ +#!/bin/bash +# +# ============LICENSE_START======================================================= +# Copyright (C) 2019 Nordix Foundation. +# ================================================================================ +# 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========================================================= +# + +# +# Script to build a Docker file for the DMaaP simulator. The docker image +# generated by this script should NOT be placed in the ONAP nexus, it is +# only for testing purposes. +# + +if [ -z "$DMAAP_SIM_HOME" ] +then + DMAAP_SIM_HOME=`pwd` +fi + +# Check for the dockerfile +if [ ! -f "$DMAAP_SIM_HOME/src/main/package/docker/Dockerfile" ] +then + echo docker file "$DMAAP_SIM_HOME/src/main/package/docker/Dockerfile" not found + exit 1 +fi + +# Check for the start script +if [ ! -f "$DMAAP_SIM_HOME/src/main/package/docker/dmaap-sim.sh" ] +then + echo start script "$DMAAP_SIM_HOME/src/main/package/docker/dmaap-sim.sh" not found + exit 1 +fi + +# Check for the tarball +tarball_count=`ls $DMAAP_SIM_HOME/target/policy-models-sim-dmaap-*-SNAPSHOT-tarball.tar.gz 2> /dev/null | wc | awk '{print $1}'` +if [ "$tarball_count" -ne "1" ] +then + echo one and only one tarball should exist in the target directory + exit 2 +fi + +# Set up the docker build +rm -fr $DMAAP_SIM_HOME/target/docker +mkdir $DMAAP_SIM_HOME/target/docker +cp $DMAAP_SIM_HOME/src/main/package/docker/Dockerfile $DMAAP_SIM_HOME/target/docker +cp $DMAAP_SIM_HOME/src/main/package/docker/dmaap-sim.sh $DMAAP_SIM_HOME/target/docker +cp $DMAAP_SIM_HOME/target/policy-models-sim-dmaap-*-SNAPSHOT-tarball.tar.gz $DMAAP_SIM_HOME/target/docker/policy-models-sim-dmaap-tarball.tar.gz + +# Run the docker build +cd $DMAAP_SIM_HOME/target +docker build -t dmaap/simulator docker + + diff --git a/models-sim/models-sim-dmaap/src/main/package/tarball/assembly.xml b/models-sim/models-sim-dmaap/src/main/package/tarball/assembly.xml new file mode 100644 index 000000000..e4671f81a --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/package/tarball/assembly.xml @@ -0,0 +1,67 @@ +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2019 Nordix Foundation. + ================================================================================ + 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========================================================= +--> + +<assembly> + <id>tarball</id> + <formats> + <format>tar.gz</format> + </formats> + <includeBaseDirectory>false</includeBaseDirectory> + <dependencySets> + <dependencySet> + <useProjectArtifact>true</useProjectArtifact> + <outputDirectory>/lib</outputDirectory> + <unpack>false</unpack> + <scope>runtime</scope> + <includes> + <include>*:jar</include> + </includes> + </dependencySet> + </dependencySets> + <fileSets> + <fileSet> + <directory>${project.basedir}/src/main/resources + </directory> + <includes> + <include>logback.xml</include> + </includes> + <outputDirectory>etc</outputDirectory> + <lineEnding>unix</lineEnding> + </fileSet> + <fileSet> + <directory>${project.basedir}/src/main/resources/etc + </directory> + <includes> + <include>DefaultConfig.json</include> + </includes> + <outputDirectory>etc</outputDirectory> + <lineEnding>unix</lineEnding> + </fileSet> + <fileSet> + <directory>${project.basedir}/src/main/resources/etc/ssl + </directory> + <includes> + <include>policy*</include> + </includes> + <outputDirectory>etc/ssl</outputDirectory> + <lineEnding>keep</lineEnding> + </fileSet> + </fileSets> +</assembly> diff --git a/models-sim/models-sim-dmaap/src/main/resources/etc/DefaultConfig.json b/models-sim/models-sim-dmaap/src/main/resources/etc/DefaultConfig.json new file mode 100644 index 000000000..dd2477a24 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/resources/etc/DefaultConfig.json @@ -0,0 +1,7 @@ +{ + "name": "DMaapSim", + "restServerParameters": { + "host": "0.0.0.0", + "port": 3904 + } +} diff --git a/models-sim/models-sim-dmaap/src/main/resources/etc/ssl/policy-keystore b/models-sim/models-sim-dmaap/src/main/resources/etc/ssl/policy-keystore Binary files differnew file mode 100644 index 000000000..7d2b1ecce --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/resources/etc/ssl/policy-keystore diff --git a/models-sim/models-sim-dmaap/src/main/resources/etc/ssl/policy-truststore b/models-sim/models-sim-dmaap/src/main/resources/etc/ssl/policy-truststore Binary files differnew file mode 100644 index 000000000..8834ac257 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/resources/etc/ssl/policy-truststore diff --git a/models-sim/models-sim-dmaap/src/main/resources/logback.xml b/models-sim/models-sim-dmaap/src/main/resources/logback.xml new file mode 100644 index 000000000..0e48d611f --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/resources/logback.xml @@ -0,0 +1,46 @@ +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2019 Nordix Foundation. + ================================================================================ + 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========================================================= +--> + +<configuration scan="true" scanPeriod="30 seconds" debug="false"> + + <contextName>DMaaPSim</contextName> + <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> + <property name="LOG_DIR" value="${java.io.tmpdir}/pf_logging/" /> + + <!-- USE FOR STD OUT ONLY --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern> + </encoder> + </appender> + + <root level="info"> + <appender-ref ref="STDOUT" /> + </root> + + <logger name="org.eclipse.jetty" level="info" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="org.onap.policy.models.sim.dmaap" level="debug" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + +</configuration> diff --git a/models-sim/models-sim-dmaap/src/main/resources/version.txt b/models-sim/models-sim-dmaap/src/main/resources/version.txt new file mode 100644 index 000000000..d629db844 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/main/resources/version.txt @@ -0,0 +1,4 @@ +ONAP DMaaP simulator Service +Version: ${project.version} +Built (UTC): ${maven.build.timestamp} +ONAP https://wiki.onap.org
\ No newline at end of file diff --git a/models-sim/models-sim-dmaap/src/test/resources/logback-test.xml b/models-sim/models-sim-dmaap/src/test/resources/logback-test.xml new file mode 100644 index 000000000..de7ef98da --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/logback-test.xml @@ -0,0 +1,54 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2019 Nordix Foundation. + ================================================================================ + 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========================================================= +--> + +<configuration> + + <contextName>DMaaPSim</contextName> + <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> + <property name="LOG_DIR" value="${java.io.tmpdir}/pf_logging/" /> + + <!-- USE FOR STD OUT ONLY --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern> + </encoder> + </appender> + + <root level="info"> + <appender-ref ref="STDOUT" /> + </root> + + <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${LOG_DIR}/apex.log</file> + <encoder> + <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full}</pattern> + </encoder> + </appender> + + <logger name="org.eclipse.jetty" level="info" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="org.onap.policy.models.sim.dmaap" level="trace" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> +</configuration> diff --git a/models-sim/models-sim-dmaap/src/test/resources/parameters/EmptyParameters.json b/models-sim/models-sim-dmaap/src/test/resources/parameters/EmptyParameters.json new file mode 100644 index 000000000..0637a088a --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/parameters/EmptyParameters.json @@ -0,0 +1 @@ +[]
\ No newline at end of file diff --git a/models-sim/models-sim-dmaap/src/test/resources/parameters/InvalidParameters.json b/models-sim/models-sim-dmaap/src/test/resources/parameters/InvalidParameters.json new file mode 100644 index 000000000..de2040cc8 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/parameters/InvalidParameters.json @@ -0,0 +1,3 @@ +{ + "name" : [] +}
\ No newline at end of file diff --git a/models-sim/models-sim-dmaap/src/test/resources/parameters/MinimumParameters.json b/models-sim/models-sim-dmaap/src/test/resources/parameters/MinimumParameters.json new file mode 100644 index 000000000..aeedf9d6e --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/parameters/MinimumParameters.json @@ -0,0 +1,7 @@ +{ + "name":"DMaapSim", + "restServerParameters":{ + "host":"0.0.0.0", + "port":6845 + } +} diff --git a/models-sim/models-sim-dmaap/src/test/resources/parameters/NoParameters.json b/models-sim/models-sim-dmaap/src/test/resources/parameters/NoParameters.json new file mode 100644 index 000000000..7a73a41bf --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/parameters/NoParameters.json @@ -0,0 +1,2 @@ +{ +}
\ No newline at end of file diff --git a/models-sim/models-sim-dmaap/src/test/resources/parameters/NormalParameters.json b/models-sim/models-sim-dmaap/src/test/resources/parameters/NormalParameters.json new file mode 100644 index 000000000..a2a036645 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/parameters/NormalParameters.json @@ -0,0 +1,7 @@ +{ + "name": "DMaapSim", + "restServerParameters": { + "host": "0.0.0.0", + "port": 6845 + } +} diff --git a/models-sim/models-sim-dmaap/src/test/resources/parameters/Parameters_InvalidName.json b/models-sim/models-sim-dmaap/src/test/resources/parameters/Parameters_InvalidName.json new file mode 100644 index 000000000..fba033e52 --- /dev/null +++ b/models-sim/models-sim-dmaap/src/test/resources/parameters/Parameters_InvalidName.json @@ -0,0 +1,9 @@ +{ + "name":" ", + "restServerParameters":{ + "host":"0.0.0.0", + "port":6969, + "userName":"dmaapsim", + "password":"zb!XztG34" + } +} diff --git a/models-sim/pom.xml b/models-sim/pom.xml new file mode 100644 index 000000000..c6165cc16 --- /dev/null +++ b/models-sim/pom.xml @@ -0,0 +1,36 @@ +<!-- + ============LICENSE_START======================================================= + Copyright (C) 2019 Nordix Foundation. + ================================================================================ + 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========================================================= +--> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.onap.policy.models</groupId> + <artifactId>policy-models</artifactId> + <version>2.0.0-SNAPSHOT</version> + </parent> + + <groupId>org.onap.policy.models.sim</groupId> + <artifactId>policy-models-sim</artifactId> + <packaging>pom</packaging> + <name>${project.artifactId}</name> + <modules> + <module>models-sim-dmaap</module> + </modules> +</project> diff --git a/models-tosca/pom.xml b/models-tosca/pom.xml index 5b857c13b..ea12057a2 100644 --- a/models-tosca/pom.xml +++ b/models-tosca/pom.xml @@ -58,21 +58,25 @@ </dependency> <dependency> - <groupId>com.h2database</groupId> - <artifactId>h2</artifactId> - <scope>test</scope> + <groupId>org.onap.policy.common</groupId> + <artifactId>common-parameters</artifactId> + <version>${policy.common.version}</version> </dependency> <dependency> - <groupId>org.mariadb.jdbc</groupId> - <artifactId>mariadb-java-client</artifactId> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> <scope>test</scope> </dependency> - <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-jersey2-jaxrs</artifactId> + <exclusions> + <exclusion> + <groupId>com.fasterxml.jackson.core</groupId> + <artifactId>jackson-databind</artifactId> + </exclusion> + </exclusions> </dependency> - </dependencies> </project> diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicy.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicy.java index 284e39c9b..27d4eb2e7 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicy.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicy.java @@ -23,6 +23,8 @@ package org.onap.policy.models.tosca.authorative.concepts; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModelProperty; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; @@ -44,6 +46,8 @@ import lombok.ToString; public class ToscaPolicy extends ToscaEntity implements Comparable<ToscaPolicy> { private String type; + @ApiModelProperty(name = "type_version") + @SerializedName("type_version") private String typeVersion; private Map<String, Object> properties; diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilter.java index bb0026e9a..012f7de34 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilter.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilter.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. @@ -39,16 +40,19 @@ import org.onap.policy.models.base.PfObjectFilter; public class ToscaPolicyFilter implements PfObjectFilter<ToscaPolicy> { public static final String LATEST_VERSION = "LATEST"; - // Regular expression + // Exact expression private String name; - // Regular Expression, set to LATEST_VERRSION to get the latest version + // Exact match, set to LATEST_VERSION to get the latest version private String version; - // Regular expression + // version prefix + private String versionPrefix; + + // Exact expression private String type; - // Regular Expression, set to LATEST_VERRSION to get the latest version + // Exact Expression, set to LATEST_VERSION to get the latest version private String typeVersion; @Override @@ -56,11 +60,11 @@ public class ToscaPolicyFilter implements PfObjectFilter<ToscaPolicy> { // @formatter:off List<ToscaPolicy> returnList = originalList.stream() - .filter(p -> filterString(p.getName(), name)) - .filter(p -> LATEST_VERSION.equals(version) - || filterString(p.getVersion(), version)) - .filter(p -> filterString(p.getType(), type)) - .filter(p -> filterString(p.getTypeVersion(), typeVersion)) + .filter(filterStringPred(name, ToscaPolicy::getName)) + .filter(filterStringPred((LATEST_VERSION.equals(version) ? null : version), ToscaPolicy::getVersion)) + .filter(filterPrefixPred(versionPrefix, ToscaPolicy::getVersion)) + .filter(filterStringPred(type, ToscaPolicy::getType)) + .filter(filterStringPred(typeVersion, ToscaPolicy::getTypeVersion)) .collect(Collectors.toList()); // @formatter:off diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifier.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifier.java index e55c6bd4d..f98a238ff 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifier.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifier.java @@ -23,13 +23,16 @@ package org.onap.policy.models.tosca.authorative.concepts; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import org.apache.commons.lang3.ObjectUtils; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ValidationResult; /** * Identifies a policy. Both the name and version must be non-null. */ @Data @NoArgsConstructor -public class ToscaPolicyIdentifier { +public class ToscaPolicyIdentifier implements Comparable<ToscaPolicyIdentifier> { @NonNull private String name; @@ -47,4 +50,37 @@ public class ToscaPolicyIdentifier { this.name = source.name; this.version = source.version; } + + /** + * Validates that appropriate fields are populated for an incoming call to the PAP + * REST API. + * + * @return the validation result + */ + public ValidationResult validatePapRest() { + BeanValidationResult result = new BeanValidationResult("group", this); + + result.validateNotNull("name", name); + result.validateNotNull("version", version); + + return result; + } + + @Override + public int compareTo(ToscaPolicyIdentifier other) { + if (this == other) { + return 0; + } + + if (other == null) { + return 1; + } + + int result = ObjectUtils.compare(getName(), other.getName()); + if (result != 0) { + return result; + } + + return ObjectUtils.compare(getVersion(), other.getVersion()); + } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersion.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersion.java index 9350d1738..a6aec0858 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersion.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersion.java @@ -20,20 +20,25 @@ package org.onap.policy.models.tosca.authorative.concepts; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.google.gson.annotations.SerializedName; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import org.apache.commons.lang3.ObjectUtils; /** * Policy identifier with an optional version; only the "name" is required. */ @Data @NoArgsConstructor -public class ToscaPolicyIdentifierOptVersion { +public class ToscaPolicyIdentifierOptVersion implements Comparable<ToscaPolicyIdentifierOptVersion> { @NonNull + @SerializedName("policy-id") private String name; + @SerializedName("policy-version") private String version; @@ -47,12 +52,36 @@ public class ToscaPolicyIdentifierOptVersion { this.version = source.version; } + public ToscaPolicyIdentifierOptVersion(ToscaPolicyIdentifier source) { + this.name = source.getName(); + this.version = source.getVersion(); + } + /** * Determines if the version is null/missing. * * @return {@code true} if the version is null/missing, {@code false} */ + @JsonIgnore public boolean isNullVersion() { return (version == null); } + + @Override + public int compareTo(ToscaPolicyIdentifierOptVersion other) { + if (this == other) { + return 0; + } + + if (other == null) { + return 1; + } + + int result = ObjectUtils.compare(getName(), other.getName()); + if (result != 0) { + return result; + } + + return ObjectUtils.compare(getVersion(), other.getVersion()); + } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifier.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifier.java index a10c3eb9c..4cd1764de 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifier.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifier.java @@ -23,13 +23,16 @@ package org.onap.policy.models.tosca.authorative.concepts; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; +import org.apache.commons.lang3.ObjectUtils; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ValidationResult; /** * Identifies a policy type. Both the name and version must be non-null. */ @Data @NoArgsConstructor -public class ToscaPolicyTypeIdentifier { +public class ToscaPolicyTypeIdentifier implements Comparable<ToscaPolicyTypeIdentifier> { @NonNull private String name; @@ -47,4 +50,37 @@ public class ToscaPolicyTypeIdentifier { this.name = source.name; this.version = source.version; } + + /** + * Validates that appropriate fields are populated for an incoming call to the PAP + * REST API. + * + * @return the validation result + */ + public ValidationResult validatePapRest() { + BeanValidationResult result = new BeanValidationResult("group", this); + + result.validateNotNull("name", name); + result.validateNotNull("version", version); + + return result; + } + + @Override + public int compareTo(ToscaPolicyTypeIdentifier other) { + if (this == other) { + return 0; + } + + if (other == null) { + return 1; + } + + int result = ObjectUtils.compare(getName(), other.getName()); + if (result != 0) { + return result; + } + + return ObjectUtils.compare(getVersion(), other.getVersion()); + } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProvider.java index 4bf014644..5f8729e08 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProvider.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProvider.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. @@ -200,7 +201,10 @@ public class AuthorativeToscaProvider { public ToscaServiceTemplate getFilteredPolicies(@NonNull final PfDao dao, @NonNull final ToscaPolicyFilter filter) throws PfModelException { - ToscaServiceTemplate serviceTemplate = new SimpleToscaProvider().getPolicies(dao, null, null).toAuthorative(); + String version = ToscaPolicyFilter.LATEST_VERSION.equals(filter.getVersion()) ? null : filter.getVersion(); + + ToscaServiceTemplate serviceTemplate = + new SimpleToscaProvider().getPolicies(dao, filter.getName(), version).toAuthorative(); List<ToscaPolicy> filteredPolicies = asConceptList(serviceTemplate.getToscaTopologyTemplate().getPolicies()); filteredPolicies = filter.filter(filteredPolicies); @@ -221,7 +225,8 @@ public class AuthorativeToscaProvider { public List<ToscaPolicy> getFilteredPolicyList(@NonNull final PfDao dao, @NonNull final ToscaPolicyFilter filter) throws PfModelException { - return filter.filter(getPolicyList(dao, null, null)); + String version = ToscaPolicyFilter.LATEST_VERSION.equals(filter.getVersion()) ? null : filter.getVersion(); + return filter.filter(getPolicyList(dao, filter.getName(), version)); } /** @@ -276,10 +281,6 @@ public class AuthorativeToscaProvider { * @return the plain list */ private <T> List<T> asConceptList(final List<Map<String, T>> listOfMaps) { - if (listOfMaps == null) { - return Collections.emptyList(); - } - List<T> returnList = new ArrayList<>(); for (Map<String, T> conceptMap : listOfMaps) { for (T concept : conceptMap.values()) { diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapper.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapper.java index cc37338e4..0d04cb9d1 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapper.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapper.java @@ -22,6 +22,7 @@ package org.onap.policy.models.tosca.legacy.mapping; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Map.Entry; import javax.ws.rs.core.Response; @@ -46,6 +47,11 @@ import org.slf4j.LoggerFactory; */ public class LegacyGuardPolicyMapper implements JpaToscaServiceTemplateMapper<LegacyGuardPolicyInput, Map<String, LegacyGuardPolicyOutput>> { + + // Tag for metadata fields + private static final String POLICY_ID = "policy-id"; + private static final String POLICY_VERSION = "policy-version"; + private static final Logger LOGGER = LoggerFactory.getLogger(LegacyGuardPolicyMapper.class); private static final Map<String, PfConceptKey> GUARD_POLICY_TYPE_MAP = new LinkedHashMap<>(); @@ -55,8 +61,6 @@ public class LegacyGuardPolicyMapper new PfConceptKey("onap.policies.controlloop.guard.FrequencyLimiter:1.0.0")); GUARD_POLICY_TYPE_MAP.put("guard.minmax.scaleout", new PfConceptKey("onap.policies.controlloop.guard.MinMax:1.0.0")); - GUARD_POLICY_TYPE_MAP.put("guard.minmax.scaleout", - new PfConceptKey("onap.policies.controlloop.guard.MinMax:1.0.0")); GUARD_POLICY_TYPE_MAP.put("guard.blacklist", new PfConceptKey("onap.policies.controlloop.guard.Blacklist:1.0.0")); } @@ -84,8 +88,13 @@ public class LegacyGuardPolicyMapper toscaPolicy.setType(guardPolicyType); toscaPolicy.setProperties(legacyGuardPolicyInput.getContent().getAsPropertyMap()); + final Map<String, String> metadata = new LinkedHashMap<>(); + metadata.put(POLICY_ID, toscaPolicy.getKey().getName()); + metadata.put(POLICY_VERSION, Integer.toString(toscaPolicy.getKey().getMajorVersion())); + toscaPolicy.setMetadata(metadata); + final JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate(); - serviceTemplate.setToscaDefinitionsVersion("tosca_simimport java.util.HashMap;\n" + "ple_yaml_1_0"); + serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_0"); serviceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate()); @@ -109,9 +118,20 @@ public class LegacyGuardPolicyMapper legacyGuardPolicyOutput.setType(toscaPolicy.getType().getName()); legacyGuardPolicyOutput.setVersion(toscaPolicy.getType().getVersion()); + if (toscaPolicy.getMetadata() == null) { + String errorMessage = "no metadata defined on TOSCA policy"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + final Map<String, Object> metadata = new LinkedHashMap<>(); - metadata.put("policy-id", toscaPolicy.getKey().getName()); - metadata.put("policy-version", toscaPolicy.getKey().getMajorVersion()); + for (Entry<String, String> metadataEntry : toscaPolicy.getMetadata().entrySet()) { + if (POLICY_VERSION.equals(metadataEntry.getKey())) { + metadata.put(POLICY_VERSION, Integer.parseInt(metadataEntry.getValue())); + } else { + metadata.put(metadataEntry.getKey(), metadataEntry.getValue()); + } + } legacyGuardPolicyOutput.setMetadata(metadata); if (toscaPolicy.getProperties() == null) { @@ -139,12 +159,6 @@ public class LegacyGuardPolicyMapper propertiesMap.put("content", content); legacyGuardPolicyOutput.setProperties(propertiesMap); - if (toscaPolicy.getProperties() == null) { - String errorMessage = "property \"Content\" not defined on TOSCA policy"; - LOGGER.warn(errorMessage); - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); - } - legacyGuardPolicyOutputMap.put(toscaPolicy.getKey().getName(), legacyGuardPolicyOutput); } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java index b6c5d3bba..7caba98d8 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java @@ -106,8 +106,8 @@ public class LegacyOperationalPolicyMapper } final String content = toscaPolicy.getProperties().get(CONTENT_PROPERTY); - if (toscaPolicy.getProperties() == null) { - String errorMessage = "property \"Content\" not defined on TOSCA policy"; + if (content == null) { + String errorMessage = "property \"content\" not defined on TOSCA policy"; LOGGER.warn(errorMessage); throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraint.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraint.java index fad227c34..6369f7996 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraint.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraint.java @@ -53,9 +53,7 @@ public abstract class JpaToscaConstraint } @Override - public int compareTo(JpaToscaConstraint otherConstraint) { - return 0; - } + public abstract int compareTo(JpaToscaConstraint otherConstraint); /** * Create instances of constraints of various types. diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogical.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogical.java index 9841cbe82..632f84add 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogical.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogical.java @@ -73,30 +73,33 @@ public class JpaToscaConstraintLogical extends JpaToscaConstraint { public ToscaConstraint toAuthorative() { ToscaConstraint toscaConstraint = new ToscaConstraint(); + if (operation == null) { + return null; + } + switch (operation) { - case EQ: { + case EQ: toscaConstraint.setEqual(compareTo); break; - } - case GT: { + + case GT: toscaConstraint.setGreaterThan(compareTo); break; - } - case GE: { + + case GE: toscaConstraint.setGreaterOrEqual(compareTo); break; - } - case LT: { + + case LT: toscaConstraint.setLessThan(compareTo); break; - } - case LE: { + + case LE: toscaConstraint.setLessOrEqual(compareTo); break; - } - default: { + + default: // Can't happen - } } return toscaConstraint; diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModel.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModel.java index a322c167f..204ef5b9d 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModel.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaModel.java @@ -24,6 +24,7 @@ import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; @@ -57,7 +58,7 @@ import org.onap.policy.models.base.PfValidationResult; public class JpaToscaModel extends PfModel { private static final long serialVersionUID = 8800599637708309945L; - @OneToOne(cascade = CascadeType.ALL) + @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) private JpaToscaServiceTemplates serviceTemplates; /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java index 671b5ccac..3e049ea17 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicy.java @@ -38,17 +38,21 @@ import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Lob; import javax.persistence.Table; +import javax.ws.rs.core.Response; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NonNull; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.validation.Assertions; import org.onap.policy.common.utils.validation.ParameterValidationUtils; import org.onap.policy.models.base.PfAuthorative; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfKey; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.base.PfUtils; import org.onap.policy.models.base.PfValidationMessage; import org.onap.policy.models.base.PfValidationResult; @@ -69,6 +73,10 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements PfAuthorative<ToscaPolicy> { private static final long serialVersionUID = 3265174757061982805L; + // Tags for metadata + private static final String METADATA_POLICY_ID_TAG = "policy-id"; + private static final String METADATA_POLICY_VERSION_TAG = "policy-version"; + // @formatter:off @Column @AttributeOverrides({ @@ -129,6 +137,8 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P * @param authorativeConcept the authorative concept to copy from */ public JpaToscaPolicy(final ToscaPolicy authorativeConcept) { + super(new PfConceptKey()); + type = new PfConceptKey(); this.fromAuthorative(authorativeConcept); } @@ -142,8 +152,7 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P if (!PfKey.NULL_KEY_VERSION.equals(type.getVersion())) { toscaPolicy.setTypeVersion(type.getVersion()); - } - else { + } else { toscaPolicy.setTypeVersion(null); } @@ -151,7 +160,18 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P Map<String, Object> propertyMap = new LinkedHashMap<>(); for (Entry<String, String> entry : properties.entrySet()) { - propertyMap.put(entry.getKey(), entry.getValue()); + try { + // TODO: This is a HACK, we need to validate the properties against their + // TODO: their data type in their policy type definition in TOSCA, which means reading + // TODO: the policy type from the database and parsing the property value object correctly + // TODO: Here we are simply reading a JSON string from the database and deserializing the + // TODO: property value from JSON + propertyMap.put(entry.getKey(), new StandardCoder().decode(entry.getValue(), Object.class)); + } catch (CoderException ce) { + String errorMessage = "error decoding property JSON value read from database: key=" + entry.getKey() + + ", value=" + entry.getValue(); + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce); + } } toscaPolicy.setProperties(propertyMap); @@ -179,9 +199,24 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P // TODO: the policy type from the database and parsing the property value object correctly // TODO: Here we are simply serializing the property value into a string and storing it // TODO: unvalidated into the database - properties.put(propertyEntry.getKey(), propertyEntry.getValue().toString()); + try { + properties.put(propertyEntry.getKey(), new StandardCoder().encode(propertyEntry.getValue())); + } catch (CoderException ce) { + String errorMessage = "error encoding property JSON value for database: key=" + + propertyEntry.getKey() + ", value=" + propertyEntry.getValue(); + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce); + } } } + + // Add the property metadata if it doesn't exist already + if (toscaPolicy.getMetadata() == null) { + setMetadata(new LinkedHashMap<>()); + } + + // Add the policy name and version fields to the metadata + getMetadata().put(METADATA_POLICY_ID_TAG, getKey().getName()); + getMetadata().put(METADATA_POLICY_VERSION_TAG, Integer.toString(getKey().getMajorVersion())); } @Override @@ -215,7 +250,7 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P PfValidationResult result = super.validate(resultIn); if (type == null || type.isNullKey()) { - result.addValidationMessage(new PfValidationMessage(type, this.getClass(), ValidationResult.INVALID, + result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID, "type is null or a null key")); } else { result = type.validate(result); @@ -238,7 +273,7 @@ public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements P * @param result The result of validations up to now * @return the validation result */ - private PfValidationResult validateProperties(@NonNull final PfValidationResult resultIn) { + private PfValidationResult validateProperties(final PfValidationResult resultIn) { PfValidationResult result = resultIn; for (Entry<String, String> propertyEntry : properties.entrySet()) { diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplate.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplate.java index fda0c8014..f9e388b04 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplate.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplate.java @@ -27,6 +27,7 @@ import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; @@ -63,6 +64,7 @@ public class JpaToscaServiceTemplate extends JpaToscaEntityType<ToscaServiceTemp implements PfAuthorative<ToscaServiceTemplate> { private static final long serialVersionUID = 8084846046148349401L; + public static final String DEFAULT_TOSCA_DEFINTIONS_VERISON = "tosca_simple_yaml_1_0_0"; public static final String DEFAULT_NAME = "ToscaServiceTemplateSimple"; public static final String DEFAULT_VERSION = "1.0.0"; @@ -70,14 +72,15 @@ public class JpaToscaServiceTemplate extends JpaToscaEntityType<ToscaServiceTemp @SerializedName("tosca_definitions_version") private String toscaDefinitionsVersion; - @OneToOne(cascade = CascadeType.ALL) + @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) @SerializedName("data_types") private JpaToscaDataTypes dataTypes; - @OneToOne(cascade = CascadeType.ALL) + @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) @SerializedName("policy_types") private JpaToscaPolicyTypes policyTypes; + @Column @SerializedName("topology_template") private JpaToscaTopologyTemplate topologyTemplate; @@ -95,7 +98,7 @@ public class JpaToscaServiceTemplate extends JpaToscaEntityType<ToscaServiceTemp * @param key the key */ public JpaToscaServiceTemplate(@NonNull final PfConceptKey key) { - this(key, ""); + this(key, DEFAULT_TOSCA_DEFINTIONS_VERISON); } /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplate.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplate.java index 3476258cf..b1c3f209d 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplate.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplate.java @@ -26,6 +26,7 @@ import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; +import javax.persistence.FetchType; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; @@ -68,7 +69,7 @@ public class JpaToscaTopologyTemplate extends PfConcept implements PfAuthorative @Column(name = "description") private String description; - @OneToOne(cascade = CascadeType.ALL) + @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) private JpaToscaPolicies policies; /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java index a207c4267..ef8ac05ec 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java @@ -24,14 +24,11 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import javax.ws.rs.core.Response; - import lombok.NonNull; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.dao.PfDao; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; @@ -40,8 +37,6 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate; import org.onap.policy.models.tosca.utils.ToscaUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * This class provides the provision of information on TOSCA concepts in the database to callers. @@ -49,8 +44,6 @@ import org.slf4j.LoggerFactory; * @author Liam Fallon (liam.fallon@est.tech) */ public class SimpleToscaProvider { - private static final Logger LOGGER = LoggerFactory.getLogger(SimpleToscaProvider.class); - /** * Get policy types. * @@ -69,14 +62,9 @@ public class SimpleToscaProvider { // Add the policy type to the TOSCA service template List<JpaToscaPolicyType> jpaPolicyTypeList = dao.getFiltered(JpaToscaPolicyType.class, name, version); - if (jpaPolicyTypeList != null) { - serviceTemplate.getPolicyTypes().getConceptMap().putAll(asConceptMap(jpaPolicyTypeList)); - return serviceTemplate; - } else { - String errorMessage = "policy type not found: " + name + ":" + version; - LOGGER.warn(errorMessage); - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); - } + serviceTemplate.getPolicyTypes().getConceptMap().putAll(asConceptMap(jpaPolicyTypeList)); + + return serviceTemplate; } /** @@ -178,14 +166,8 @@ public class SimpleToscaProvider { // Add the policy type to the TOSCA service template List<JpaToscaPolicy> jpaPolicyList = dao.getFiltered(JpaToscaPolicy.class, name, version); - if (jpaPolicyList != null) { - serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().putAll(asConceptMap(jpaPolicyList)); - return serviceTemplate; - } else { - String errorMessage = "policy not found: " + name + ":" + version; - LOGGER.warn(errorMessage); - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); - } + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().putAll(asConceptMap(jpaPolicyList)); + return serviceTemplate; } /** diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaIdentifierTestBase.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaIdentifierTestBase.java index 5c935394b..d7bca2808 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaIdentifierTestBase.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaIdentifierTestBase.java @@ -20,6 +20,9 @@ package org.onap.policy.models.tosca.authorative.concepts; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.onap.policy.common.utils.coder.Coder; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; @@ -29,19 +32,49 @@ import org.onap.policy.common.utils.coder.StandardCoder; * * @param <T> type of key being tested */ -public class ToscaIdentifierTestBase<T> { +public class ToscaIdentifierTestBase<T extends Comparable<T>> { + public static final String NAME = "my-name"; + public static final String VERSION = "1.2.3"; private static final Coder coder = new StandardCoder(); private final Class<T> clazz; + private final String nameField; + private final String versionField; /** * Constructs the object. + * * @param clazz the type of class being tested + * @param nameField name of the field containing the "name" + * @param versionField name of the field containing the "version" */ - public ToscaIdentifierTestBase(Class<T> clazz) { + public ToscaIdentifierTestBase(Class<T> clazz, String nameField, String versionField) { this.clazz = clazz; + this.nameField = nameField; + this.versionField = versionField; + } + + /** + * Tests the compareTo() method. + * + * @throws Exception if an error occurs + */ + public void testCompareTo() throws Exception { + T ident = makeIdent(NAME, VERSION); + assertEquals(0, ident.compareTo(ident)); + + assertTrue(ident.compareTo(null) > 0); + + assertTrue(ident.compareTo(makeIdent(NAME, VERSION)) == 0); + assertTrue(ident.compareTo(makeIdent(NAME, null)) > 0); + assertTrue(ident.compareTo(makeIdent(null, VERSION)) > 0); + assertTrue(ident.compareTo(makeIdent(NAME, VERSION + "a")) < 0); + assertTrue(ident.compareTo(makeIdent(NAME + "a", VERSION)) < 0); + + // name takes precedence over version + assertTrue(makeIdent(NAME, VERSION + "a").compareTo(makeIdent(NAME + "a", VERSION)) < 0); } /** @@ -57,7 +90,9 @@ public class ToscaIdentifierTestBase<T> { bldr.append("{"); if (name != null) { - bldr.append("'name':'"); + bldr.append("'"); + bldr.append(nameField); + bldr.append("':'"); bldr.append(name); bldr.append("'"); } @@ -67,7 +102,9 @@ public class ToscaIdentifierTestBase<T> { bldr.append(','); } - bldr.append("'version':'"); + bldr.append("'"); + bldr.append(versionField); + bldr.append("':'"); bldr.append(version); bldr.append("'"); } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java index 4653296b7..f7c9c7ef0 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyFilterTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019 AT&T Intellectual Property. 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. @@ -95,6 +96,7 @@ public class ToscaPolicyFilterTest { if (policy.getName() == null) { policy.setName(policyEntry.getKey()); } + if (policy.getVersion() == null) { policy.setVersion(PfKey.NULL_KEY_VERSION); } @@ -186,6 +188,22 @@ public class ToscaPolicyFilterTest { } @Test + public void testFilterVersionPrefix() { + // null pattern + ToscaPolicyFilter filter = ToscaPolicyFilter.builder().versionPrefix(null).build(); + List<ToscaPolicy> filteredList = filter.filter(policyList); + assertEquals(17, filteredList.size()); + + filter = ToscaPolicyFilter.builder().versionPrefix("1.").build(); + filteredList = filter.filter(policyList); + assertEquals(17, filteredList.size()); + + filter = ToscaPolicyFilter.builder().versionPrefix("100.").build(); + filteredList = filter.filter(policyList); + assertEquals(0, filteredList.size()); + } + + @Test public void testFilterTypeVersion() { ToscaPolicyFilter filter = ToscaPolicyFilter.builder().type("onap.policies.controlloop.Operational").build(); List<ToscaPolicy> filteredList = filter.filter(policyList); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java index 561b4fb21..1d393c1d5 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierOptVersionTest.java @@ -31,17 +31,15 @@ import org.junit.Test; * Test the other constructors, as {@link PojosTest} tests the other methods. */ public class ToscaPolicyIdentifierOptVersionTest extends ToscaIdentifierTestBase<ToscaPolicyIdentifierOptVersion> { - private static final String NAME = "my-name"; - private static final String VERSION = "1.2.3"; public ToscaPolicyIdentifierOptVersionTest() { - super(ToscaPolicyIdentifierOptVersion.class); + super(ToscaPolicyIdentifierOptVersion.class, "policy-id", "policy-version"); } @Test public void testAllArgsConstructor_testIsNullVersion() { assertThatThrownBy(() -> new ToscaPolicyIdentifierOptVersion(null, VERSION)) - .isInstanceOf(NullPointerException.class); + .isInstanceOf(NullPointerException.class); // with null version ToscaPolicyIdentifierOptVersion orig = new ToscaPolicyIdentifierOptVersion(NAME, null); @@ -57,7 +55,8 @@ public class ToscaPolicyIdentifierOptVersionTest extends ToscaIdentifierTestBase @Test public void testCopyConstructor() throws Exception { - assertThatThrownBy(() -> new ToscaPolicyIdentifierOptVersion(null)).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new ToscaPolicyIdentifierOptVersion((ToscaPolicyIdentifierOptVersion) null)) + .isInstanceOf(NullPointerException.class); ToscaPolicyIdentifierOptVersion orig = new ToscaPolicyIdentifierOptVersion(); @@ -68,4 +67,29 @@ public class ToscaPolicyIdentifierOptVersionTest extends ToscaIdentifierTestBase orig = makeIdent(NAME, VERSION); assertEquals(orig.toString(), new ToscaPolicyIdentifierOptVersion(orig).toString()); } + + @Test + public void testCopyToscaPolicyIdentifierConstructor() throws Exception { + assertThatThrownBy(() -> new ToscaPolicyIdentifierOptVersion((ToscaPolicyIdentifier) null)) + .isInstanceOf(NullPointerException.class); + + ToscaPolicyIdentifier orig = new ToscaPolicyIdentifier(); + + // verify with null values + ToscaPolicyIdentifierOptVersion newIdent = new ToscaPolicyIdentifierOptVersion(orig); + assertEquals(null, newIdent.getName()); + assertEquals(null, newIdent.getVersion()); + + // verify with all values + orig.setName(NAME); + orig.setVersion(VERSION); + newIdent = new ToscaPolicyIdentifierOptVersion(orig); + assertEquals(NAME, newIdent.getName()); + assertEquals(VERSION, newIdent.getVersion()); + } + + @Test + public void testCompareTo() throws Exception { + super.testCompareTo(); + } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java index a53af7b1f..f31abf837 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyIdentifierTest.java @@ -22,18 +22,21 @@ package org.onap.policy.models.tosca.authorative.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; /** - * Test the other constructors, as {@link PojosTest} tests the other methods. + * Test methods not tested by {@link PojosTest}. */ public class ToscaPolicyIdentifierTest extends ToscaIdentifierTestBase<ToscaPolicyIdentifier> { - private static final String NAME = "my-name"; - private static final String VERSION = "1.2.3"; public ToscaPolicyIdentifierTest() { - super(ToscaPolicyIdentifier.class); + super(ToscaPolicyIdentifier.class, "name", "version"); } @Test @@ -59,4 +62,30 @@ public class ToscaPolicyIdentifierTest extends ToscaIdentifierTestBase<ToscaPoli orig = new ToscaPolicyIdentifier(NAME, VERSION); assertEquals(orig.toString(), new ToscaPolicyIdentifier(orig).toString()); } + + @Test + public void testValidatePapRest() throws Exception { + ToscaPolicyIdentifier ident = new ToscaPolicyIdentifier(NAME, VERSION); + ValidationResult result = ident.validatePapRest(); + assertNotNull(result); + assertTrue(result.isValid()); + assertNull(result.getResult()); + + ident = makeIdent(NAME, null); + result = ident.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + + ident = makeIdent(null, VERSION); + result = ident.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + } + + @Test + public void testCompareTo() throws Exception { + super.testCompareTo(); + } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java index 8388f1061..e440dd6da 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/ToscaPolicyTypeIdentifierTest.java @@ -22,18 +22,21 @@ package org.onap.policy.models.tosca.authorative.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; /** - * Test the other constructors, as {@link PojosTest} tests the other methods. + * Test methods not tested by {@link PojosTest}. */ public class ToscaPolicyTypeIdentifierTest extends ToscaIdentifierTestBase<ToscaPolicyTypeIdentifier> { - private static final String NAME = "my-name"; - private static final String VERSION = "1.2.3"; public ToscaPolicyTypeIdentifierTest() { - super(ToscaPolicyTypeIdentifier.class); + super(ToscaPolicyTypeIdentifier.class, "name", "version"); } @Test @@ -60,4 +63,29 @@ public class ToscaPolicyTypeIdentifierTest extends ToscaIdentifierTestBase<Tosca assertEquals(orig.toString(), new ToscaPolicyTypeIdentifier(orig).toString()); } + @Test + public void testValidatePapRest() throws Exception { + ToscaPolicyTypeIdentifier ident = new ToscaPolicyTypeIdentifier(NAME, VERSION); + ValidationResult result = ident.validatePapRest(); + assertNotNull(result); + assertTrue(result.isValid()); + assertNull(result.getResult()); + + ident = makeIdent(NAME, null); + result = ident.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + + ident = makeIdent(null, VERSION); + result = ident.validatePapRest(); + assertNotNull(result); + assertFalse(result.isValid()); + assertNotNull(result.getResult()); + } + + @Test + public void testCompareTo() throws Exception { + super.testCompareTo(); + } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java new file mode 100644 index 000000000..5ad314ae6 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTest.java @@ -0,0 +1,399 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.tosca.authorative.provider; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.dao.DaoParameters; +import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.dao.PfDaoFactory; +import org.onap.policy.models.dao.impl.DefaultPfDao; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate; + +/** + * Test of the {@link AuthorativeToscaProvider} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class AuthorativeToscaProviderPolicyTest { + private PfDao pfDao; + private StandardCoder standardCoder; + + /** + * Set up the DAO towards the database. + * + * @throws Exception on database errors + */ + @Before + public void setupDao() throws Exception { + final DaoParameters daoParameters = new DaoParameters(); + daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); + + daoParameters.setPersistenceUnit("ToscaConceptTest"); + + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); + + // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + + daoParameters.setJdbcProperties(jdbcProperties ); + + pfDao = new PfDaoFactory().createPfDao(daoParameters); + pfDao.init(daoParameters); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + standardCoder = new StandardCoder(); + } + + @After + public void teardown() throws Exception { + pfDao.close(); + } + + @Test + public void testPoliciesGet() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getPolicies(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getPolicyList(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( + ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaPolicy beforePolicy = + toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + ToscaPolicy createdPolicy = + createdServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, createdPolicy)); + assertTrue(beforePolicy.getType().equals(createdPolicy.getType())); + + ToscaServiceTemplate gotServiceTemplate = + new AuthorativeToscaProvider().getPolicies(pfDao, policyKey.getName(), policyKey.getVersion()); + + ToscaPolicy gotPolicy = + gotServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicy)); + assertTrue(beforePolicy.getType().equals(gotPolicy.getType())); + + List<ToscaPolicy> gotPolicyList = + new AuthorativeToscaProvider().getPolicyList(pfDao, "onap.restart.tca", "1.0.0"); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, "onap.restart.tca", null); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, null, null); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, null, "1.0.0"); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = new AuthorativeToscaProvider().getPolicyList(pfDao, "Nonexistant", "1.0.0"); + assertEquals(0, gotPolicyList.size()); + } + + @Test + public void testPoliciesGetFiltered() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicies(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicies(null, ToscaPolicyFilter.builder().build()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicies(pfDao, null); + }).hasMessage("filter is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyList(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyList(null, ToscaPolicyFilter.builder().build()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, null); + }).hasMessage("filter is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( + ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaPolicy beforePolicy = + toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + ToscaPolicy createdPolicy = + createdServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, createdPolicy)); + assertTrue(beforePolicy.getType().equals(createdPolicy.getType())); + + ToscaServiceTemplate gotServiceTemplate = + new AuthorativeToscaProvider().getFilteredPolicies(pfDao, ToscaPolicyFilter.builder().build()); + + ToscaPolicy gotPolicy = + gotServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicy)); + assertTrue(beforePolicy.getType().equals(gotPolicy.getType())); + + gotServiceTemplate = new AuthorativeToscaProvider().getFilteredPolicies(pfDao, + ToscaPolicyFilter.builder().name(policyKey.getName()).build()); + + gotPolicy = gotServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicy)); + assertTrue(beforePolicy.getType().equals(gotPolicy.getType())); + + gotServiceTemplate = new AuthorativeToscaProvider().getFilteredPolicies(pfDao, + ToscaPolicyFilter.builder().name(policyKey.getName()).version("1.0.0").build()); + + gotPolicy = gotServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicy)); + assertTrue(beforePolicy.getType().equals(gotPolicy.getType())); + + List<ToscaPolicy> gotPolicyList = + new AuthorativeToscaProvider().getPolicyList(pfDao, "onap.restart.tca", "1.0.0"); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = + new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, ToscaPolicyFilter.builder().build()); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, + ToscaPolicyFilter.builder().name(policyKey.getName()).build()); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + + gotPolicyList = new AuthorativeToscaProvider().getFilteredPolicyList(pfDao, + ToscaPolicyFilter.builder().name(policyKey.getName()).version("1.0.0").build()); + assertEquals(1, gotPolicyList.size()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, gotPolicyList.get(0))); + } + + @Test + public void testPolicyCreate() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(null, new ToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( + ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaPolicy beforePolicy = + toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + ToscaPolicy createdPolicy = + createdServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, createdPolicy)); + assertTrue(beforePolicy.getType().equals(createdPolicy.getType())); + } + + + @Test + public void testPolicyUpdate() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().updatePolicies(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().updatePolicies(null, new ToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().updatePolicies(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( + ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaPolicy beforePolicy = + toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + ToscaPolicy createdPolicy = + createdServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, createdPolicy)); + assertTrue(beforePolicy.getType().equals(createdPolicy.getType())); + + ToscaServiceTemplate updatedServiceTemplate = + new AuthorativeToscaProvider().updatePolicies(pfDao, toscaServiceTemplate); + + ToscaPolicy updatedPolicy = + updatedServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, updatedPolicy)); + assertTrue(beforePolicy.getType().equals(updatedPolicy.getType())); + } + + @Test + public void testPoliciesDelete() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(null, null, "version"); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(null, "name", null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(null, "name", "version"); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(pfDao, null, null); + }).hasMessage("name is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(pfDao, null, "version"); + }).hasMessage("name is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(pfDao, "name", null); + }).hasMessage("version is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( + ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicies(pfDao, toscaServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaPolicy beforePolicy = + toscaServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + ToscaPolicy createdPolicy = + createdServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, createdPolicy)); + assertTrue(beforePolicy.getType().equals(createdPolicy.getType())); + + ToscaServiceTemplate deletedServiceTemplate = + new AuthorativeToscaProvider().deletePolicy(pfDao, policyKey.getName(), policyKey.getVersion()); + + ToscaPolicy deletedPolicy = + deletedServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).get(policyKey.getName()); + assertEquals(0, beforePolicy.compareNameVersion(beforePolicy, createdPolicy)); + assertTrue(beforePolicy.getType().equals(deletedPolicy.getType())); + + ToscaServiceTemplate gotServiceTemplate = + new AuthorativeToscaProvider().getPolicies(pfDao, policyKey.getName(), policyKey.getVersion()); + + assertEquals(0, gotServiceTemplate.getToscaTopologyTemplate().getPolicies().get(0).size()); + } + + @Test + public void testAssertPoliciesExist() throws PfModelException { + ToscaServiceTemplate testServiceTemplate = new ToscaServiceTemplate(); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicy(pfDao, "name", null); + }).hasMessage("version is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(pfDao, testServiceTemplate); + }).hasMessage("topology template not specified on service template"); + + testServiceTemplate.setToscaTopologyTemplate(new ToscaTopologyTemplate()); + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(pfDao, testServiceTemplate); + }).hasMessage("no policies specified on topology template of service template"); + + testServiceTemplate.getToscaTopologyTemplate().setPolicies(new ArrayList<>()); + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicies(pfDao, testServiceTemplate); + }).hasMessage("An incoming list of concepts must have at least one entry"); + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java new file mode 100644 index 000000000..6a925bcf3 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/AuthorativeToscaProviderPolicyTypeTest.java @@ -0,0 +1,408 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.tosca.authorative.provider; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import com.google.gson.GsonBuilder; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.apache.commons.lang3.ObjectUtils; +import org.eclipse.persistence.config.PersistenceUnitProperties; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.common.utils.coder.StandardCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.dao.DaoParameters; +import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.dao.PfDaoFactory; +import org.onap.policy.models.dao.impl.DefaultPfDao; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeFilter; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate; +import org.yaml.snakeyaml.Yaml; + +/** + * Test of the {@link AuthorativeToscaProvider} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class AuthorativeToscaProviderPolicyTypeTest { + private static String yamlAsJsonString; + private PfDao pfDao; + private StandardCoder standardCoder; + + + /** + * Read the policy type definition. + * + * @throws Exception on errors + */ + @BeforeClass + public static void readPolicyDefinition() { + String yamlString = + ResourceUtils.getResourceAsString("policytypes/onap.policies.optimization.AffinityPolicy.yaml"); + + Object yamlObject = new Yaml().load(yamlString); + yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject); + } + + /** + * Set up the DAO towards the database. + * + * @throws Exception on database errors + */ + @Before + public void setupDao() throws Exception { + final DaoParameters daoParameters = new DaoParameters(); + daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); + + daoParameters.setPersistenceUnit("ToscaConceptTest"); + + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); + + // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + + daoParameters.setJdbcProperties(jdbcProperties ); + + pfDao = new PfDaoFactory().createPfDao(daoParameters); + pfDao.init(daoParameters); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + standardCoder = new StandardCoder(); + } + + @After + public void teardown() throws Exception { + pfDao.close(); + } + + @Test + public void testPolicyTypesGet() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getPolicyTypes(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getPolicyList(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate); + + PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0"); + + ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName()); + ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(createdPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription())); + + ToscaServiceTemplate gotServiceTemplate = new AuthorativeToscaProvider().getPolicyTypes(pfDao, + policyTypeKey.getName(), policyTypeKey.getVersion()); + + ToscaPolicyType gotPolicyType = gotServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription())); + + List<ToscaPolicyType> gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, + "onap.policies.optimization.AffinityPolicy", "0.0.0"); + assertEquals(1, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, + "onap.policies.optimization.AffinityPolicy", null); + assertEquals(1, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, null, null); + assertEquals(2, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, null, "0.0.0"); + assertEquals(2, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + } + + + @Test + public void testPolicyTypesGetFiltered() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyTypes(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyTypes(null, ToscaPolicyTypeFilter.builder().build()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, null); + }).hasMessage("filter is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyTypeList(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyTypeList(null, ToscaPolicyTypeFilter.builder().build()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, null); + }).hasMessage("filter is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate); + + PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0"); + + ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName()); + ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(createdPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription())); + + ToscaServiceTemplate gotServiceTemplate = + new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, ToscaPolicyTypeFilter.builder().build()); + + ToscaPolicyType gotPolicyType = gotServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), gotPolicyType.getDescription())); + + gotServiceTemplate = new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, + ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).build()); + + gotPolicyType = gotServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), gotPolicyType.getDescription())); + + gotServiceTemplate = new AuthorativeToscaProvider().getFilteredPolicyTypes(pfDao, + ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).version("0.0.0").build()); + + gotPolicyType = gotServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), gotPolicyType.getDescription())); + + List<ToscaPolicyType> gotPolicyTypeList = new AuthorativeToscaProvider().getPolicyTypeList(pfDao, + "onap.policies.optimization.AffinityPolicy", "0.0.0"); + assertEquals(1, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, + ToscaPolicyTypeFilter.builder().build()); + assertEquals(2, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, + ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).build()); + assertEquals(1, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, + ToscaPolicyTypeFilter.builder().name(policyTypeKey.getName()).version("0.0.0").build()); + assertEquals(1, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + + gotPolicyTypeList = new AuthorativeToscaProvider().getFilteredPolicyTypeList(pfDao, + ToscaPolicyTypeFilter.builder().version("1.0.0").build()); + assertEquals(1, gotPolicyTypeList.size()); + assertEquals(true, beforePolicyType.getName().equals(gotPolicyType.getName())); + } + + @Test + public void testPolicyTypesCreate() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(null, new ToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + ToscaServiceTemplate testToscaServiceTemplate = new ToscaServiceTemplate(); + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(pfDao, testToscaServiceTemplate); + }).hasMessage("no policy types specified on service template"); + + testToscaServiceTemplate.setPolicyTypes(new ArrayList<>()); + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(pfDao, testToscaServiceTemplate); + }).hasMessage("An incoming list of concepts must have at least one entry"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate); + + PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0"); + + ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName()); + ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(createdPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription())); + } + + @Test + public void testPolicyTypesUpdate() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().updatePolicyTypes(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().updatePolicyTypes(null, new ToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().updatePolicyTypes(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate); + + PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0"); + + ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName()); + ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(createdPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription())); + + ToscaServiceTemplate updatedServiceTemplate = + new AuthorativeToscaProvider().updatePolicyTypes(pfDao, toscaServiceTemplate); + + ToscaPolicyType updatedPolicy = updatedServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(updatedPolicy.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), updatedPolicy.getDescription())); + } + + @Test + public void testPolicyTypesDelete() throws Exception { + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(null, null, "version"); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(null, "name", null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(null, "name", "version"); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(pfDao, null, null); + }).hasMessage("name is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(pfDao, null, "version"); + }).hasMessage("name is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(pfDao, "name", null); + }).hasMessage("version is marked @NonNull but is null"); + + ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode(yamlAsJsonString, ToscaServiceTemplate.class); + + assertNotNull(toscaServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new AuthorativeToscaProvider().createPolicyTypes(pfDao, toscaServiceTemplate); + + PfConceptKey policyTypeKey = new PfConceptKey("onap.policies.optimization.AffinityPolicy:0.0.0"); + + ToscaPolicyType beforePolicyType = toscaServiceTemplate.getPolicyTypes().get(1).get(policyTypeKey.getName()); + ToscaPolicyType createdPolicyType = createdServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(createdPolicyType.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), createdPolicyType.getDescription())); + + ToscaServiceTemplate deletedServiceTemplate = new AuthorativeToscaProvider().deletePolicyType(pfDao, + policyTypeKey.getName(), policyTypeKey.getVersion()); + + ToscaPolicyType deletedPolicy = deletedServiceTemplate.getPolicyTypes().get(0).get(policyTypeKey.getName()); + assertEquals(true, beforePolicyType.getName().equals(deletedPolicy.getName())); + assertEquals(0, ObjectUtils.compare(beforePolicyType.getDescription(), deletedPolicy.getDescription())); + + ToscaServiceTemplate gotServiceTemplate = new AuthorativeToscaProvider().getPolicyTypes(pfDao, + policyTypeKey.getName(), policyTypeKey.getVersion()); + + assertEquals(0, gotServiceTemplate.getPolicyTypes().get(0).size()); + } + + @Test + public void testAssertPoliciesExist() throws PfModelException { + ToscaServiceTemplate testServiceTemplate = new ToscaServiceTemplate(); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().deletePolicyType(pfDao, "name", null); + }).hasMessage("version is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(pfDao, testServiceTemplate); + }).hasMessage("no policy types specified on service template"); + + testServiceTemplate.setToscaTopologyTemplate(new ToscaTopologyTemplate()); + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(pfDao, testServiceTemplate); + }).hasMessage("no policy types specified on service template"); + + testServiceTemplate.setPolicyTypes(new ArrayList<>()); + assertThatThrownBy(() -> { + new AuthorativeToscaProvider().createPolicyTypes(pfDao, testServiceTemplate); + }).hasMessage("An incoming list of concepts must have at least one entry"); + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/mapping/ToscaServiceTemplateMappingTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java index 1bac0b973..a4458a874 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/mapping/ToscaServiceTemplateMappingTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/provider/ToscaServiceTemplateMappingTest.java @@ -21,7 +21,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.tosca.authorative.mapping; +package org.onap.policy.models.tosca.authorative.provider; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java index 5720b5594..9c2344080 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java @@ -20,6 +20,7 @@ package org.onap.policy.models.tosca.legacy.concepts; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -28,6 +29,7 @@ import java.util.Map; import org.junit.Test; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyInput; +import org.onap.policy.models.tosca.legacy.concepts.testconcepts.DummyBadLegacyGuardPolicyContent; public class LegacyGuardPolicyTest { @@ -45,6 +47,10 @@ public class LegacyGuardPolicyTest { content.setActor("SO"); guard.setContent(content); assertEquals("SO", guard.getContent().getActor()); - } + DummyBadLegacyGuardPolicyContent dblgpc = new DummyBadLegacyGuardPolicyContent(); + assertThatThrownBy(() -> { + dblgpc.getAsPropertyMap(); + }).hasMessage("could not convert content to a property map"); + } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/TestPojos.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/TestPojos.java index f35a4e668..26077189e 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/TestPojos.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/TestPojos.java @@ -44,9 +44,19 @@ public class TestPojos { @Test public void testPojos() { - final Validator validator = ValidatorBuilder.create().with(new ToStringTester()) - .with(new SetterMustExistRule()).with(new GetterMustExistRule()).with(new SetterTester()) - .with(new GetterTester()).build(); - validator.validate(POJO_PACKAGE, new FilterPackageInfo()); + // @formatter:off + final Validator validator = ValidatorBuilder + .create() + .with(new ToStringTester()) + .with(new SetterMustExistRule()) + .with(new GetterMustExistRule()) + .with(new SetterTester()) + .with(new GetterTester()) + .build(); + validator.validate(POJO_PACKAGE, + new FilterPackageInfo() + ); + + // @formatter:on } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/testconcepts/DummyBadLegacyGuardPolicyContent.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/testconcepts/DummyBadLegacyGuardPolicyContent.java new file mode 100644 index 000000000..1b149416c --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/testconcepts/DummyBadLegacyGuardPolicyContent.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.tosca.legacy.concepts.testconcepts; + +import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyContent; + +/** + * Dummy {@link LegacyGuardPolicyContent} class to force exception for testing. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class DummyBadLegacyGuardPolicyContent extends LegacyGuardPolicyContent { + public static final String TO_TRIGGER_EXCEPTION = "Dummy"; + @SuppressWarnings("unused") + private final transient String aaa = "aaa"; +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java new file mode 100644 index 000000000..f2fb53d60 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyGuardPolicyMapperTest.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.tosca.legacy.mapping; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; + +import org.junit.Test; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate; + +/** + * Test the {@link LegacyGuardPolicyMapper} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class LegacyGuardPolicyMapperTest { + + @Test + public void testLegacyGuardPolicyMapper() { + JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate(); + serviceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies()); + + JpaToscaPolicy policy = new JpaToscaPolicy(new PfConceptKey("PolicyName", "0.0.1")); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policy.getKey(), policy); + + assertThatThrownBy(() -> { + new LegacyGuardPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + }).hasMessageContaining("no metadata defined on TOSCA policy"); + + policy.setMetadata(new LinkedHashMap<>()); + assertThatThrownBy(() -> { + new LegacyGuardPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + }).hasMessageContaining("no properties defined on TOSCA policy"); + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java index 26242611b..4df62aff0 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapperTest.java @@ -18,20 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.tosca.legacy.serialization; +package org.onap.policy.models.tosca.legacy.mapping; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import java.util.LinkedHashMap; + import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfValidationResult; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; import org.onap.policy.models.tosca.legacy.mapping.LegacyOperationalPolicyMapper; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,9 +47,9 @@ import org.slf4j.LoggerFactory; * * @author Liam Fallon (liam.fallon@est.tech) */ -public class LegacyOperationalPolicySerializationTest { +public class LegacyOperationalPolicyMapperTest { // Logger for this class - private static final Logger LOGGER = LoggerFactory.getLogger(LegacyOperationalPolicySerializationTest.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LegacyOperationalPolicyMapperTest.class); private StandardCoder standardCoder; @@ -68,4 +75,31 @@ public class LegacyOperationalPolicySerializationTest { assertEquals("operational.restart:1.0.0", serviceTemplate.getTopologyTemplate().getPolicies().get("operational.restart").getId()); } + + @Test + public void testOperationalPolicyMapper() throws Exception { + JpaToscaServiceTemplate serviceTemplate = new JpaToscaServiceTemplate(); + serviceTemplate.setTopologyTemplate(new JpaToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new JpaToscaPolicies()); + + JpaToscaPolicy policy0 = new JpaToscaPolicy(new PfConceptKey("PolicyName0", "0.0.1")); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policy0.getKey(), policy0); + JpaToscaPolicy policy1 = new JpaToscaPolicy(new PfConceptKey("PolicyName1", "0.0.1")); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policy1.getKey(), policy1); + + assertThatThrownBy(() -> { + new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + }).hasMessage("more than one policy found in service template"); + + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().remove(policy1.getKey()); + + assertThatThrownBy(() -> { + new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + }).hasMessage("no properties defined on TOSCA policy"); + + policy0.setProperties(new LinkedHashMap<>()); + assertThatThrownBy(() -> { + new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + }).hasMessage("property \"content\" not defined on TOSCA policy"); + } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java index 2fdc3aae7..71254ec6f 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyGuardTest.java @@ -24,10 +24,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.sql.Connection; -import java.sql.DriverManager; import java.util.Map; +import java.util.Properties; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -47,7 +47,6 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicyOutput; * @author Liam Fallon (liam.fallon@est.tech) */ public class LegacyProvider4LegacyGuardTest { - private Connection connection; private PfDao pfDao; private StandardCoder standardCoder; @@ -59,17 +58,21 @@ public class LegacyProvider4LegacyGuardTest { */ @Before public void setupDao() throws Exception { - // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database - // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance - connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); - final DaoParameters daoParameters = new DaoParameters(); daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); - // Use the persistence unit ToscaConceptTest to test towards the h2 database - // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance daoParameters.setPersistenceUnit("ToscaConceptTest"); + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); + + // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + + daoParameters.setJdbcProperties(jdbcProperties); + pfDao = new PfDaoFactory().createPfDao(daoParameters); pfDao.init(daoParameters); } @@ -85,7 +88,6 @@ public class LegacyProvider4LegacyGuardTest { @After public void teardown() throws Exception { pfDao.close(); - connection.close(); } @Test diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java index d198bd4f5..c018aae7b 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider4LegacyOperationalTest.java @@ -24,9 +24,9 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.sql.Connection; -import java.sql.DriverManager; +import java.util.Properties; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -44,7 +44,6 @@ import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; * @author Liam Fallon (liam.fallon@est.tech) */ public class LegacyProvider4LegacyOperationalTest { - private Connection connection; private PfDao pfDao; private StandardCoder standardCoder; @@ -55,17 +54,21 @@ public class LegacyProvider4LegacyOperationalTest { */ @Before public void setupDao() throws Exception { - // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database - // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance - connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); - final DaoParameters daoParameters = new DaoParameters(); daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); - // Use the persistence unit ToscaConceptTest to test towards the h2 database - // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance daoParameters.setPersistenceUnit("ToscaConceptTest"); + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); + + // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + + daoParameters.setJdbcProperties(jdbcProperties ); + pfDao = new PfDaoFactory().createPfDao(daoParameters); pfDao.init(daoParameters); } @@ -81,7 +84,6 @@ public class LegacyProvider4LegacyOperationalTest { @After public void teardown() throws Exception { pfDao.close(); - connection.close(); } @Test diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java index de0c813e2..d3239da73 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintLogicalTest.java @@ -21,44 +21,55 @@ package org.onap.policy.models.tosca.simple.concepts; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; import org.junit.Test; -import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraintLogical; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConstraint; /** - * DAO test for ToscaConstraintLogicalString. + * Test the {@link JpaToscaConstraintLogical} class. * * @author Liam Fallon (liam.fallon@est.tech) */ public class JpaToscaConstraintLogicalTest { @Test - public void testConstraintLogicalStringPojo() { - assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint")); + public void testLogicalConstraint() { + ToscaConstraint c0 = new ToscaConstraint(); + c0.setEqual("Hello"); + JpaToscaConstraintLogical jc0 = new JpaToscaConstraintLogical(c0); + assertEquals(c0, jc0.toAuthorative()); + + ToscaConstraint c1 = new ToscaConstraint(); + c1.setGreaterOrEqual("Hello"); + JpaToscaConstraintLogical jc1 = new JpaToscaConstraintLogical(c1); + assertEquals(c1, jc1.toAuthorative()); + + ToscaConstraint c2 = new ToscaConstraint(); + c2.setGreaterThan("Hello"); + JpaToscaConstraintLogical jc2 = new JpaToscaConstraintLogical(c2); + assertEquals(c2, jc2.toAuthorative()); - try { - new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("operation is marked @NonNull but is null", exc.getMessage()); - } + ToscaConstraint c3 = new ToscaConstraint(); + c3.setLessOrEqual("Hello"); + JpaToscaConstraintLogical jc3 = new JpaToscaConstraintLogical(c3); + assertEquals(c3, jc3.toAuthorative()); - try { - new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, "Hello"); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("operation is marked @NonNull but is null", exc.getMessage()); - } + ToscaConstraint c4 = new ToscaConstraint(); + c4.setLessThan("Hello"); + JpaToscaConstraintLogical jc4 = new JpaToscaConstraintLogical(c4); + assertEquals(c4, jc4.toAuthorative()); - try { - new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("compareTo is marked @NonNull but is null", exc.getMessage()); - } + ToscaConstraint c5 = new ToscaConstraint(); + JpaToscaConstraintLogical jc5 = new JpaToscaConstraintLogical(c5); + assertNull(jc5.toAuthorative()); - assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint")); + assertEquals(-1, jc0.compareTo(null)); + assertEquals(0, jc0.compareTo(jc0)); + assertNotEquals(0, jc0.compareTo(new JpaToscaConstraintValidValues(new ArrayList<>()))); + assertEquals(-2, jc0.compareTo(jc1)); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java new file mode 100644 index 000000000..ff4187a47 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaConstraintTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.tosca.simple.concepts; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConstraint; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraintLogical; + +/** + * DAO test for ToscaConstraintLogicalString. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class JpaToscaConstraintTest { + + @Test + public void testConstraintLogicalStringPojo() { + assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint")); + + try { + new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, null); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("operation is marked @NonNull but is null", exc.getMessage()); + } + + try { + new JpaToscaConstraintLogical((JpaToscaConstraintOperation) null, "Hello"); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("operation is marked @NonNull but is null", exc.getMessage()); + } + + try { + new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, null); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("compareTo is marked @NonNull but is null", exc.getMessage()); + } + + assertNotNull(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint")); + + assertEquals(0, new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "") + .compareTo(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, ""))); + + JpaToscaConstraintOperation op = JpaToscaConstraintOperation.EQ; + assertEquals("equal_to", op.getToscaToken()); + + List<String> validValues = new ArrayList<>(); + validValues.add("hello"); + validValues.add("goodbye"); + JpaToscaConstraintValidValues cvv0 = new JpaToscaConstraintValidValues(validValues); + assertEquals(-1, cvv0.compareTo(null)); + assertEquals(0, cvv0.compareTo(cvv0)); + assertNotEquals(0, cvv0.compareTo(new JpaToscaConstraintLogical(JpaToscaConstraintOperation.EQ, "Constraint"))); + JpaToscaConstraintValidValues cvv1 = new JpaToscaConstraintValidValues(validValues); + assertEquals(0, cvv0.compareTo(cvv1)); + + cvv1.fromAuthorative(new ToscaConstraint()); + assertNotNull(cvv1.getValidValues()); + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java index efdddccb0..66cde51fc 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypeTest.java @@ -20,11 +20,11 @@ package org.onap.policy.models.tosca.simple.concepts; +import static org.assertj.core.api.Assertions.assertThatThrownBy; 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 java.util.ArrayList; import java.util.LinkedHashMap; @@ -35,6 +35,8 @@ import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConstraint; +import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaConstraint; import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty; @@ -51,20 +53,15 @@ public class JpaToscaDataTypeTest { assertNotNull(new JpaToscaDataType()); assertNotNull(new JpaToscaDataType(new PfConceptKey())); assertNotNull(new JpaToscaDataType(new JpaToscaDataType())); + assertNotNull(new JpaToscaDataType(new ToscaDataType())); - try { + assertThatThrownBy(() -> { new JpaToscaDataType((PfConceptKey) null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaDataType((JpaToscaDataType) null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("copyConcept is marked @NonNull but is null"); PfConceptKey dtKey = new PfConceptKey("tdt", "0.0.1"); JpaToscaDataType tdt = new JpaToscaDataType(dtKey); @@ -105,12 +102,9 @@ public class JpaToscaDataTypeTest { otherDt.setProperties(properties); assertEquals(0, tdt.compareTo(otherDt)); - try { + assertThatThrownBy(() -> { tdt.copyTo(null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("target is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("target is marked @NonNull but is null"); assertEquals(3, tdt.getKeys().size()); assertEquals(1, new JpaToscaDataType().getKeys().size()); @@ -132,12 +126,23 @@ public class JpaToscaDataTypeTest { tdt.getProperties().remove(null); assertTrue(tdt.validate(new PfValidationResult()).isValid()); - try { + assertThatThrownBy(() -> { tdt.validate(null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("resultIn is marked @NonNull but is null", exc.getMessage()); - } - + }).hasMessage("resultIn is marked @NonNull but is null"); + + ToscaDataType dat = new ToscaDataType(); + dat.setName("name"); + dat.setVersion("1.2.3"); + dat.setConstraints(new ArrayList<>()); + ToscaConstraint constraint = new ToscaConstraint(); + constraint.setEqual("EqualTo"); + dat.getConstraints().add(constraint); + + JpaToscaDataType tdta = new JpaToscaDataType(); + tdta.fromAuthorative(dat); + assertEquals("name", tdta.getKey().getName()); + + ToscaDataType datOut = tdta.toAuthorative(); + assertNotNull(datOut); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java index ce90e372c..c732fa604 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaDataTypesTest.java @@ -24,10 +24,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.TreeMap; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes; @@ -74,5 +79,10 @@ public class JpaToscaDataTypesTest { } catch (Exception exc) { assertEquals("key is marked @NonNull but is null", exc.getMessage()); } + + List<Map<String, ToscaDataType>> dtMapList = new ArrayList<>(); + dtMapList.add(new LinkedHashMap<>()); + dtMapList.get(0).put("policyType", new ToscaDataType()); + assertNotNull(new JpaToscaDataTypes(dtMapList)); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java index 6f6141c5b..db3635ecb 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPoliciesTest.java @@ -24,10 +24,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.TreeMap; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; @@ -74,5 +79,10 @@ public class JpaToscaPoliciesTest { } catch (Exception exc) { assertEquals("key is marked @NonNull but is null", exc.getMessage()); } + + List<Map<String, ToscaPolicy>> polMapList = new ArrayList<>(); + polMapList.add(new LinkedHashMap<>()); + polMapList.get(0).put("policyType", new ToscaPolicy()); + assertNotNull(new JpaToscaPolicies(polMapList)); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java index ec8e6da8f..ae38ab916 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTest.java @@ -20,11 +20,11 @@ package org.onap.policy.models.tosca.simple.concepts; +import static org.assertj.core.api.Assertions.assertThatThrownBy; 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 java.util.ArrayList; import java.util.HashMap; @@ -33,7 +33,9 @@ import java.util.Map; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; /** @@ -50,47 +52,36 @@ public class JpaToscaPolicyTest { assertNotNull(new JpaToscaPolicy(new PfConceptKey(), new PfConceptKey())); assertNotNull(new JpaToscaPolicy(new JpaToscaPolicy())); - try { + ToscaPolicy pol = new ToscaPolicy(); + pol.setType("type"); + assertNotNull(new JpaToscaPolicy(pol)); + + assertThatThrownBy(() -> { new JpaToscaPolicy((PfConceptKey) null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaPolicy(null, null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaPolicy(new PfConceptKey(), null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("type is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("type is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaPolicy(null, new PfConceptKey()); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaPolicy((JpaToscaPolicy) null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("copyConcept is marked @NonNull but is null"); PfConceptKey tpKey = new PfConceptKey("tdt", "0.0.1"); PfConceptKey ptKey = new PfConceptKey("policyType", "0.0.1"); JpaToscaPolicy tp = new JpaToscaPolicy(tpKey, ptKey); Map<String, String> propertyMap = new HashMap<>(); - propertyMap.put("Property", "Property Value"); + propertyMap.put("Property", "\"Property Value\""); tp.setProperties(propertyMap); assertEquals(propertyMap, tp.getProperties()); @@ -126,12 +117,9 @@ public class JpaToscaPolicyTest { otherDt.setTargets(targets); assertEquals(0, tp.compareTo(otherDt)); - try { + assertThatThrownBy(() -> { tp.copyTo(null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("target is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("target is marked @NonNull but is null"); assertEquals(3, tp.getKeys().size()); assertEquals(2, new JpaToscaPolicy().getKeys().size()); @@ -164,11 +152,35 @@ public class JpaToscaPolicyTest { tp.getTargets().remove(null); assertTrue(tp.validate(new PfValidationResult()).isValid()); - try { + PfConceptKey tpTypeKey = tp.getKey(); + assertNotNull(tpTypeKey); + tp.setType(null); + assertFalse(tp.validate(new PfValidationResult()).isValid()); + tp.setType(PfConceptKey.getNullKey()); + assertFalse(tp.validate(new PfValidationResult()).isValid()); + tp.setType(tpTypeKey); + assertTrue(tp.validate(new PfValidationResult()).isValid()); + + assertThatThrownBy(() -> { tp.validate(null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("resultIn is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("resultIn is marked @NonNull but is null"); + + assertNotNull(tp.toAuthorative()); + tp.getType().setVersion(PfKey.NULL_KEY_VERSION); + assertNotNull(tp.toAuthorative()); + tp.setProperties(null); + assertNotNull(tp.toAuthorative()); + + assertThatThrownBy(() -> { + tp.fromAuthorative(null); + }).hasMessage("toscaPolicy is marked @NonNull but is null"); + + pol = new ToscaPolicy(); + pol.setName("policy"); + pol.setVersion("1.2.3"); + pol.setType("poltype"); + pol.setTypeVersion("2.2.3"); + tp.fromAuthorative(pol); + assertEquals("2.2.3", tp.getType().getVersion()); } -}
\ No newline at end of file +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java index 870640e75..3cdcd9552 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypeTest.java @@ -37,6 +37,7 @@ import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.base.PfValidationResult; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaEntityType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty; @@ -209,5 +210,9 @@ public class JpaToscaPolicyTypeTest { assertEquals(-1, tet.compareTo(null)); assertEquals(0, tet.compareTo(tet)); assertFalse(tet.compareTo(tet.getKey()) == 0); + + assertNotNull(new JpaToscaPolicyType(new ToscaPolicyType())); + + assertNotNull(new JpaToscaEntityType<ToscaPolicyType>(new ToscaPolicyType())); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java index d0ea1782f..e02df235f 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPolicyTypesTest.java @@ -24,10 +24,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.TreeMap; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes; @@ -74,5 +79,10 @@ public class JpaToscaPolicyTypesTest { } catch (Exception exc) { assertEquals("key is marked @NonNull but is null", exc.getMessage()); } + + List<Map<String, ToscaPolicyType>> ptMapList = new ArrayList<>(); + ptMapList.add(new LinkedHashMap<>()); + ptMapList.get(0).put("policyType", new ToscaPolicyType()); + assertNotNull(new JpaToscaPolicyTypes(ptMapList)); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java index b8766601b..706011bcf 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaPropertyTest.java @@ -191,6 +191,8 @@ public class JpaToscaPropertyTest { tp.setDefaultValue(null); assertTrue(tp.validate(new PfValidationResult()).isValid()); + tp.setDefaultValue(""); + assertFalse(tp.validate(new PfValidationResult()).isValid()); tp.setDefaultValue("defaultKey"); assertTrue(tp.validate(new PfValidationResult()).isValid()); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java index 4569d42ff..a2a418ef9 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplateTest.java @@ -157,7 +157,7 @@ public class JpaToscaServiceTemplateTest { tst.clean(); assertEquals(tttClone0, tst); - assertFalse(new JpaToscaServiceTemplate().validate(new PfValidationResult()).isValid()); + assertTrue(new JpaToscaServiceTemplate().validate(new PfValidationResult()).isValid()); assertTrue(tst.validate(new PfValidationResult()).isValid()); tst.setDescription(null); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java index 91d6d0bd3..354fe8b78 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaServiceTemplatesTest.java @@ -20,14 +20,18 @@ package org.onap.policy.models.tosca.simple.concepts; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; import java.util.TreeMap; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplates; @@ -41,39 +45,29 @@ public class JpaToscaServiceTemplatesTest { new JpaToscaServiceTemplates(new PfConceptKey(), new TreeMap<PfConceptKey, JpaToscaServiceTemplate>())); assertNotNull(new JpaToscaServiceTemplates(new JpaToscaServiceTemplates())); - try { + assertThatThrownBy(() -> { new JpaToscaServiceTemplates((PfConceptKey) null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaServiceTemplates((JpaToscaServiceTemplates) null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("copyConcept is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaServiceTemplates(null, null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaServiceTemplates(new PfConceptKey(), null); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("conceptMap is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("conceptMap is marked @NonNull but is null"); - try { + assertThatThrownBy(() -> { new JpaToscaServiceTemplates(null, new TreeMap<PfConceptKey, JpaToscaServiceTemplate>()); - fail("test should throw an exception"); - } catch (Exception exc) { - assertEquals("key is marked @NonNull but is null", exc.getMessage()); - } + }).hasMessage("key is marked @NonNull but is null"); + + List<Map<String, ToscaServiceTemplate>> tsMapList = new ArrayList<>(); + tsMapList.add(new LinkedHashMap<>()); + tsMapList.get(0).put("serviceTemplate", new ToscaServiceTemplate()); + assertNotNull(new JpaToscaServiceTemplates(tsMapList)); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java index 417f202f5..61ce3d077 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/JpaToscaTopologyTemplateTest.java @@ -33,6 +33,7 @@ import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies; import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate; @@ -49,6 +50,7 @@ public class JpaToscaTopologyTemplateTest { assertNotNull(new JpaToscaTopologyTemplate()); assertNotNull(new JpaToscaTopologyTemplate(new PfReferenceKey())); assertNotNull(new JpaToscaTopologyTemplate(new JpaToscaTopologyTemplate())); + assertNotNull(new JpaToscaTopologyTemplate(new ToscaTopologyTemplate())); try { new JpaToscaTopologyTemplate((PfReferenceKey) null); @@ -121,6 +123,11 @@ public class JpaToscaTopologyTemplateTest { assertTrue(new JpaToscaTopologyTemplate().validate(new PfValidationResult()).isValid()); assertTrue(ttt.validate(new PfValidationResult()).isValid()); + ttt.setKey(PfReferenceKey.getNullKey()); + assertFalse(ttt.validate(new PfValidationResult()).isValid()); + ttt.setKey(tttKey); + assertTrue(ttt.validate(new PfValidationResult()).isValid()); + ttt.setDescription(null); assertTrue(ttt.validate(new PfValidationResult()).isValid()); ttt.setDescription(""); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/TestPojos.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/TestPojos.java index e5be49860..edb6e2e58 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/TestPojos.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/TestPojos.java @@ -40,7 +40,6 @@ import org.onap.policy.common.utils.validation.ToStringTester; * */ public class TestPojos { - private static final String POJO_PACKAGE = "org.onap.policy.models.tosca.simple.concepts"; @Test diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java index b13cb4b0b..f8e422160 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/testconcepts/DummyToscaConstraint.java @@ -45,4 +45,9 @@ public class DummyToscaConstraint extends JpaToscaConstraint { @Override public void fromAuthorative(ToscaConstraint authorativeConcept) { } + + @Override + public int compareTo(JpaToscaConstraint otherConstraint) { + return 0; + } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java index dca34b08e..1f582cf84 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java @@ -20,14 +20,15 @@ package org.onap.policy.models.tosca.simple.provider; +import static org.assertj.core.api.Assertions.assertThatThrownBy; 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.sql.Connection; -import java.sql.DriverManager; +import java.util.Properties; +import org.eclipse.persistence.config.PersistenceUnitProperties; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -50,11 +51,9 @@ import org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate; * @author Liam Fallon (liam.fallon@est.tech) */ public class SimpleToscaProviderTest { - private Connection connection; private PfDao pfDao; private StandardCoder standardCoder; - /** * Set up the DAO towards the database. * @@ -62,17 +61,21 @@ public class SimpleToscaProviderTest { */ @Before public void setupDao() throws Exception { - // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database - // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance - connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); - final DaoParameters daoParameters = new DaoParameters(); daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); - // Use the persistence unit ToscaConceptTest to test towards the h2 database - // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance daoParameters.setPersistenceUnit("ToscaConceptTest"); + Properties jdbcProperties = new Properties(); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); + + // H2, use "org.mariadb.jdbc.Driver" and "jdbc:mariadb://localhost:3306/policy" for locally installed MariaDB + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); + jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:testdb"); + + daoParameters.setJdbcProperties(jdbcProperties); + pfDao = new PfDaoFactory().createPfDao(daoParameters); pfDao.init(daoParameters); } @@ -88,18 +91,10 @@ public class SimpleToscaProviderTest { @After public void teardown() throws Exception { pfDao.close(); - connection.close(); } @Test public void testPoliciesGet() throws Exception { - try { - new SimpleToscaProvider().getPolicies(null, null, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), ToscaServiceTemplate.class); @@ -125,27 +120,6 @@ public class SimpleToscaProviderTest { @Test public void testPolicyCreate() throws Exception { - try { - new SimpleToscaProvider().createPolicies(null, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - - try { - new SimpleToscaProvider().createPolicies(null, new JpaToscaServiceTemplate()); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - - try { - new SimpleToscaProvider().createPolicies(pfDao, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("serviceTemplate is marked @NonNull but is null", exc.getMessage()); - } - ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), ToscaServiceTemplate.class); @@ -162,27 +136,6 @@ public class SimpleToscaProviderTest { @Test public void testPolicyUpdate() throws Exception { - try { - new SimpleToscaProvider().updatePolicies(null, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - - try { - new SimpleToscaProvider().updatePolicies(null, new JpaToscaServiceTemplate()); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - - try { - new SimpleToscaProvider().updatePolicies(pfDao, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("serviceTemplate is marked @NonNull but is null", exc.getMessage()); - } - ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), ToscaServiceTemplate.class); @@ -199,27 +152,6 @@ public class SimpleToscaProviderTest { @Test public void testPoliciesDelete() throws Exception { - try { - new SimpleToscaProvider().deletePolicy(null, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - - try { - new SimpleToscaProvider().deletePolicy(null, new PfConceptKey()); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("dao is marked @NonNull but is null", exc.getMessage()); - } - - try { - new SimpleToscaProvider().deletePolicy(pfDao, null); - fail("test should throw an exception here"); - } catch (Exception exc) { - assertEquals("policyKey is marked @NonNull but is null", exc.getMessage()); - } - ToscaServiceTemplate toscaServiceTemplate = standardCoder.decode( ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), ToscaServiceTemplate.class); @@ -272,6 +204,88 @@ public class SimpleToscaProviderTest { assertEquals("list of policies specified on topology template of service template is empty", exc.getMessage()); } + } + + @Test + public void testNonNulls() { + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicyTypes(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().createPolicyTypes(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().createPolicyTypes(null, new JpaToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().createPolicyTypes(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().updatePolicyTypes(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + assertThatThrownBy(() -> { + new SimpleToscaProvider().updatePolicyTypes(null, new JpaToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().updatePolicyTypes(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicyType(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicyType(null, new PfConceptKey()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicyType(pfDao, null); + }).hasMessage("policyTypeKey is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().getPolicies(null, null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().createPolicies(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().createPolicies(null, new JpaToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().createPolicies(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().updatePolicies(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().updatePolicies(null, new JpaToscaServiceTemplate()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().updatePolicies(pfDao, null); + }).hasMessage("serviceTemplate is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicy(null, null); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicy(null, new PfConceptKey()); + }).hasMessage("dao is marked @NonNull but is null"); + + assertThatThrownBy(() -> { + new SimpleToscaProvider().deletePolicy(pfDao, null); + }).hasMessage("policyKey is marked @NonNull but is null"); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java index 5f0cbb355..9d9ee608d 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java @@ -171,7 +171,7 @@ public class MonitoringPolicySerializationTest { JpaToscaPolicy policyVal = policiesConceptMap.values().iterator().next(); // Check metadata - assertTrue(policyVal.getMetadata().size() == 1); + assertTrue(policyVal.getMetadata().size() == 2); assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey()); assertEquals("onap.restart.tca", policyVal.getMetadata().entrySet().iterator().next().getValue()); @@ -204,7 +204,7 @@ public class MonitoringPolicySerializationTest { JpaToscaPolicy policyVal = policiesConceptMap.values().iterator().next(); // Check metadata - assertTrue(policyVal.getMetadata().size() == 1); + assertTrue(policyVal.getMetadata().size() == 2); assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey()); assertEquals("onap.scaleout.tca", policyVal.getMetadata().entrySet().iterator().next().getValue()); @@ -237,7 +237,7 @@ public class MonitoringPolicySerializationTest { JpaToscaPolicy policyVal = policiesConceptMap.values().iterator().next(); // Check metadata - assertTrue(policyVal.getMetadata().size() == 1); + assertTrue(policyVal.getMetadata().size() == 2); assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey()); assertEquals("onap.vfirewall.tca", policyVal.getMetadata().entrySet().iterator().next().getValue()); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java new file mode 100644 index 000000000..40a2fd29a --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/utils/ToscaUtilsTest.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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.models.tosca.utils; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.Test; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; + +/** + * Import the {@link ToscaUtils} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class ToscaUtilsTest { + + @Test + public void test() { + JpaToscaServiceTemplate jpaToscaServiceTemplate = new JpaToscaServiceTemplate(); + jpaToscaServiceTemplate.setPolicyTypes(new JpaToscaPolicyTypes()); + + assertThatThrownBy(() -> { + ToscaUtils.assertPolicyTypesExist(jpaToscaServiceTemplate); + }).hasMessage("list of policy types specified on service template is empty"); + } +} diff --git a/models-tosca/src/test/resources/META-INF/persistence.xml b/models-tosca/src/test/resources/META-INF/persistence.xml index 23e8567f1..936e5a11c 100644 --- a/models-tosca/src/test/resources/META-INF/persistence.xml +++ b/models-tosca/src/test/resources/META-INF/persistence.xml @@ -26,34 +26,13 @@ <class>org.onap.policy.models.dao.converters.CDataConditioner</class> <class>org.onap.policy.models.dao.converters.Uuid2String</class> <class>org.onap.policy.models.base.PfConceptKey</class> - <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class> <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class> + <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType</class> <properties> - <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" /> - <property name="javax.persistence.jdbc.user" value="policy" /> - <property name="javax.persistence.jdbc.password" value="P01icY" /> <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> <property name="eclipselink.logging.level" value="INFO" /> - </properties> - </persistence-unit> - - <persistence-unit name="ToscaConceptMariaDBTest" transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - - <class>org.onap.policy.models.dao.converters.CDataConditioner</class> - <class>org.onap.policy.models.dao.converters.Uuid2String</class> - <class>org.onap.policy.models.base.PfConceptKey</class> - <class>org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy</class> - - <properties> - <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" /> - <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/policy" /> - <property name="javax.persistence.jdbc.user" value="policy" /> - <property name="javax.persistence.jdbc.password" value="P01icY" /> - <property name="javax.persistence.schema-generation.database.action" value="create" /> <!-- property name="eclipselink.logging.level" value="ALL" /> <property name="eclipselink.logging.level.jpa" value="ALL" /> @@ -65,10 +44,6 @@ <property name="eclipselink.logging.level.server" value="ALL" /> <property name="eclipselink.logging.level.query" value="ALL" /> <property name="eclipselink.logging.level.properties" value="ALL" /--> - - <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> - <property name="eclipselink.ddl-generation.output-mode" value="database" /> - <property name="eclipselink.logging.level" value="INFO" /> </properties> </persistence-unit> </persistence> @@ -24,7 +24,7 @@ <parent> <groupId>org.onap.policy.parent</groupId> <artifactId>integration</artifactId> - <version>2.1.0-SNAPSHOT</version> + <version>2.1.0</version> <relativePath/> </parent> @@ -39,7 +39,7 @@ <properties> <derby.version>10.13.1.1</derby.version> <javax.ws.rs-api.version>2.0.1</javax.ws.rs-api.version> - <policy.common.version>1.4.0-SNAPSHOT</policy.common.version> + <policy.common.version>1.4.0</policy.common.version> <!-- sonar/jacoco overrides --> <!-- Overriding oparent default sonar/jacoco settings Combine all our reports into one file shared across sub-modules --> @@ -59,6 +59,7 @@ <module>models-provider</module> <module>models-examples</module> <module>models-interactions</module> + <module>models-sim</module> </modules> <distributionManagement> @@ -112,6 +113,11 @@ </dependency> <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + </dependency> + + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> diff --git a/version.properties b/version.properties index 614e56e9c..a3ac0d9c7 100644 --- a/version.properties +++ b/version.properties @@ -3,7 +3,7 @@ # because they are used in Jenkins, whose plug-in doesn't support major=2 -minor=1 +minor=0 patch=0 base_version=${major}.${minor}.${patch} |