2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.schemagen.genxsd;
23 import com.google.common.collect.Multimap;
26 import java.io.FileOutputStream;
27 import java.util.ArrayList;
28 import java.util.HashMap;
30 import java.util.SortedSet;
31 import java.util.TreeSet;
33 import org.apache.commons.text.similarity.LevenshteinDistance;
34 import org.onap.aai.edges.EdgeIngestor;
35 import org.onap.aai.edges.EdgeRule;
36 import org.onap.aai.edges.EdgeRuleQuery;
37 import org.onap.aai.schemagen.GenerateXsd;
38 import org.onap.aai.setup.SchemaVersion;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public class PutRelationPathSet {
44 private static final Logger logger = LoggerFactory.getLogger("PutRelationPathSet.class");
45 protected static HashMap<String, String> putRelationPaths = new HashMap<String, String>();
47 public static void add(String useOpId, String path) {
48 putRelationPaths.put(useOpId, path);
53 SchemaVersion version;
54 protected ArrayList<String> relations = new ArrayList<String>();
55 String objectName = "";
57 public PutRelationPathSet(SchemaVersion v) {
61 public PutRelationPathSet(String opId, String path, SchemaVersion v) {
62 this.apiPath = path.replace("/relationship-list/relationship", "");
65 objectName = DeleteOperation.deletePaths.get(apiPath);
66 logger.debug("II-apiPath: " + apiPath + "\nPath: " + path + "\nopId=" + opId
67 + "\nobjectName=" + objectName);
70 private void process(EdgeIngestor edgeIngestor) {
71 this.ei = edgeIngestor;
74 this.writeRelationsFile();
78 private void toRelations() {
79 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
80 logger.debug("apiPath: " + apiPath + "\nopId=" + opId + "\nobjectName=" + objectName);
84 new EdgeRuleQuery.Builder("ToOnly", objectName).version(version).build();
85 Multimap<String, EdgeRule> results = ei.getRules(q1);
86 relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
87 SortedSet<String> ss = new TreeSet<String>(results.keySet());
88 for (String key : ss) {
89 results.get(key).stream()
90 .filter((i) -> ("NONE".equals(i.getContains()) && !i.isPrivateEdge()))
92 String rel = selectedRelation(i);
94 logger.debug("Relation added: " + rel);
97 } catch (Exception e) {
98 logger.debug("objectName: " + objectName + "\n" + e);
102 private String selectedRelation(EdgeRule rule) {
103 String selectedRelation = "";
104 EdgeDescription ed = new EdgeDescription(rule);
105 logger.debug(ed.getRuleKey() + "Type=" + ed.getType());
106 String obj = ed.getRuleKey().replace(objectName, "").replace("|", "");
108 if (ed.getType() == EdgeDescription.LineageType.UNRELATED) {
109 String selectObj = getUnrelatedObjectPaths(obj, apiPath);
110 logger.debug("SelectedObj" + selectObj);
111 selectedRelation = formatObjectRelationSet(obj, selectObj);
112 logger.trace("ObjectRelationSet" + selectedRelation);
114 String selectObj = getKinObjectPath(obj, apiPath);
115 logger.debug("SelectedObj" + selectObj);
116 selectedRelation = formatObjectRelation(obj, selectObj);
117 logger.trace("ObjectRelationSet" + selectedRelation);
119 return selectedRelation;
122 private void fromRelations() {
123 logger.debug("“comment”: “Valid FROM Relations that can be added”");
127 new EdgeRuleQuery.Builder(objectName, "FromOnly").version(version).build();
128 Multimap<String, EdgeRule> results = ei.getRules(q1);
129 relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
130 SortedSet<String> ss = new TreeSet<String>(results.keySet());
131 for (String key : ss) {
132 results.get(key).stream().filter((i) -> (!i.isPrivateEdge())).forEach((i) -> {
133 String rel = selectedRelation(i);
135 logger.debug("Relation added: " + rel);
138 } catch (Exception e) {
139 logger.debug("objectName: " + objectName + "\n" + e);
143 private void writeRelationsFile() {
144 File examplefilePath =
145 new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString() + "/"
146 + opId.replace("RelationshipListRelationship", "") + ".json");
148 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
150 if (!examplefilePath.exists()) {
151 examplefilePath.getParentFile().mkdirs();
152 if (!examplefilePath.createNewFile()) {
153 logger.debug("examplefilePath create file error");
156 } catch (Exception e) {
157 logger.debug("examplefilePath create file error", e);
160 try (FileOutputStream fop = new FileOutputStream(examplefilePath)) {
161 if (relations.size() > 0) {
162 fop.write("[\n".getBytes());
164 fop.write(String.join(",\n", relations).getBytes());
165 if (relations.size() > 0) {
166 fop.write("\n]\n".getBytes());
169 } catch (Exception e) {
170 logger.debug("examplefilePath write error", e);
173 logger.debug(String.join(",\n", relations));
176 private static String formatObjectRelationSet(String obj, String selectObj) {
177 StringBuilder pathSb = new StringBuilder();
178 String[] paths = selectObj.split("[|]");
179 for (String s : paths) {
180 logger.trace("SelectOBJ" + s);
181 pathSb.append(formatObjectRelation(obj, s)).append(",\n");
183 pathSb.deleteCharAt(pathSb.length() - 2);
184 return pathSb.toString();
187 private static String formatObjectRelation(String obj, String selectObj) {
188 StringBuilder pathSb = new StringBuilder();
189 pathSb.append("{\n");
190 pathSb.append("\"related-to\" : \"").append(obj).append("\",\n");
191 pathSb.append("\"related-link\" : \"").append(selectObj).append("\"\n");
193 return pathSb.toString();
196 private static String getKinObjectPath(String obj, String apiPath) {
197 LevenshteinDistance proximity = new LevenshteinDistance();
198 String targetPath = "";
199 int targetScore = Integer.MAX_VALUE;
200 int targetMaxScore = 0;
201 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
202 if (p.getValue().equals(obj)) {
203 targetScore = (targetScore >= proximity.apply(apiPath, p.getKey()))
204 ? proximity.apply(apiPath, p.getKey())
207 (targetScore >= proximity.apply(apiPath, p.getKey())) ? p.getKey() : targetPath;
208 targetMaxScore = (targetMaxScore <= proximity.apply(apiPath, p.getKey()))
209 ? proximity.apply(apiPath, p.getKey())
211 logger.trace(proximity.apply(apiPath, p.getKey()) + ":" + p.getKey());
212 logger.trace(proximity.apply(apiPath, p.getKey()) + ":" + apiPath);
218 private static String getUnrelatedObjectPaths(String obj, String apiPath) {
219 StringBuilder targetPath = new StringBuilder();
220 logger.trace("Obj:" + obj + "\n" + apiPath);
221 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
222 if (p.getValue().equals(obj)) {
223 logger.trace("p.getvalue:" + p.getValue() + "p.getkey:" + p.getKey());
224 targetPath.append(targetPath.length() == 0 ? "" : "|").append(p.getKey());
225 logger.trace("Match:" + apiPath + "\n" + targetPath);
228 return targetPath.toString();
231 public void generateRelations(EdgeIngestor edgeIngestor) {
232 putRelationPaths.forEach((k, v) -> {
233 logger.trace("k=" + k + "\n" + "v=" + v + v.equals(
234 "/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription/{service-type}/service-instances/service-instance/{service-instance-id}/allotted-resources/allotted-resource/{id}/relationship-list/relationship"));
235 logger.debug("apiPath(Operation): " + v);
236 logger.debug("Target object: " + v.replace("/relationship-list/relationship", ""));
237 logger.debug("Relations: ");
238 PutRelationPathSet prp = new PutRelationPathSet(k, v, this.version);
239 prp.process(edgeIngestor);