Enhancements for the aai-common library
[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 org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import java.io.UnsupportedEncodingException;
27 import java.net.URISyntaxException;
28 import java.util.*;
29 import java.util.Map.Entry;
30 import java.util.regex.Matcher;
31 import java.util.regex.Pattern;
32
33 import org.apache.tinkerpop.gremlin.structure.Vertex;
34 import org.onap.aai.config.SpringContextAware;
35 import org.onap.aai.db.props.AAIProperties;
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.*;
40 import org.onap.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException;
41 import org.onap.aai.schema.enums.PropertyMetadata;
42 import org.onap.aai.serialization.db.DBSerializer;
43 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
44 import org.onap.aai.setup.SchemaVersions;
45
46 public abstract class SideEffect {
47
48     protected static final Pattern template = Pattern.compile("\\{(.*?)\\}");
49     private static final Logger logger = LoggerFactory.getLogger(SideEffect.class);
50
51     protected final Introspector obj;
52     protected final TransactionalGraphEngine dbEngine;
53     protected final DBSerializer serializer;
54     protected final Loader latestLoader;
55     protected final Vertex self;
56
57     protected Set<String> templateKeys = new HashSet<>();
58
59     public SideEffect(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) {
60         this.obj = obj;
61         this.dbEngine = dbEngine;
62         this.serializer = serializer;
63         this.self = self;
64         this.latestLoader = LoaderUtil.getLatestVersion();
65     }
66
67     protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException {
68         final Map<String, String> properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata());
69         for (Entry<String, String> entry : properties.entrySet()) {
70             Optional<String> populatedUri = this.replaceTemplates(obj, entry.getValue());
71             Optional<String> completeUri = this.resolveRelativePath(populatedUri);
72             try {
73                 this.processURI(completeUri, entry);
74             } catch (EdgeRuleNotFoundException | AmbiguousRuleChoiceException e) {
75                 logger.warn("Unable to execute the side effect {} due to ", e, this.getClass().getName());
76             }
77         }
78     }
79
80     protected Map<String, String> findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) {
81         final Map<String, String> result = new HashMap<>();
82         for (String prop : obj.getProperties()) {
83             final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop);
84             if (map.containsKey(metadata)) {
85                 result.put(prop, map.get(metadata));
86             }
87         }
88         return result;
89     }
90
91     protected Map<String, String> findProperties(Introspector obj, String uriString)
92             throws AAIMissingRequiredPropertyException {
93
94         final Map<String, String> result = new HashMap<>();
95         final Set<String> missing = new LinkedHashSet<>();
96         Matcher m = template.matcher(uriString);
97         int properties = 0;
98         while (m.find()) {
99             String propName = m.group(1);
100             String value = obj.getValue(propName);
101             properties++;
102             if (value != null) {
103                 result.put(propName, value);
104             } else {
105                 if (replaceWithWildcard()) {
106                     result.put(propName, "*");
107                 }
108                 missing.add(propName);
109             }
110         }
111
112         if (!missing.isEmpty() && (properties != missing.size())) {
113             throw new AAIMissingRequiredPropertyException(
114                     "Cannot complete " + this.getPropertyMetadata().toString() + " uri. Missing properties " + missing);
115         }
116         return result;
117     }
118
119     protected Optional<String> replaceTemplates(Introspector obj, String uriString)
120             throws AAIMissingRequiredPropertyException {
121         String result = uriString;
122         final Map<String, String> propMap = this.findProperties(obj, uriString);
123         if (propMap.isEmpty()) {
124             return Optional.empty();
125         }
126         for (Entry<String, String> entry : propMap.entrySet()) {
127             templateKeys.add(entry.getKey());
128             result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue());
129         }
130         // drop out wildcards if they exist
131         result = result.replaceFirst("/[^/]+?(?:/\\*)+", "");
132         return Optional.of(result);
133     }
134
135     private Optional<String> resolveRelativePath(Optional<String> populatedUri) throws UnsupportedEncodingException {
136         if (!populatedUri.isPresent()) {
137             return Optional.empty();
138         } else {
139             return Optional.of(populatedUri.get().replaceFirst("\\./", this.serializer.getURIForVertex(self) + "/"));
140         }
141     }
142
143     protected abstract boolean replaceWithWildcard();
144
145     protected abstract PropertyMetadata getPropertyMetadata();
146
147     protected abstract void processURI(Optional<String> completeUri, Entry<String, String> entry)
148             throws URISyntaxException, UnsupportedEncodingException, AAIException, EdgeRuleNotFoundException,
149             AmbiguousRuleChoiceException;
150 }