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