aboutsummaryrefslogtreecommitdiffstats
path: root/model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxModel.java
blob: ce52b147f9a5e33c3d256f38fb48a533757b5330 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2019-2022 Nordix Foundation.
 *  Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.model.basicmodel.concepts;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.common.utils.validation.Assertions;

/**
 * This class is the base class for all models in Apex. All model classes inherit from this model so all models must
 * have a key and have key information.
 *
 * <p>Validation checks that the model key is valid. It goes on to check for null keys and checks each key for
 * uniqueness in the model. A check is carried out to ensure that an {@link AxKeyInfo} instance exists for every
 * {@link AxArtifactKey} key. For each {@link AxReferenceKey} instance, a check is made that its parent and local name
 * are nut null and that a {@link AxKeyInfo} entry exists for its parent. Then a check is made that each used
 * {@link AxArtifactKey} and {@link AxReferenceKey} usage references a key that exists. Finally, a check is made to
 * ensure that an {@link AxArtifactKey} instance exists for every {@link AxKeyInfo} instance.
 */
public class AxModel extends AxConcept {
    private static final String IS_A_NULL_KEY = " is a null key";

    private static final long serialVersionUID = -771659065637205430L;

    private AxArtifactKey key;
    private AxKeyInformation keyInformation;

    /**
     * The Default Constructor creates this concept with a NULL artifact key.
     */
    public AxModel() {
        this(new AxArtifactKey());
    }

    /**
     * Copy constructor.
     *
     * @param copyConcept the concept to copy from
     */
    public AxModel(final AxModel copyConcept) {
        super(copyConcept);
    }

    /**
     * Constructor to create this concept with the specified key.
     *
     * @param key the key of this concept
     */
    public AxModel(final AxArtifactKey key) {
        this(key, new AxKeyInformation(new AxArtifactKey(key.getName() + "_KeyInfo", key.getVersion())));
    }

    /**
     * Constructor to create this concept and set all its fields.
     *
     * @param key the key of this concept
     * @param keyInformation the key information of this concept
     */
    public AxModel(final AxArtifactKey key, final AxKeyInformation keyInformation) {
        super();
        Assertions.argumentNotNull(key, "key may not be null");
        Assertions.argumentNotNull(keyInformation, "keyInformation may not be null");

        this.key = key;
        this.keyInformation = keyInformation;
    }

    /**
     * Registers this model with the {@link ModelService}. All models are registered with the model service so that
     * models can be references from anywhere in the Apex system without being passed as references through deep call
     * chains.
     */
    public void register() {
        ModelService.registerModel(AxKeyInformation.class, getKeyInformation());
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public AxArtifactKey getKey() {
        return key;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public List<AxKey> getKeys() {
        final List<AxKey> keyList = key.getKeys();

        // We just add the key for the KeyInformation itself. We don't add the
        // keys from key information because
        // that is a list of key information for existing keys
        keyList.add(keyInformation.getKey());

        return keyList;
    }

    /**
     * Sets the key of this concept.
     *
     * @param key the key of this concept
     */
    public void setKey(final AxArtifactKey key) {
        Assertions.argumentNotNull(key, "key may not be null");
        this.key = key;
    }

    /**
     * Gets the key information of this concept.
     *
     * @return the key information of this concept
     */
    public AxKeyInformation getKeyInformation() {
        return keyInformation;
    }

    /**
     * Sets the key information of this concept.
     *
     * @param keyInformation the key information of this concept
     */
    public void setKeyInformation(final AxKeyInformation keyInformation) {
        Assertions.argumentNotNull(keyInformation, "keyInformation may not be null");
        this.keyInformation = keyInformation;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public AxValidationResult validate(final AxValidationResult resultIn) {
        AxValidationResult result = resultIn;

        if (key.equals(AxArtifactKey.getNullKey())) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key is a null key"));
        }

        result = key.validate(result);
        result = keyInformation.validate(result);

        // Key consistency check
        final Set<AxArtifactKey> artifactKeySet = new TreeSet<>();
        final Set<AxReferenceKey> referenceKeySet = new TreeSet<>();
        final Set<AxKeyUse> usedKeySet = new TreeSet<>();

        for (final AxKey axKey : this.getKeys()) {
            // Check for the two type of keys we have
            if (axKey instanceof AxArtifactKey) {
                result = validateArtifactKeyInModel((AxArtifactKey) axKey, artifactKeySet, result);
            } else if (axKey instanceof AxReferenceKey) {
                result = validateReferenceKeyInModel((AxReferenceKey) axKey, referenceKeySet, result);
            } else {
                // It must be an AxKeyUse, nothing else is legal
                usedKeySet.add((AxKeyUse) axKey);
            }
        }

        // Check all reference keys have correct parent keys
        for (final AxReferenceKey referenceKey : referenceKeySet) {
            if (!artifactKeySet.contains(referenceKey.getParentArtifactKey())) {
                result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                                "parent artifact key not found for reference key " + referenceKey));
            }
        }

        result = validateKeyUses(usedKeySet, artifactKeySet, referenceKeySet, result);

        // Check key information for unused key information
        for (final AxArtifactKey keyInfoKey : keyInformation.getKeyInfoMap().keySet()) {
            if (!artifactKeySet.contains(keyInfoKey)) {
                result.addValidationMessage(new AxValidationMessage(keyInfoKey, this.getClass(),
                                ValidationResult.WARNING, "key not found for key information entry"));
            }
        }

        return result;
    }

