Alter PDP_UPDATE message to store lists of delpoyed/undeployed policies
[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-2020 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.models.tosca.simple.concepts;
25
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29 import javax.persistence.AttributeOverride;
30 import javax.persistence.AttributeOverrides;
31 import javax.persistence.Column;
32 import javax.persistence.ElementCollection;
33 import javax.persistence.Entity;
34 import javax.persistence.Inheritance;
35 import javax.persistence.InheritanceType;
36 import javax.persistence.Lob;
37 import javax.persistence.Table;
38 import javax.ws.rs.core.Response;
39 import lombok.Data;
40 import lombok.EqualsAndHashCode;
41 import lombok.NonNull;
42 import org.onap.policy.common.parameters.BeanValidationResult;
43 import org.onap.policy.common.parameters.annotations.NotBlank;
44 import org.onap.policy.common.parameters.annotations.NotNull;
45 import org.onap.policy.common.parameters.annotations.Valid;
46 import org.onap.policy.common.utils.coder.CoderException;
47 import org.onap.policy.common.utils.coder.StandardCoder;
48 import org.onap.policy.models.base.PfAuthorative;
49 import org.onap.policy.models.base.PfConcept;
50 import org.onap.policy.models.base.PfConceptKey;
51 import org.onap.policy.models.base.PfKey;
52 import org.onap.policy.models.base.PfModelRuntimeException;
53 import org.onap.policy.models.base.PfUtils;
54 import org.onap.policy.models.base.validation.annotations.VerifyKey;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
56
57 /**
58  * Class to represent the policy in TOSCA definition.
59  *
60  * @author Chenfei Gao (cgao@research.att.com)
61  * @author Liam Fallon (liam.fallon@est.tech)
62  */
63 @Entity
64 @Table(name = "ToscaPolicy")
65 @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
66 @Data
67 @EqualsAndHashCode(callSuper = true)
68 public class JpaToscaPolicy extends JpaToscaEntityType<ToscaPolicy> implements PfAuthorative<ToscaPolicy> {
69     private static final long serialVersionUID = 3265174757061982805L;
70
71     // Tags for metadata
72     private static final String METADATA_POLICY_ID_TAG = "policy-id";
73     private static final String METADATA_POLICY_VERSION_TAG = "policy-version";
74
75     private static final StandardCoder STANDARD_CODER = new StandardCoder();
76
77     // @formatter:off
78     @Column
79     @AttributeOverrides({
80         @AttributeOverride(name = "name",
81                            column = @Column(name = "type_name")),
82         @AttributeOverride(name = "version",
83                            column = @Column(name = "type_version"))
84         })
85     @VerifyKey
86     @NotNull
87     private PfConceptKey type;
88
89     @ElementCollection
90     @Lob
91     private Map<@NotNull @NotBlank String, @NotNull String> properties;
92
93     @ElementCollection
94     private List<@NotNull @Valid PfConceptKey> targets;
95     // @formatter:on
96
97     /**
98      * The Default Constructor creates a {@link JpaToscaPolicy} object with a null key.
99      */
100     public JpaToscaPolicy() {
101         this(new PfConceptKey());
102     }
103
104     /**
105      * The Key Constructor creates a {@link JpaToscaPolicy} object with the given concept key.
106      *
107      * @param key the key
108      */
109     public JpaToscaPolicy(@NonNull final PfConceptKey key) {
110         this(key, new PfConceptKey());
111     }
112
113     /**
114      * The full Constructor creates a {@link JpaToscaPolicy} object with all mandatory fields.
115      *
116      * @param key the key
117      * @param type the type of the policy
118      */
119     public JpaToscaPolicy(@NonNull final PfConceptKey key, @NonNull final PfConceptKey type) {
120         super(key);
121         this.type = type;
122     }
123
124     /**
125      * Copy constructor.
126      *
127      * @param copyConcept the concept to copy from
128      */
129     public JpaToscaPolicy(@NonNull final JpaToscaPolicy copyConcept) {
130         super(copyConcept);
131         this.type = new PfConceptKey(copyConcept.type);
132         this.properties = (copyConcept.properties != null ? new LinkedHashMap<>(copyConcept.properties) : null);
133         this.targets = PfUtils.mapList(copyConcept.targets, PfConceptKey::new);
134     }
135
136     /**
137      * Authorative constructor.
138      *
139      * @param authorativeConcept the authorative concept to copy from
140      */
141     public JpaToscaPolicy(final ToscaPolicy authorativeConcept) {
142         super(new PfConceptKey());
143         type = new PfConceptKey();
144         this.fromAuthorative(authorativeConcept);
145     }
146
147     @Override
148     public ToscaPolicy toAuthorative() {
149         ToscaPolicy toscaPolicy = new ToscaPolicy();
150         super.setToscaEntity(toscaPolicy);
151         super.toAuthorative();
152
153         toscaPolicy.setType(type.getName());
154
155         if (!PfKey.NULL_KEY_VERSION.equals(type.getVersion())) {
156             toscaPolicy.setTypeVersion(type.getVersion());
157         } else {
158             toscaPolicy.setTypeVersion(null);
159         }
160
161         toscaPolicy.setProperties(PfUtils.mapMap(properties, property -> {
162             try {
163                 return STANDARD_CODER.decode(property, Object.class);
164             } catch (CoderException ce) {
165                 String errorMessage = "error decoding property JSON value read from database: " + property;
166                 throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce);
167             }
168         }));
169
170         return toscaPolicy;
171     }
172
173     @Override
174     public void fromAuthorative(@NonNull final ToscaPolicy toscaPolicy) {
175         super.fromAuthorative(toscaPolicy);
176
177         if (toscaPolicy.getType() != null) {
178             type.setName(toscaPolicy.getType());
179         } else {
180             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
181                     "PolicyType type not specified, the type of the PolicyType for this policy must be specified in "
182                             + "the type field");
183         }
184
185         if (toscaPolicy.getTypeVersion() != null) {
186             type.setVersion(toscaPolicy.getTypeVersion());
187         } else {
188             throw new PfModelRuntimeException(Response.Status.BAD_REQUEST,
189                     "PolicyType version not specified, the version of the PolicyType for this policy must be specified"
190                             + " in the type_version field");
191         }
192
193         properties = PfUtils.mapMap(toscaPolicy.getProperties(), property -> {
194             try {
195                 return STANDARD_CODER.encode(property);
196             } catch (CoderException ce) {
197                 String errorMessage = "error encoding property JSON value for database: " + property;
198                 throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce);
199             }
200         });
201
202         // Add the property metadata if it doesn't exist already
203         if (toscaPolicy.getMetadata() == null) {
204             setMetadata(new LinkedHashMap<>());
205         }
206
207         // Add the policy name and version fields to the metadata
208         getMetadata().put(METADATA_POLICY_ID_TAG, getKey().getName());
209         getMetadata().put(METADATA_POLICY_VERSION_TAG, getKey().getVersion());
210     }
211
212     @Override
213     public List<PfKey> getKeys() {
214         final List<PfKey> keyList = super.getKeys();
215
216         keyList.addAll(type.getKeys());
217
218         if (targets != null) {
219             keyList.addAll(targets);
220         }
221
222         return keyList;
223     }
224
225     @Override
226     public void clean() {
227         super.clean();
228
229         type.clean();
230
231         if (targets != null) {
232             for (PfConceptKey target : targets) {
233                 target.clean();
234             }
235         }
236     }
237
238     @Override
239     public BeanValidationResult validate(String fieldName) {
240         BeanValidationResult result = super.validate(fieldName);
241
242         validateKeyVersionNotNull(result, "key", getKey());
243
244         return result;
245     }
246
247     @Override
248     public int compareTo(final PfConcept otherConcept) {
249         if (otherConcept == null) {
250             return -1;
251         }
252
253         if (this == otherConcept) {
254             return 0;
255         }
256
257         if (getClass() != otherConcept.getClass()) {
258             return getClass().getName().compareTo(otherConcept.getClass().getName());
259         }
260
261         final JpaToscaPolicy other = (JpaToscaPolicy) otherConcept;
262         int result = super.compareTo(other);
263         if (result != 0) {
264             return result;
265         }
266
267         result = type.compareTo(other.type);
268         if (result != 0) {
269             return result;
270         }
271
272         result = PfUtils.compareMaps(properties, other.properties);
273         if (result != 0) {
274             return result;
275         }
276
277         return PfUtils.compareCollections(targets, other.targets);
278     }
279 }