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