aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/aai/cacher/injestion/parser/strategy/aai/dmaap/AAIResourceDmaapParserStrategy.java
blob: 8d88a4a596f8a3a11330006ab0d1f5c6e408a560 (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
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 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.
 * ============LICENSE_END=========================================================
 */
package org.onap.aai.cacher.injestion.parser.strategy.aai.dmaap;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.onap.aai.cacher.injestion.parser.strategy.AAIResourceGetAllPayloadParserStrategy;
import org.onap.aai.cacher.injestion.parser.strategy.aai.AAIResourcesUriTemplates;
import org.onap.aai.cacher.injestion.parser.strategy.aai.AAIUriSegment;
import org.onap.aai.cacher.model.CacheEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * AAI resource get all parser strategy
 */
@Component(value = "aai-resource-dmaap")
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class AAIResourceDmaapParserStrategy extends AAIResourceGetAllPayloadParserStrategy {
    
    private final static EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIResourceDmaapParserStrategy.class);

    @Autowired
    public AAIResourceDmaapParserStrategy(AAIResourcesUriTemplates aaiResourcesUriTemplates) {
        super(aaiResourcesUriTemplates);
    }

    /**
     * Parses aai resources specific payloads generating the details for caching.
     *
     * @param originalKey
     * @param jsonObject
     * @return
     */
    @Override
    public List<CacheEntry> process(String originalKey, JsonObject jsonObject) {
        final List<CacheEntry> cacheEntries;

        JsonObject header = jsonObject.getAsJsonObject("event-header");
        String topEntityType = header.get("top-entity-type").getAsString();
        String fullUri = header.get("entity-link").getAsString();
        if ( fullUri.endsWith("/")) {
            fullUri = fullUri.substring(0, fullUri.length() - 1);
        }
        String entityUri = aaiResourcesUriTemplates.getAAIUriFromEntityUri(fullUri);
        String fullUriPrefix = aaiResourcesUriTemplates.getAAIUriFromEntityUriPrefix(fullUri);

        DmaapAction actionType = DmaapAction.valueOf(header.get("action").getAsString());

        List<AAIUriSegment> uriSegments = aaiResourcesUriTemplates.getAaiUriSegments(entityUri);

        // get base uri so if is top lvl use "" else go 1 back from current node type. to reuse exist functions.
        String baseUri = getBaseUri(uriSegments);

        // get wrapped wrap obj it looks like a get-all result with 1
        // will wrap address lists even though they do not normally have a wrapper
        JsonObject wrappedEntityObject = getWrappedEntityObject(jsonObject.getAsJsonObject("entity"), uriSegments);

        // get cache entries
        cacheEntries = internalProcess(topEntityType, wrappedEntityObject, baseUri);

        // modify action to map to dmaap event type
        cacheEntries.forEach(cacheEntry -> cacheEntry.setDbAction(actionType.getDbAction()));

        // cache entries for relationships
        MultiValueMap<String, AAIRelatedToDetails> cacheEntriesRelationships =
                getFromRelationshipFullUriToRelationshipObj(cacheEntries, fullUriPrefix, actionType);

        if (jsonObject.has("existing-obj")) {
            MultiValueMap<String, AAIRelatedToDetails> existingCacheEntriesRelationships =
                    getFromRelationshipFullUriToRelationshipObj(
                            internalProcess(topEntityType, jsonObject.getAsJsonObject("existing-obj"), baseUri),
                            fullUriPrefix,
                            actionType
                    );
            adjustRelationshipsBasedOnExisting(existingCacheEntriesRelationships, cacheEntriesRelationships);

        }

        cacheEntries.addAll(getRelationshipCacheEntries(cacheEntriesRelationships));

        getParentUpdateCacheEntryIfNeeded(topEntityType, entityUri, actionType, uriSegments).ifPresent(cacheEntries::add);

        return cacheEntries;
    }

    private Optional<CacheEntry> getParentUpdateCacheEntryIfNeeded(String topEntityType, String entityUri, DmaapAction actionType, List<AAIUriSegment> uriSegments) {

        if (uriSegments.size() <= 1) {
            return Optional.empty();
        }

        switch (actionType) {
            case DELETE:
                return Optional.of(getParentUpdateCacheEntry(topEntityType, entityUri, actionType, uriSegments));
            case CREATE:
                return Optional.of(getParentUpdateCacheEntry(topEntityType, entityUri, DmaapAction.UPDATE, uriSegments));
            default:
                return Optional.empty();
        }
    }

    private CacheEntry getParentUpdateCacheEntry(String topEntityType, String entityUri, DmaapAction actionType, List<AAIUriSegment> uriSegments) {
        String parentUri = String.join(
                "",
                uriSegments.stream().limit(uriSegments.size()-1).map(AAIUriSegment::getSegment).collect(Collectors.toList()));
        JsonObject findQuery = new JsonObject();
        findQuery.addProperty("_id", parentUri);
        JsonObject nestedFindQuery = new JsonObject();
        nestedFindQuery.addProperty("_id", parentUri);
        StringBuilder nestedField = new StringBuilder();
        uriSegments.get(uriSegments.size()-1).getSegmentPlural().ifPresent(plural -> nestedField.append(plural).append("."));
        nestedField.append(uriSegments.get(uriSegments.size()-1).getSegmentSingular());
        JsonObject nestedIdentifier = new JsonObject();
        JsonArray ja = new JsonArray();
        ja.add(entityUri);
        nestedIdentifier.add("$in", ja);
        return CacheEntry.CacheEntryBuilder.createCacheEntry()
                .inCollection(topEntityType)
                .withDbAction(actionType.getDbAction())
                .withId(parentUri)
                .isNested(true)
                .isNestedPayloadString(true)
                .withNestedString(entityUri)
                .withFindQuery(findQuery)
                .withNestedFind(nestedFindQuery)
                .withNestedField(nestedField.toString())
                .withNestedFieldIdentifierObj(nestedIdentifier)
                .build();
    }

    private List<CacheEntry> getRelationshipCacheEntries(MultiValueMap<String, AAIRelatedToDetails> cacheEntriesRelationships) {
        final List<CacheEntry> cacheEntries = new ArrayList<>();
        JsonObject relatedToObj;
        for (Map.Entry<String, List<AAIRelatedToDetails>> relationship : cacheEntriesRelationships.entrySet()) {
            for (AAIRelatedToDetails aaiRelatedToDetails : relationship.getValue()) {
                relatedToObj = fullUriToRelationshipObj(relationship.getKey(), aaiRelatedToDetails.getLabel());
                cacheEntries.add(generateRelationshipCacheEntry(relatedToObj, aaiRelatedToDetails.getActionType(),
                        aaiRelatedToDetails.getFullUri()));
            }
        }
        return cacheEntries;
    }

    private CacheEntry generateRelationshipCacheEntry(JsonObject entity, DmaapAction actionType, String fullUri) {

        String uri = aaiResourcesUriTemplates.getAAIUriFromEntityUri(fullUri);
        List<AAIUriSegment> uriSegmentList = aaiResourcesUriTemplates.getAaiUriSegments(uri);
        String collection = uriSegmentList.get(0).getSegmentSingular();
        JsonObject findQuery = new JsonObject();
        findQuery.addProperty("_id", uri);
        JsonObject nestedFindQuery = new JsonObject();
        nestedFindQuery.addProperty("_id", uri);
        nestedFindQuery.addProperty("relationship-list.relationship.related-link", entity.get("related-link").getAsString());
        String nestedField = "relationship-list.relationship";
        JsonObject nestedIdentifier = new JsonObject();
        nestedIdentifier.addProperty("related-link", entity.get("related-link").getAsString());

        return CacheEntry.CacheEntryBuilder.createCacheEntry().inCollection(collection).withDbAction(actionType.getDbAction())
                .withId(uri).isNested(true).withPayload(entity).withFindQuery(findQuery)
                .withNestedFind(nestedFindQuery).withNestedField(nestedField)
                .withNestedFieldIdentifierObj(nestedIdentifier).build();
    }

    private void adjustRelationshipsBasedOnExisting(MultiValueMap<String, AAIRelatedToDetails> existingCacheEntriesRelationships,
                                                    MultiValueMap<String, AAIRelatedToDetails> cacheEntriesRelationships) {
        existingCacheEntriesRelationships.forEach((k, v) -> {
            if (cacheEntriesRelationships.containsKey(k)) {
                v.forEach(oldA -> {
                    int found = -1;
                    for (int i = 0; i < cacheEntriesRelationships.get(k).size(); i++) {
                        if (cacheEntriesRelationships.get(k).get(i).getFullUri().equals(oldA.getFullUri())) {
                            found = i;
                            break;
                        }
                    }
                    if (found != -1) {
                        cacheEntriesRelationships.get(k).remove(cacheEntriesRelationships.get(k).get(found));
                    } else {
                        oldA.setActionType(DmaapAction.DELETE);
                        cacheEntriesRelationships.get(k).add(oldA);
                    }
                });
            } else {
                v.forEach(aaiRelatedToDetails -> {
                    aaiRelatedToDetails.setActionType(DmaapAction.DELETE);
                    cacheEntriesRelationships.add(k, aaiRelatedToDetails);
                });
            }
        });
    }

    private MultiValueMap<String, AAIRelatedToDetails> getFromRelationshipFullUriToRelationshipObj(
            List<CacheEntry> cacheEntries,
            String fullUriPrefix,
            DmaapAction actionType) {
        final MultiValueMap<String, AAIRelatedToDetails> relationshipMapping = new LinkedMultiValueMap<>();
        for (CacheEntry cacheEntry : cacheEntries) {
            for (Map.Entry<String, JsonElement> e : cacheEntry.getPayload().entrySet()) {
                if (e.getKey().equals("relationship-list") && e.getValue().isJsonObject()) {
                    JsonArray relationships = e.getValue().getAsJsonObject().getAsJsonArray("relationship");
                    for (JsonElement relationship : relationships) {
                        relationshipMapping.add(fullUriPrefix + cacheEntry.getId(), new AAIRelatedToDetails(
                                relationship.getAsJsonObject().get("related-link").getAsString(),
                                relationship.getAsJsonObject().get("relationship-label").getAsString(), actionType));
                    }
                }
            }
        }
        return relationshipMapping;
    }

    /**
     * Given fullUri uri generate an aai relationship obj
     *
     * @param fullUri
     * @return
     */
    protected JsonObject fullUriToRelationshipObj(String fullUri, String label) {
        final JsonObject relObj = new JsonObject();
        final JsonArray relData = new JsonArray();
        String uri = aaiResourcesUriTemplates.getAAIUriFromEntityUri(fullUri);
        List<AAIUriSegment> uriSegmentList = aaiResourcesUriTemplates.getAaiUriSegments(uri);

        relObj.addProperty("related-to", uriSegmentList.get(uriSegmentList.size() - 1).getSegmentSingular());
        if (label != null) {
            relObj.addProperty("relationship-label", label);
        }
        relObj.addProperty("related-link", fullUri);

        for (AAIUriSegment aaiUriSegment : uriSegmentList) {
            aaiUriSegment.getSegmentKeyValues().forEach((k, v) -> {
                JsonObject relDataEntry;
                relDataEntry = new JsonObject();
                relDataEntry.addProperty("relationship-key", aaiUriSegment.getSegmentSingular() + "." + k);
                relDataEntry.addProperty("relationship-value", v);
                relData.add(relDataEntry);
            });
        }
        relObj.add("relationship-data", relData);

        return relObj;
    }

    private JsonObject getWrappedEntityObject(JsonObject dmaapEntity, List<AAIUriSegment> uriSegments) {
        JsonObject objectWrapper = new JsonObject();
        JsonArray arrayWrapper = new JsonArray();
        String arrayKey = uriSegments.get(0).getSegmentSingular();
        JsonObject entityBody = dmaapEntity.getAsJsonObject();

        if (uriSegments.size() > 1) {
            Optional<String> segmentPlural;
            String segmentSingular;
            String jsonStr;
            JsonObject jsonObj;
            JsonArray jsonArray;
            JsonElement jsonElement;

            for (int i = 1; i < uriSegments.size(); i++) {

                if (uriSegments.get(i).getSegmentPlural().isPresent()) {
                    segmentPlural = uriSegments.get(i).getSegmentPlural();
                    segmentSingular = uriSegments.get(i).getSegmentSingular();
                    if ( segmentSingular.equals("cvlan-tag")) {
                            // map to what is in the entity
                        segmentSingular = "cvlan-tag-entry";
                    }
                    jsonObj = entityBody.getAsJsonObject(uriSegments.get(i).getSegmentPlural().get());
                    jsonArray = jsonObj.getAsJsonArray(segmentSingular);
                    if ( jsonArray == null ) {
                        LOGGER.error("failed in getWrappedEntityObject " + segmentSingular + " not found in " + jsonObj );
                        // exception expected for missing template
                    }
                    entityBody = jsonArray.get(0).getAsJsonObject();
                    arrayKey = uriSegments.get(i).getSegmentSingular();
                } else {
                    entityBody = entityBody.getAsJsonArray(uriSegments.get(i).getSegmentSingular()).get(0).getAsJsonObject();
                    arrayKey = uriSegments.get(i).getSegmentSingular();
                }

            }
        }
        arrayWrapper.add(entityBody);
        objectWrapper.add(arrayKey, arrayWrapper);
        return objectWrapper;
    }

    private String getBaseUri(List<AAIUriSegment> uriSegments) {
        if (uriSegments.isEmpty() || uriSegments.size() == 1) {
            return "";
        }
        return String.join("", uriSegments.subList(0, uriSegments.size()-1).stream().map(AAIUriSegment::getSegment).collect(Collectors.toList()));
    }



}