Merge "[AAI] Fix doc config files"
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / introspection / sideeffect / SideEffect.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai.introspection.sideeffect;
22
23 import java.io.UnsupportedEncodingException;
24 import java.net.URISyntaxException;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.LinkedHashSet;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.Optional;
31 import java.util.Set;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import org.apache.tinkerpop.gremlin.structure.Vertex;
36 import org.onap.aai.edges.exceptions.AmbiguousRuleChoiceException;
37 import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
38 import org.onap.aai.exceptions.AAIException;
39 import org.onap.aai.introspection.Introspector;
40 import org.onap.aai.introspection.Loader;
41 import org.onap.aai.introspection.LoaderUtil;
42 import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException;
43 import org.onap.aai.schema.enums.PropertyMetadata;
44 import org.onap.aai.serialization.db.DBSerializer;
45 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public abstract class SideEffect {
50
51     protected static final Pattern template = Pattern.compile("\\{(.*?)\\}");
52     private static final Logger logger = LoggerFactory.getLogger(SideEffect.class);
53
54     protected final Introspector obj;
55     protected final TransactionalGraphEngine dbEngine;
56     protected final DBSerializer serializer;
57     protected final Loader latestLoader;
58     protected final Vertex self;
59
60     protected Set<String> templateKeys = new HashSet<>();
61
62     public SideEffect(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
63         this.obj = obj;
64         this.dbEngine = dbEngine;
65         this.serializer = serializer;
66         this.self = self;
67         this.latestLoader = LoaderUtil.getLatestVersion();
68     }
69
70     protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException {
71         final Map<String, String> properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata());
72         for (Entry<String, String> entry : properties.entrySet()) {
73             Optional<String> populatedUri = this.replaceTemplates(obj, entry.getValue());
74             Optional<String> completeUri = this.resolveRelativePath(populatedUri);
75             try {
76                 this.processURI(completeUri, entry);
77             } catch (EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
78                 logger.warn("Unable to execute the side effect {} due to ", this.getClass().getName(), e);
79             }
80         }
81     }
82
83     protected Map<String, String> findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) {
84         final Map<String, String> result = new HashMap<>();
85         for (String prop : obj.getProperties()) {
86             final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
87             if (map.containsKey(metadata)) {
88                 result.put(prop, map.get(metadata));
89             }
90         }
91         return result;
92     }
93
94     protected Map<String, String> findProperties(Introspector obj, String uriString)
95             throws AAIMissingRequiredPropertyException {
96
97         final Map<String, String> result = new HashMap<>();
98         final Set<String> missing = new LinkedHashSet<>();
99         Matcher m = template.matcher(uriString);
100         int properties = 0;
101         while (m.find()) {
102             String propName = m.group(1);
103             String value = obj.getValue(propName);
104             properties++;
105             if (value != null) {
106                 result.put(propName, value);
107             } else {
108                 if (replaceWithWildcard()) {
109                     result.put(propName, "*");
110                 }
111                 missing.add(propName);
112             }
113         }
114
115         if (!missing.isEmpty() && (properties != missing.size())) {
116             throw new AAIMissingRequiredPropertyException(
117                     "Cannot complete " + this.getPropertyMetadata().toString() + " uri. Missing properties " + missing);
118         }
119         return result;
120     }
121
122     protected Optional<String> replaceTemplates(Introspector obj, String uriString)
123             throws AAIMissingRequiredPropertyException {
124         String result = uriString;
125         final Map<String, String> propMap = this.findProperties(obj, uriString);
126         if (propMap.isEmpty()) {
127             return Optional.empty();
128         }
129         for (Entry<String, String> entry : propMap.entrySet()) {
130             templateKeys.add(entry.getKey());
131             result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
132         }
133         // drop out wildcards if they exist
134         result = result.replaceFirst("/[^/]+?(?:/\\*)+", "");
135         return Optional.of(result);
136     }
137
138     private Optional<String> resolveRelativePath(Optional<String> populatedUri) throws UnsupportedEncodingException {
139         if (!populatedUri.isPresent()) {
140             return Optional.empty();
141         } else {
142             return Optional.of(populatedUri.get().replaceFirst("\\./", this.serializer.getURIForVertex(self) + "/"));
143         }
144     }
145
146     protected abstract boolean replaceWithWildcard();
147
148     protected abstract PropertyMetadata getPropertyMetadata();
149
150     protected abstract void processURI(Optional<String> completeUri, Entry<String, String> entry)
151             throws URISyntaxException, UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException,
152             AmbiguousRuleChoiceException;
153 }