b9acde26cc47762c57877bbcc4a85618958591cd
[policy/models.git] / models-tosca / src / main / java / org / onap / policy / models / tosca / simple / concepts / JpaToscaEntityType.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019-2020,2022-2023 Nordix Foundation.
4  *  Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.models.tosca.simple.concepts;
23
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.TreeMap;
28 import javax.persistence.AttributeOverride;
29 import javax.persistence.AttributeOverrides;
30 import javax.persistence.Column;
31 import javax.persistence.ElementCollection;
32 import javax.persistence.EmbeddedId;
33 import javax.persistence.Lob;
34 import javax.persistence.MappedSuperclass;
35 import javax.ws.rs.core.Response;
36 import lombok.Data;
37 import lombok.EqualsAndHashCode;
38 import lombok.NonNull;
39 import org.apache.commons.lang3.ObjectUtils;
40 import org.onap.policy.common.parameters.annotations.NotBlank;
41 import org.onap.policy.common.parameters.annotations.NotNull;
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.PfAuthorative;
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.base.validation.annotations.VerifyKey;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;
52
53 /**
54  * Class to represent the EntrySchema of list/map property in TOSCA definition.
55  */
56 @MappedSuperclass
57 @Data
58 @EqualsAndHashCode(callSuper = false)
59 public class JpaToscaEntityType<T extends ToscaEntity> extends PfConcept implements PfAuthorative<T> {
60     private static final long serialVersionUID = -1330661834220739393L;
61
62     private static final StandardCoder STANDARD_CODER = new StandardCoder();
63
64     @EmbeddedId
65     @VerifyKey
66     @NotNull
67     private PfConceptKey key;
68
69     // @formatter:off
70     @Column
71     @AttributeOverrides({
72         @AttributeOverride(name = "name", column = @Column(name = "derived_from_name")),
73         @AttributeOverride(name = "version", column = @Column(name = "derived_from_version"))
74     })
75     @VerifyKey
76     private PfConceptKey derivedFrom;
77
78     @ElementCollection
79     @Lob
80     private Map<@NotNull @NotBlank String, @NotNull @NotBlank String> metadata;
81
82     @Column
83     @NotBlank
84     private String description;
85
86     private transient T toscaEntity;
87     // @formatter:on
88
89     /**
90      * The Default Constructor creates a {@link JpaToscaEntityType} object with a null key.
91      */
92     public JpaToscaEntityType() {
93         this(new PfConceptKey());
94     }
95
96     /**
97      * The Key Constructor creates a {@link JpaToscaEntityType} object with the given concept key.
98      *
99      * @param key the key
100      */
101     public JpaToscaEntityType(@NonNull final PfConceptKey key) {
102         this.key = key;
103     }
104
105     /**
106      * Copy constructor.
107      *
108      * @param copyConcept the concept to copy from
109      */
110     public JpaToscaEntityType(final JpaToscaEntityType<T> copyConcept) {
111         super(copyConcept);
112         this.key = new PfConceptKey(copyConcept.key);
113         this.derivedFrom = (copyConcept.derivedFrom != null ? new PfConceptKey(copyConcept.derivedFrom) : null);
114         this.metadata = (copyConcept.metadata != null ? new TreeMap<>(copyConcept.metadata) : null);
115         this.description = copyConcept.description;
116     }
117
118     /**
119      * Authorative constructor.
120      *
121      * @param authorativeConcept the authorative concept to copy from
122      */
123     public JpaToscaEntityType(final T authorativeConcept) {
124         this.fromAuthorative(authorativeConcept);
125     }
126
127     @Override
128     public T toAuthorative() {
129         toscaEntity.setName(getKey().getName());
130         toscaEntity.setVersion(getKey().getVersion());
131
132         if (derivedFrom != null) {
133             toscaEntity.setDerivedFrom(derivedFrom.getName());
134         }
135
136         if (description != null) {
137             toscaEntity.setDescription(description);
138         }
139
140         toscaEntity.setMetadata(PfUtils.mapMap(metadata, this::deserializeMetadataValue));
141
142         return toscaEntity;
143     }
144
145     @Override
146     public void fromAuthorative(T toscaEntity) {
147         key = new PfConceptKey();
148
149         if (toscaEntity.getName() != null) {
150             key.setName(toscaEntity.getName());
151         }
152
153         if (toscaEntity.getVersion() != null) {
154             key.setVersion(toscaEntity.getVersion());
155         }
156
157         if (toscaEntity.getDerivedFrom() != null) {
158             // Check if the derived from field contains a name-version ID
159             if (toscaEntity.getDerivedFrom().contains(":")) {
160                 derivedFrom = new PfConceptKey(toscaEntity.getDerivedFrom());
161             } else {
162                 derivedFrom = new PfConceptKey(toscaEntity.getDerivedFrom(), PfKey.NULL_KEY_VERSION);
163             }
164         }
165
166         if (toscaEntity.getDescription() != null) {
167             description = toscaEntity.getDescription();
168         }
169
170         metadata = PfUtils.mapMap(toscaEntity.getMetadata(), this::serializeMetadataValue);
171     }
172
173     @Override
174     public List<PfKey> getKeys() {
175         final List<PfKey> keyList = getKey().getKeys();
176         if (derivedFrom != null) {
177             keyList.addAll(derivedFrom.getKeys());
178         }
179         return keyList;
180     }
181
182     @Override
183     public void clean() {
184         key.clean();
185
186         if (derivedFrom != null) {
187             derivedFrom.clean();
188         }
189
190         if (metadata != null) {
191             for (Entry<String, String> metadataEntry : metadata.entrySet()) {
192                 metadataEntry.setValue(metadataEntry.getValue().trim());
193             }
194         }
195
196         description = (description != null ? description.trim() : null);
197     }
198
199     @Override
200     public int compareTo(final PfConcept otherConcept) {
201         if (otherConcept == null) {
202             return -1;
203         }
204         if (this == otherConcept) {
205             return 0;
206         }
207         if (getClass() != otherConcept.getClass()) {
208             return getClass().getName().compareTo(otherConcept.getClass().getName());
209         }
210
211         @SuppressWarnings("unchecked")
212         final JpaToscaEntityType<T> other = (JpaToscaEntityType<T>) otherConcept;
213
214         int result = key.compareTo(other.key);
215         if (result != 0) {
216             return result;
217         }
218
219         result = ObjectUtils.compare(derivedFrom, other.derivedFrom);
220         if (result != 0) {
221             return result;
222         }
223
224         result = PfUtils.compareMaps(metadata, other.metadata);
225         if (result != 0) {
226             return result;
227         }
228
229         return ObjectUtils.compare(description, other.description);
230     }
231
232     protected Object deserializeMetadataValue(String metadataValue) {
233         try {
234             return STANDARD_CODER.decode(metadataValue, Object.class);
235         } catch (CoderException ce) {
236             String errorMessage = "error decoding metadata JSON value read from database: " + metadataValue;
237             throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce);
238         }
239     }
240
241     protected String serializeMetadataValue(Object metadataValue) {
242         try {
243             return STANDARD_CODER.encode(metadataValue);
244         } catch (CoderException ce) {
245             String errorMessage = "error encoding metadata JSON value for database: " + metadataValue;
246             throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage, ce);
247         }
248     }
249 }