private static final String NAME_TOKEN = "name";
private static final String VERSION_TOKEN = "version";
- @Column(name = NAME_TOKEN)
+ @Column(name = NAME_TOKEN, length = 128)
private String name;
- @Column(name = VERSION_TOKEN)
+ @Column(name = VERSION_TOKEN, length = 128)
private String version;
/**
private static final int PARENT_LOCAL_NAME_FIELD = 2;
private static final int LOCAL_NAME_FIELD = 3;
- @Column(name = PARENT_KEY_NAME)
+ @Column(name = PARENT_KEY_NAME, length = 128)
private String parentKeyName;
- @Column(name = PARENT_KEY_VERSION)
+ @Column(name = PARENT_KEY_VERSION, length = 128)
private String parentKeyVersion;
- @Column(name = PARENT_LOCAL_NAME)
+ @Column(name = PARENT_LOCAL_NAME, length = 128)
private String parentLocalName;
- @Column(name = LOCAL_NAME)
+ @Column(name = LOCAL_NAME, length = 128)
private String localName;
/**
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
-
</dependencies>
</project>
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"
+<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>
<artifactId>policy-models-tosca</artifactId>
<version>${project.version}</version>
</dependency>
+
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.mariadb.jdbc</groupId>
+ <artifactId>mariadb-java-client</artifactId>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
</project>
--- /dev/null
+/*-
+ * ============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.provider.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+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.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.simple.concepts.ToscaPolicy;
+import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate;
+import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test persistence of monitoring policies to and from the database.
+ *
+ * @author Liam Fallon (liam.fallon@est.tech)
+ */
+public class MonitoringPolicyPersistenceTest {
+ // Logger for this class
+ private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicyPersistenceTest.class);
+
+ private Gson gson;
+
+ private Connection connection;
+ private PfDao pfDao;
+
+ /**
+ * Set up the DAO towards the database.
+ *
+ * @throws Exception on database errors
+ */
+ @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");
+
+ pfDao = new PfDaoFactory().createPfDao(daoParameters);
+ pfDao.init(daoParameters);
+ }
+
+ /**
+ * Set up GSON.
+ */
+ @Before
+ public void setupGson() {
+ gson = new ToscaServiceTemplateMessageBodyHandler().getGson();
+ }
+
+ @After
+ public void teardown() throws Exception {
+ pfDao.close();
+ connection.close();
+ }
+
+ @Test
+ public void testJsonDeserialization() throws JsonSyntaxException, IOException {
+ ToscaServiceTemplate serviceTemplate =
+ gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"),
+ ToscaServiceTemplate.class);
+
+ assertNotNull(serviceTemplate);
+ LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString());
+ assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid());
+
+ ToscaPolicy policyBeforeDb = serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca");
+
+ pfDao.create(policyBeforeDb);
+
+ ToscaPolicy policyAfterDb = pfDao.get(ToscaPolicy.class, new PfConceptKey("onap.restart.tca:1.0.0"));
+
+ assertEquals(policyBeforeDb, policyAfterDb);
+ }
+}
--- /dev/null
+<?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=========================================================
+-->
+
+<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
+ <persistence-unit name="ToscaConceptTest" 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.ToscaPolicy</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.ToscaPolicy</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" />
+ <property name="eclipselink.logging.level.ddl" value="ALL" />
+ <property name="eclipselink.logging.level.connection" value="ALL" />
+ <property name="eclipselink.logging.level.sql" value="ALL" />
+ <property name="eclipselink.logging.level.transaction" value="ALL" />
+ <property name="eclipselink.logging.level.sequencing" value="ALL" />
+ <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>
// TODO: Check if this is the correct way to set the policy type version
toscaPolicy.setType(new PfConceptKey("SomeDerivedPolicyType", "1.0.0"));
- Map<String, Object> propertyMap = new HashMap<>();
+ Map<String, String> propertyMap = new HashMap<>();
toscaPolicy.setProperties(propertyMap);
toscaPolicy.getProperties().put("Content", legacyOperationalPolicy.getContent());
package org.onap.policy.models.tosca.simple.concepts;
-import com.google.gson.annotations.SerializedName;
-
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
-import javax.persistence.CascadeType;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
+import javax.persistence.ElementCollection;
import javax.persistence.EmbeddedId;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
-import javax.persistence.OneToMany;
import lombok.Data;
import lombok.EqualsAndHashCode;
* Class to represent the EntrySchema of list/map property in TOSCA definition.
*/
@MappedSuperclass
-@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Data
@EqualsAndHashCode(callSuper = false)
public class ToscaEntityType extends PfConcept {
@EmbeddedId
private PfConceptKey key;
- @SerializedName("derived_from")
- @Column(name = "derivedFrom")
+ // @formatter:off
+ @Column
+ @AttributeOverrides({
+ @AttributeOverride(name = "name",
+ column = @Column(name = "derived_from_name")),
+ @AttributeOverride(name = "version",
+ column = @Column(name = "derived_from_version"))
+ })
private PfConceptKey derivedFrom;
- @OneToMany(cascade = CascadeType.ALL)
+ @ElementCollection
private Map<String, String> metadata;
- @Column(name = "description")
+ @Column
private String description;
+ // @formatter:on
/**
* The Default Constructor creates a {@link ToscaEntityType} object with a null key.
import java.util.Map;
import java.util.Map.Entry;
+import javax.persistence.AttributeOverride;
+import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
public class ToscaPolicy extends ToscaEntityType {
private static final long serialVersionUID = 3265174757061982805L;
+ // @formatter:off
@Column
+ @AttributeOverrides({
+ @AttributeOverride(name = "name",
+ column = @Column(name = "type_name")),
+ @AttributeOverride(name = "version",
+ column = @Column(name = "type_version"))
+ })
private PfConceptKey type;
@ElementCollection
- private Map<String, Object> properties;
+ @Column(length = 10000)
+ private Map<String, String> properties;
@ElementCollection
private List<PfConceptKey> targets;
+ // @formatter:on
/**
* The Default Constructor creates a {@link ToscaPolicy} object with a null key.
private PfValidationResult validateProperties(@NonNull final PfValidationResult resultIn) {
PfValidationResult result = resultIn;
- for (Entry<String, Object> propertyEntry : properties.entrySet()) {
+ for (Entry<String, String> propertyEntry : properties.entrySet()) {
if (!ParameterValidationUtils.validateStringParameter(propertyEntry.getKey())) {
result.addValidationMessage(new PfValidationMessage(getKey(), this.getClass(), ValidationResult.INVALID,
"policy property key may not be null "));
JsonArray policiesJsonArray = new JsonArray();
for (ToscaPolicy policy: policies.getConceptMap().values()) {
- JsonElement policyEntry = new ToscaPolicyJsonAdapter().serialize(policy, type, context);
- policiesJsonArray.add(policyEntry);
+ policiesJsonArray.add(new ToscaPolicyJsonAdapter().serialize(policy, type, context));
}
return policiesJsonArray;
package org.onap.policy.models.tosca.simple.serialization;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
private static final String METADATA = "metadata";
private static final String PROPERTIES = "properties";
+ private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
+
@Override
public ToscaPolicy deserialize(@NonNull final JsonElement policyElement, @NonNull final Type type,
@NonNull final JsonDeserializationContext context) {
final JsonObject policyMetadataMapObject = policyJsonObject.get(METADATA).getAsJsonObject();
Map<String, String> policyMetadataMap = new HashMap<>();
for (Entry<String, JsonElement> entry : policyMetadataMapObject.entrySet()) {
- final String policyMetadataEntryKey = entry.getKey();
- final String policyMetadataEntryValue = entry.getValue().getAsString();
- policyMetadataMap.put(policyMetadataEntryKey, policyMetadataEntryValue);
+ policyMetadataMap.put(entry.getKey(), entry.getValue().getAsString());
}
policy.setMetadata(policyMetadataMap);
}
// Set properties
if (policyJsonObject.has(PROPERTIES)) {
final JsonObject policyPropertiesMapObject = policyJsonObject.get(PROPERTIES).getAsJsonObject();
- Map<String, Object> propertiesMap = new HashMap<>();
+ Map<String, String> propertiesMap = new HashMap<>();
for (Entry<String, JsonElement> entry : policyPropertiesMapObject.entrySet()) {
- final String policyPropertiesEntryKey = entry.getKey();
- final JsonElement policyPropertiesEntryValue = entry.getValue();
- propertiesMap.put(policyPropertiesEntryKey, policyPropertiesEntryValue);
+ // 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 serializing the property value into a string and storing it
+ // TODO: unvalidated into the database
+ propertiesMap.put(entry.getKey(), gson.toJson(entry.getValue()));
}
policy.setProperties(propertiesMap);
}
if (policy.getMetadata() != null) {
JsonObject metadataMapObject = new JsonObject();
for (Entry<String, String> entry : policy.getMetadata().entrySet()) {
- final String entryKey = entry.getKey();
- final String entryVal = entry.getValue();
- metadataMapObject.addProperty(entryKey, entryVal);
+ metadataMapObject.addProperty(entry.getKey(), entry.getValue());
}
policyValJsonObject.add(METADATA, metadataMapObject);
}
// Add properties
if (policy.getProperties() != null) {
JsonObject propertiesMapObject = new JsonObject();
- for (Entry<String, Object> entry : policy.getProperties().entrySet()) {
- final String entryKey = entry.getKey();
- JsonElement entryVal = null;
- if (entry.getValue() instanceof JsonElement) {
- entryVal = (JsonElement) entry.getValue();
- }
- propertiesMapObject.add(entryKey, entryVal);
+ for (Entry<String, String> entry : policy.getProperties().entrySet()) {
+ // TODO: This is the other direction of the HACK
+ JsonObject valueObject = gson.fromJson(entry.getValue(), JsonObject.class);
+ propertiesMapObject.add(entry.getKey(), valueObject);
}
policyValJsonObject.add(PROPERTIES, propertiesMapObject);
}
.registerTypeAdapter(ToscaTopologyTemplate.class, new ToscaTopologyTemplateJsonAdapter())
.registerTypeAdapter(ToscaPolicies.class, new ToscaPoliciesJsonAdapter())
.registerTypeAdapter(ToscaPolicy.class, new ToscaPolicyJsonAdapter())
+ .setPrettyPrinting()
.create()
);
// @formatter:on
PfConceptKey ptKey = new PfConceptKey("policyType", "0.0.1");
ToscaPolicy tp = new ToscaPolicy(tpKey, ptKey);
- Map<String, Object> propertyMap = new HashMap<>();
+ Map<String, String> propertyMap = new HashMap<>();
propertyMap.put("Property", "Property Value");
tp.setProperties(propertyMap);
assertEquals(propertyMap, tp.getProperties());
import static org.junit.Assert.assertTrue;
import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
assertEquals("onap.restart.tca:1.0.0",
serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca").getId());
+
+ String reserializedString = gson.toJson(serviceTemplate, ToscaServiceTemplate.class);
+ assertEquals(vcpePolicyJson.replaceAll("\\s+", ""), reserializedString.replaceAll("\\s+", ""));
+
+ ToscaServiceTemplate serviceTemplate2 = gson.fromJson(reserializedString, ToscaServiceTemplate.class);
+ assertNotNull(serviceTemplate2);
+ assertEquals(serviceTemplate, serviceTemplate2);
}
@Test
String vcpePolicyYaml = ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.yaml");
Object yamlObject = yaml.load(vcpePolicyYaml);
- String yamlAsJsonString = new Gson().toJson(yamlObject);
+ String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject);
ToscaServiceTemplate serviceTemplate = gson.fromJson(yamlAsJsonString, ToscaServiceTemplate.class);
assertEquals("onap.restart.tca:1.0.0",
serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca").getId());
+
+ String reserializedString = gson.toJson(serviceTemplate, ToscaServiceTemplate.class);
+ assertEquals(yamlAsJsonString.replaceAll("\\s+", ""), reserializedString.replaceAll("\\s+", ""));
+
+ ToscaServiceTemplate serviceTemplate2 = gson.fromJson(reserializedString, ToscaServiceTemplate.class);
+ assertNotNull(serviceTemplate2);
+ assertEquals(serviceTemplate, serviceTemplate2);
}
}