Fix metadataSet serialization for db persistence and retrieval.
[policy/models.git] / models-tosca / src / main / java / org / onap / policy / models / tosca / simple / concepts / JpaToscaPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Model
4  * ================================================================================
5  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019-2021 Nordix Foundation.
7  * Modifications Copyright (C) 2022 Bell Canada. All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * SPDX-License-Identifier: Apache-2.0
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.policy.models.tosca.simple.concepts;
26
27 import java.util.LinkedHashMap;
28 import java.util.List;
29 import javax.persistence.CollectionTable;
30 import javax.persistence.ElementCollection;
31 import javax.persistence.Entity;
32 import javax.persistence.Inheritance;
33 import javax.persistence.InheritanceType;
34 import javax.persistence.JoinColumn;
35 import javax.persistence.Table;
36 import javax.ws.rs.core.Response;
37 import lombok.Data;
38 import lombok.EqualsAndHashCode;
39 import lombok.NonNull;
40 import org.onap.policy.common.parameters.BeanValidationResult;
41 import org.onap.policy.common.parameters.annotations.NotNull;
42 import org.onap.policy.common.parameters.annotations.Valid;
43 import org.onap.policy.common.utils.coder.CoderException;
44 import org.onap.policy.common.utils.coder.StandardCoder;
45 import org.onap.policy.models.base.PfConcept;
46 import org.onap.policy.models.base.PfConceptKey;
47 import org.onap.policy.models.base.PfKey;
48 import org.onap.policy.models.base.PfModelRuntimeException;
49 import org.onap.policy.models.base.PfUtils;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
51
52 /**
53  * Class to represent the policy in TOSCA definition.
54  *
55  * @author Chenfei Gao (cgao@research.att.com)
56  * @author Liam Fallon (liam.fallon@est.tech)
57  */
58 @Entity
59 @Table(name = "ToscaPolicy")
60 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
61 @Data
62 @EqualsAndHashCode(callSuper = true)
63 public class JpaToscaPolicy extends JpaToscaWithTypeAndStringProperties<ToscaPolicy> {
64     private static final long serialVersionUID = 3265174757061982805L;
65     private static final String METADATA_METADATA_SET_NAME_TAG = "metadataSetName";
66     private static final String METADATA_METADATA_SET_VERSION_TAG = "metadataSetVersion";
67
68     // Tags for metadata
69     private static final String METADATA_POLICY_ID_TAG = "policy-id";
70     private static final String METADATA_POLICY_VERSION_TAG = "policy-version";
71
72     private static final StandardCoder STANDARD_CODER = new StandardCoder();
73
74     @ElementCollection
75     @CollectionTable(joinColumns = {
76         @JoinColumn(name = "toscaPolicyName",    referencedColumnName = "name"),
77         @JoinColumn(name = "toscaPolicyVersion",    referencedColumnName = "version")
78     })
79     private List<@NotNull @Valid PfConceptKey> targets;
80
81     /**
82      * The Default Constructor creates a {@link JpaToscaPolicy} object with a null key.
83      */
84     public JpaToscaPolicy() {
85         super();
86     }
87
88     /**
89      * The Key Constructor creates a {@link JpaToscaPolicy} object with the given concept key.
90      *
91      * @param key the key
92      */
93     public JpaToscaPolicy(@NonNull final PfConceptKey key) {
94         super(key, new PfConceptKey());
95     }
96
97     /**
98      * The full Constructor creates a {@link JpaToscaPolicy} object with all mandatory fields.
99      *
100      * @param key the key
101      * @param type the type of the policy
102      */
103     public JpaToscaPolicy(@NonNull final PfConceptKey key, @NonNull final PfConceptKey type) {
104         super(key, type);
105     }
106
107     /**
108      * Copy constructor.
109      *
110      * @param copyConcept the concept to copy from
111      */
112     public JpaToscaPolicy(@NonNull final JpaToscaPolicy copyConcept) {
113         super(copyConcept);
114         this.targets = PfUtils.mapList(copyConcept.targets, PfConceptKey::new);
115     }
116
117     /**
118      * Authorative constructor.
119      *
120      * @param authorativeConcept the authorative concept to copy from
121      */
122     public JpaToscaPolicy(final ToscaPolicy authorativeConcept) {
123         super(new PfConceptKey());
124         this.fromAuthorative(authorativeConcept);
125     }
126
127     @Override
128     public ToscaPolicy toAuthorative() {
129         var toscaPolicy = new ToscaPolicy();
130         super.setToscaEntity(toscaPolicy);
131         super.toAuthorative();
132
133         return toscaPolicy;
134     }
135
136     @Override
137     public void fromAuthorative(@NonNull final ToscaPolicy toscaPolicy) {
138         super.fromAuthorative(toscaPolicy);
139
140         // Add the property metadata if it doesn't exist already
141         if (toscaPolicy.getMetadata() == null) {
142             setMetadata(new LinkedHashMap<>());
143         }
144
145         // Add the policy name and version fields to the metadata
146         getMetadata().put(METADATA_POLICY_ID_TAG, getKey().getName());
147         getMetadata().put(METADATA_POLICY_VERSION_TAG, getKey().getVersion());
148
149         // Add metadataSet name and version to the metadata
150         if (getMetadata().containsKey(METADATA_METADATA_SET_NAME_TAG)
151                 && getMetadata().containsKey(METADATA_METADATA_SET_VERSION_TAG)) {
152             getMetadata().put(METADATA_METADATA_SET_NAME_TAG, getMetadata().get(METADATA_METADATA_SET_NAME_TAG)
153                     .replaceAll("^\"|\"$", ""));
154
155             getMetadata().put(METADATA_METADATA_SET_VERSION_TAG, getMetadata().get(METADATA_METADATA_SET_VERSION_TAG)
156                     .replaceAll("^\"|\"$", ""));
157         }
158     }
159
160     @Override
161     protected Object deserializePropertyValue(String propValue) {
162         try {
163             return STANDARD_CODER.decode(propValue, Object.class);
164         } catch (CoderException ce) {
165             String errorMessage = "error decoding property JSON value read from database: " + propValue;
166             throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce);
167         }
168     }
169
170     @Override
171     protected String serializePropertyValue(Object propValue) {
172         try {
173             return STANDARD_CODER.encode(propValue);
174         } catch (CoderException ce) {
175             String errorMessage = "error encoding property JSON value for database: " + propValue;
176             throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce);
177         }
178     }
179
180     @Override
181     public List<PfKey> getKeys() {
182         final List<PfKey> keyList = super.getKeys();
183
184         if (targets != null) {
185             keyList.addAll(targets);
186         }
187
188         return keyList;
189     }
190
191     @Override
192     public void clean() {
193         super.clean();
194
195         if (targets != null) {
196             for (PfConceptKey target : targets) {
197                 target.clean();
198             }
199         }
200     }
201
202     @Override
203     public BeanValidationResult validate(String fieldName) {
204         BeanValidationResult result = super.validate(fieldName);
205
206         validateKeyVersionNotNull(result, "key", getKey());
207
208         return result;
209     }
210
211     @Override
212     public int compareTo(final PfConcept otherConcept) {
213         if (this == otherConcept) {
214             return 0;
215         }
216
217         int result = super.compareTo(otherConcept);
218         if (result != 0) {
219             return result;
220         }
221
222         final JpaToscaPolicy other = (JpaToscaPolicy) otherConcept;
223
224         return PfUtils.compareCollections(targets, other.targets);
225     }
226 }