    /**
     * Check for consistent usage of an artifact key in the model.
     *
     * @param artifactKey The artifact key to check
     * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to the set
     * @param result The validation result to append to
     * @return the result of the validation
     */
    private AxValidationResult validateArtifactKeyInModel(final AxArtifactKey artifactKey,
                    final Set<AxArtifactKey> artifactKeySet, final AxValidationResult result) {
        // Null key check
        if (artifactKey.equals(AxArtifactKey.getNullKey())) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key " + artifactKey + IS_A_NULL_KEY));
        }

        // Null key name start check
        if (artifactKey.getName().toUpperCase().startsWith(AxKey.NULL_KEY_NAME)) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key " + artifactKey + " name starts with keyword " + AxKey.NULL_KEY_NAME));
        }

        // Unique key check
        if (artifactKeySet.contains(artifactKey)) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "duplicate key " + artifactKey + " found"));
        } else {
            artifactKeySet.add(artifactKey);
        }

        // Key information check
        if (!keyInformation.getKeyInfoMap().containsKey(artifactKey)) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key information not found for key " + artifactKey));
        }

        return result;
    }

    /**
     * Check for consistent usage of a reference key in the model.
     *
     * @param referenceKey The reference key to check
     * @param referenceKeySet The set of reference keys encountered so far, this key is appended to the set
     * @param result The validation result to append to
     * @return the result of the validation
     */
    private AxValidationResult validateReferenceKeyInModel(final AxReferenceKey referenceKey,
                    final Set<AxReferenceKey> referenceKeySet, final AxValidationResult result) {
        // Null key check
        if (referenceKey.equals(AxReferenceKey.getNullKey())) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key " + referenceKey + IS_A_NULL_KEY));
        }

        // Null parent key check
        if (referenceKey.getParentArtifactKey().equals(AxArtifactKey.getNullKey())) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "parent artifact key of key " + referenceKey + IS_A_NULL_KEY));
        }

        // Null local name check
        if (referenceKey.getLocalName().equals(AxKey.NULL_KEY_NAME)) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key " + referenceKey + " has a null local name"));
        }

        // Null key name start check
        if (referenceKey.getParentArtifactKey().getName().toUpperCase().startsWith(AxKey.NULL_KEY_NAME)) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key " + referenceKey + " parent name starts with keyword " + AxKey.NULL_KEY_NAME));
        }

        // Unique key check
        if (referenceKeySet.contains(referenceKey)) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "duplicate key " + referenceKey + " found"));
        } else {
            referenceKeySet.add(referenceKey);
        }

        // Key information check
        if (!keyInformation.getKeyInfoMap().containsKey(referenceKey.getParentArtifactKey())) {
            result.addValidationMessage(new AxValidationMessage(key, this.getClass(), ValidationResult.INVALID,
                            "key information not found for parent key of key " + referenceKey));
        }

        return result;
    }

    /**
     * Check for consistent usage of cross-key references in the model.
     *
     * @param usedKeySet The set of all keys used in the model
     * @param artifactKeySet The set of artifact keys encountered so far, this key is appended to the set
     * @param referenceKeySet The set of reference keys encountered so far, this key is appended to the set
     * @param result The validation result to append to
     * @return the result of the validation
     */
    private AxValidationResult validateKeyUses(final Set<AxKeyUse> usedKeySet, final Set<AxArtifactKey> artifactKeySet,
                    final Set<AxReferenceKey> referenceKeySet, final AxValidationResult result) {
        // Check all key uses
        for (final AxKeyUse usedKey : usedKeySet) {
            if (usedKey.getKey() instanceof AxArtifactKey) {
                // AxArtifact key usage, check the key exists
                if (!artifactKeySet.contains(usedKey.getKey())) {
                    result.addValidationMessage(new AxValidationMessage(usedKey.getKey(), this.getClass(),
                                    ValidationResult.INVALID, "an artifact key used in the model is not defined"));
                }
            } else {
                // AxReference key usage, check the key exists
                if (!referenceKeySet.contains(usedKey.getKey())) {
                    result.addValidationMessage(new AxValidationMessage(usedKey.getKey(), this.getClass(),
                                    ValidationResult.INVALID, "a reference key used in the model is not defined"));
                }
            }
        }

        return result;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void clean() {
        key.clean();
        keyInformation.clean();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public String toString() {
        final var builder = new StringBuilder();
        builder.append(this.getClass().getSimpleName());
        builder.append(":(");
        builder.append("key=");
        builder.append(key);
        builder.append(",keyInformation=");
        builder.append(keyInformation);
        builder.append(")");
        return builder.toString();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public AxConcept copyTo(final AxConcept target) {
        Assertions.argumentNotNull(target, "target may not be null");

        final Object copyObject = target;
        Assertions.instanceOf(copyObject, AxModel.class);

        final AxModel copy = ((AxModel) copyObject);
        copy.setKey(new AxArtifactKey(key));
        copy.setKeyInformation(new AxKeyInformation(keyInformation));

        return copy;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public int hashCode() {
        final var prime = 31;
        var result = 1;
        result = prime * result + key.hashCode();
        result = prime * result + keyInformation.hashCode();
        return result;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }

        final AxModel other = (AxModel) obj;
        if (!key.equals(other.key)) {
            return false;
        }
        return keyInformation.equals(other.keyInformation);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public int compareTo(final AxConcept otherObj) {
        if (otherObj == null) {
            return -1;
        }
        if (this == otherObj) {
            return 0;
        }
        if (getClass() != otherObj.getClass()) {
            return this.hashCode() - otherObj.hashCode();
        }

        final AxModel other = (AxModel) otherObj;
        if (!key.equals(other.key)) {
            return key.compareTo(other.key);
        }
        return keyInformation.compareTo(other.keyInformation);
    }
}