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