aboutsummaryrefslogtreecommitdiffstats
path: root/models/src/main/java/org/onap/policy/clamp/models/acm/document/base/DocUtil.java
blob: 143ee233ab4841098e116605ac18a006c1930c40 (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2022 Nordix Foundation.
 * ================================================================================
 * 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.clamp.models.acm.document.base;

import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.function.Function;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.onap.policy.clamp.models.acm.document.concepts.DocToscaEntity;
import org.onap.policy.clamp.models.acm.document.concepts.DocToscaServiceTemplate;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfKey;
import org.onap.policy.models.base.PfModelRuntimeException;
import org.onap.policy.models.base.PfNameVersion;
import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DocUtil {

    public static final String REF_DATA_TYPES = "dataTypes";
    public static final String REF_POLICY_TYPES = "policyTypes";
    public static final String REF_NODE_TYPES = "nodeTypes";
    public static final String REF_CAPABILITY_TYPES = "capabilityTypes";
    public static final String REF_RELATIONSHIP_TYPES = "relationshipTypes";
    public static final String REF_NODE_TEMPLATES = "nodeTemplates";
    public static final String REF_POLICIES = "policies";
    public static final String REF_REQUIREMENTS = "requirements";
    public static final String REF_CAPABILITIES = "capabilities";

    /**
     * Convenience method to apply a mapping function to all of the values of a map, generating a new map.
     *
     * @param source map whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @return a new map, containing mappings of all of the items in the original map
     */
    public static <A extends PfNameVersion, R> Map<String, R> docMapToMap(Map<String, A> source,
            Function<A, R> mapFunc) {
        return docMapToMap(source, mapFunc, null);
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a map, generating a new map.
     *
     * @param source map whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @param defaultValue if source is null
     * @return a new map, containing mappings of all of the items in the original map
     */
    public static <A extends PfNameVersion, R> Map<String, R> docMapToMap(Map<String, A> source, Function<A, R> mapFunc,
            Map<String, R> defaultValue) {
        if (source == null) {
            return defaultValue;
        }
        Map<String, R> map = new LinkedHashMap<>();
        for (Entry<String, A> ent : source.entrySet()) {
            map.put(ent.getValue().getName(), mapFunc.apply(ent.getValue()));
        }

        return map;
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a map, generating a new map.
     *
     * @param source map whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @return a new map, containing mappings of all of the items in the original map, or {@code null} if the source is
     *         {@code null}
     */
    public static <A extends ToscaEntity, R> Map<String, R> mapToDocMap(Map<String, A> source, Function<A, R> mapFunc) {
        return mapToDocMap(source, mapFunc, null);
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a map, generating a new map.
     *
     * @param source map whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @param defaultValue if source is null
     * @return a new map, containing mappings of all of the items in the original map, or defaultValue if the source is
     *         {@code null}
     */
    public static <A extends ToscaEntity, R> Map<String, R> mapToDocMap(Map<String, A> source, Function<A, R> mapFunc,
            Map<String, R> defaultValue) {
        if (source == null) {
            return defaultValue;
        }
        Map<String, R> conceptMap = new LinkedHashMap<>();

        for (var incomingConceptEntry : source.entrySet()) {

            var conceptKey = new PfConceptKey();
            conceptKey.setName(incomingConceptEntry.getKey());
            if (incomingConceptEntry.getValue().getVersion() != null) {
                conceptKey.setVersion(incomingConceptEntry.getValue().getVersion());
            }

            incomingConceptEntry.getValue().setName(findConceptField(conceptKey, conceptKey.getName(),
                    incomingConceptEntry.getValue(), PfNameVersion::getDefinedName));
            incomingConceptEntry.getValue().setVersion(findConceptField(conceptKey, conceptKey.getVersion(),
                    incomingConceptEntry.getValue(), PfNameVersion::getDefinedVersion));

            var authoritiveImpl = mapFunc.apply(incomingConceptEntry.getValue());

            // After all that, save the map entry
            conceptMap.put(conceptKey.getId(), authoritiveImpl);
        }

        return conceptMap;
    }

    private static String findConceptField(final PfConceptKey conceptKey, final String keyFieldValue,
            final PfNameVersion concept, final Function<PfNameVersion, String> fieldGetterFunction) {

        String conceptField = fieldGetterFunction.apply(concept);

        if (StringUtils.isBlank(conceptField) || keyFieldValue.equals(conceptField)) {
            return keyFieldValue;
        } else {
            throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, "Key " + conceptKey.getId() + " field "
                    + keyFieldValue + " does not match the value " + conceptField + " in the concept field");
        }
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a list of maps, generating a new map.
     *
     * @param source list of maps whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @return a new map, containing mappings of all of the items in the original map, or {@code null} if the source is
     *         {@code null}
     */
    public static <A extends ToscaEntity, R> Map<String, R> listToDocMap(List<Map<String, A>> source,
            Function<A, R> mapFunc) {

        return listToDocMap(source, mapFunc, null);
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a list of maps, generating a new map.
     *
     * @param source list of maps whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @param defaultValue if source is null
     * @return a new map, containing mappings of all of the items in the original map, or defaultValue if the source is
     *         {@code null}
     */
    public static <A extends ToscaEntity, R> Map<String, R> listToDocMap(List<Map<String, A>> source,
            Function<A, R> mapFunc, Map<String, R> defaultValue) {
        if (source == null) {
            return defaultValue;
        }
        Map<String, R> conceptMap = new LinkedHashMap<>();

        for (var map : source) {
            conceptMap.putAll(mapToDocMap(map, mapFunc));
        }

        return conceptMap;
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a map, generating a new list of maps.
     *
     * @param source map whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @return a new list of maps, containing mappings of all of the items in the original map, or {@code null} if the
     *         source is {@code null}
     */
    public static <A extends PfNameVersion, R> List<Map<String, R>> docMapToList(Map<String, A> source,
            Function<A, R> mapFunc) {
        return docMapToList(source, mapFunc, null);
    }

    /**
     * Convenience method to apply a mapping function to all of the values of a map, generating a new list of maps.
     *
     * @param source map whose values are to be mapped, or {@code null}
     * @param mapFunc mapping function
     * @param defaultValue if source is null
     * @return a new list of maps, containing mappings of all of the items in the original map, or defaultValue if the
     *         source is {@code null}
     */
    public static <A extends PfNameVersion, R> List<Map<String, R>> docMapToList(Map<String, A> source,
            Function<A, R> mapFunc, List<Map<String, R>> defaultValue) {
        if (source == null) {
            return defaultValue;
        }

        List<Map<String, R>> result = new ArrayList<>();
        for (Entry<String, A> ent : source.entrySet()) {
            Map<String, R> map = new LinkedHashMap<>();
            map.put(ent.getValue().getName(), mapFunc.apply(ent.getValue()));
            result.add(map);

        }

        return result;
    }

    /**
     * Create DocConceptKey.
     *
     * @param name the name
     * @param version the version
     * @return DocConceptKey
     */
    public static DocConceptKey createDocConceptKey(String name, String version) {
        var key = new DocConceptKey();
        if (version != null && !version.isBlank()) {
            key.setName(name);
            key.setVersion(version);
        } else {
            var list = name.split(":");
            switch (list.length) {
                case 0, 1:
                    key.setName(name);
                    key.setVersion(PfKey.NULL_KEY_VERSION);
                    break;
                case 2:
                    key.setName(list[0]);
                    key.setVersion(list[1]);
                    break;
                default:
            }
        }
        return key;
    }

    /**
     * Get DocToscaReferences.
     *
     * @return ToscaReferenceType
     */
    public static Map<String, Set<String>> getToscaReferences(DocToscaServiceTemplate serviceTemplate) {
        var referenceType = new HashMap<String, Set<String>>();
        fillReferenceType(referenceType, REF_DATA_TYPES, serviceTemplate.getDataTypes());
        fillReferenceType(referenceType, REF_POLICY_TYPES, serviceTemplate.getPolicyTypes());
        fillReferenceType(referenceType, REF_NODE_TYPES, serviceTemplate.getNodeTypes());
        fillReferenceType(referenceType, REF_CAPABILITY_TYPES, serviceTemplate.getCapabilityTypes());
        fillReferenceType(referenceType, REF_RELATIONSHIP_TYPES, serviceTemplate.getRelationshipTypes());

        if (serviceTemplate.getNodeTypes() != null) {

            serviceTemplate.getNodeTypes().values().forEach(
                    nodeType -> fillReferenceType(referenceType, REF_REQUIREMENTS, nodeType.getRequirements()));
        }
        if (serviceTemplate.getToscaTopologyTemplate() != null) {

            fillReferenceType(referenceType, REF_NODE_TEMPLATES,
                    serviceTemplate.getToscaTopologyTemplate().getNodeTemplates());

            fillReferenceType(referenceType, REF_POLICIES, serviceTemplate.getToscaTopologyTemplate().getPolicies());

            if (serviceTemplate.getToscaTopologyTemplate().getNodeTemplates() != null) {
                for (var nodeTemplate : serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().values()) {
                    fillReferenceType(referenceType, REF_REQUIREMENTS, nodeTemplate.getRequirements());
                    fillReferenceType(referenceType, REF_CAPABILITIES, nodeTemplate.getCapabilities());
                }
            }

        }
        return referenceType;
    }

    private static <A extends DocToscaEntity<?>> void fillReferenceType(Map<String, Set<String>> referenceType,
            String type, Map<String, A> map) {
        referenceType.putIfAbsent(type, new HashSet<>());
        if (map != null) {
            referenceType.get(type).addAll(toSetToscaReferences(map));
        }

    }

    private static <A extends DocToscaEntity<?>> void fillReferenceType(Map<String, Set<String>> referenceType,
            String type, List<Map<String, A>> list) {
        referenceType.putIfAbsent(type, new HashSet<>());
        if (list != null) {
            list.forEach(map -> referenceType.get(type).addAll(toSetToscaReferences(map)));
        }
    }

    private static <A extends DocToscaEntity<?>> Set<String> toSetToscaReferences(Map<String, A> map) {
        Set<String> result = new HashSet<>();
        for (var entity : map.values()) {
            result.add(entity.getDocConceptKey().getId()); // ref for type
            result.add(entity.getDocConceptKey().getName()); // ref for derived from
        }
        return result;
    }

    /**
     * Compare two maps of the same type, nulls are allowed.
     *
     * @param leftMap the first map
     * @param rightMap the second map
     * @return a measure of the comparison
     */
    public static <V extends Comparable<? super V>> int compareMaps(final Map<String, V> leftMap,
            final Map<String, V> rightMap) {
        if ((MapUtils.isEmpty(leftMap) && MapUtils.isEmpty(rightMap))) {
            return 0;
        }
        if (leftMap == null) {
            return 1;
        }

        if (rightMap == null) {
            return -1;
        }
        if (leftMap.size() != rightMap.size()) {
            return leftMap.hashCode() - rightMap.hashCode();
        }

        for (var leftEntry : leftMap.entrySet()) {
            var result = ObjectUtils.compare(leftEntry.getValue(), rightMap.get(leftEntry.getKey()));
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }

    /**
     * Compare two lists of Map of the same type, nulls are allowed.
     *
     * @param leftCollection the first list
     * @param rightCollection the second list
     * @return a measure of the comparison
     */
    public static <V extends Comparable<? super V>> int compareCollections(final List<Map<String, V>> leftCollection,
            final List<Map<String, V>> rightCollection) {
        if ((CollectionUtils.isEmpty(leftCollection) && CollectionUtils.isEmpty(rightCollection))) {
            return 0;
        }
        if (leftCollection == null) {
            return 1;
        }

        if (rightCollection == null) {
            return -1;
        }
        if (leftCollection.size() != rightCollection.size()) {
            return leftCollection.hashCode() - rightCollection.hashCode();
        }

        for (var i = 0; i < leftCollection.size(); i++) {
            var result = compareMaps(leftCollection.get(i), rightCollection.get(i));
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}