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;
25 import java.io.FileOutputStream;
26 import java.util.ArrayList;
27 import java.util.HashMap;
29 import java.util.SortedSet;
30 import java.util.TreeSet;
31 import org.apache.commons.text.similarity.LevenshteinDistance;
32 import org.onap.aai.edges.EdgeIngestor;
33 import org.onap.aai.edges.EdgeRule;
34 import org.onap.aai.edges.EdgeRuleQuery;
35 import org.onap.aai.schemagen.GenerateXsd;
36 import org.onap.aai.setup.SchemaVersion;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
40 public class PutRelationPathSet {
42 private static final Logger logger = LoggerFactory.getLogger("PutRelationPathSet.class");
43 protected static HashMap<String, String> putRelationPaths = new HashMap<String, String>();
45 public static void add(String useOpId, String path) {
46 putRelationPaths.put(useOpId, path);
51 SchemaVersion version;
52 protected ArrayList<String> relations = new ArrayList<String>();
53 String objectName = "";
55 public PutRelationPathSet(SchemaVersion v) {
59 public PutRelationPathSet(String opId, String path, SchemaVersion v) {
60 this.apiPath = path.replace("/relationship-list/relationship", "");
63 objectName = DeleteOperation.deletePaths.get(apiPath);
65 "II-apiPath: " + apiPath + "\nPath: " + path + "\nopId=" + opId + "\nobjectName=" +
69 private void process(EdgeIngestor edgeIngestor) {
70 this.ei = edgeIngestor;
73 this.writeRelationsFile();
77 private void toRelations() {
78 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
79 logger.debug("apiPath: " + apiPath + "\nopId=" + opId + "\nobjectName=" + objectName);
83 new EdgeRuleQuery.Builder("ToOnly", objectName).version(version).build();
84 Multimap<String, EdgeRule> results = ei.getRules(q1);
85 relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
86 SortedSet<String> ss = new TreeSet<String>(results.keySet());
87 for (String key : ss) {
88 results.get(key).stream()
89 .filter((i) -> ("NONE".equals(i.getContains()) && !i.isPrivateEdge()))
91 String rel = selectedRelation(i);
93 logger.debug("Relation added: " + rel);
96 } catch (Exception e) {
97 logger.debug("objectName: " + objectName + "\n" + e);
101 private String selectedRelation(EdgeRule rule) {
102 String selectedRelation = "";
103 EdgeDescription ed = new EdgeDescription(rule);
104 logger.debug(ed.getRuleKey() + "Type=" + ed.getType());
105 String obj = ed.getRuleKey().replace(objectName, "").replace("|", "");
107 if (ed.getType() == EdgeDescription.LineageType.UNRELATED) {
108 String selectObj = getUnrelatedObjectPaths(obj, apiPath);
109 logger.debug("SelectedObj" + selectObj);
110 selectedRelation = formatObjectRelationSet(obj, selectObj);
111 logger.trace("ObjectRelationSet" + selectedRelation);
113 String selectObj = getKinObjectPath(obj, apiPath);
114 logger.debug("SelectedObj" + selectObj);
115 selectedRelation = formatObjectRelation(obj, selectObj);
116 logger.trace("ObjectRelationSet" + selectedRelation);
118 return selectedRelation;
121 private void fromRelations() {
122 logger.debug("“comment”: “Valid FROM Relations that can be added”");
126 new EdgeRuleQuery.Builder(objectName, "FromOnly").version(version).build();
127 Multimap<String, EdgeRule> results = ei.getRules(q1);
128 relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
129 SortedSet<String> ss = new TreeSet<String>(results.keySet());
130 for (String key : ss) {
131 results.get(key).stream().filter((i) -> (!i.isPrivateEdge())).forEach((i) -> {
132 String rel = selectedRelation(i);
134 logger.debug("Relation added: " + rel);
137 } catch (Exception e) {
138 logger.debug("objectName: " + objectName + "\n" + e);
142 private void writeRelationsFile() {
143 File examplefilePath = new File(
144 GenerateXsd.getYamlDir() + "/relations/" + version.toString() + "/" +
145 opId.replace("RelationshipListRelationship", "") + ".json");
147 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
149 if (!examplefilePath.exists()) {
150 examplefilePath.getParentFile().mkdirs();
151 if(!examplefilePath.createNewFile()) {
152 logger.debug("examplefilePath create file error");
155 } catch (Exception e) {
156 logger.debug("examplefilePath create file error", e);
159 try (FileOutputStream fop = new FileOutputStream(examplefilePath)) {
160 if (relations.size() > 0) {
161 fop.write("[\n".getBytes());
163 fop.write(String.join(",\n", relations).getBytes());
164 if (relations.size() > 0) {
165 fop.write("\n]\n".getBytes());
168 } catch (Exception e) {
169 logger.debug("examplefilePath write error", e);
172 logger.debug(String.join(",\n", relations));
175 private static String formatObjectRelationSet(String obj, String selectObj) {
176 StringBuilder pathSb = new StringBuilder();
177 String[] paths = selectObj.split("[|]");
178 for (String s : paths) {
179 logger.trace("SelectOBJ" + s);
180 pathSb.append(formatObjectRelation(obj, s)).append(",\n");
182 pathSb.deleteCharAt(pathSb.length() - 2);
183 return pathSb.toString();
186 private static String formatObjectRelation(String obj, String selectObj) {
187 StringBuilder pathSb = new StringBuilder();
188 pathSb.append("{\n");
189 pathSb.append("\"related-to\" : \"").append(obj).append("\",\n");
190 pathSb.append("\"related-link\" : \"").append(selectObj).append("\"\n");
192 return pathSb.toString();
195 private static String getKinObjectPath(String obj, String apiPath) {
196 LevenshteinDistance proximity = new LevenshteinDistance();
197 String targetPath = "";
198 int targetScore = Integer.MAX_VALUE;
199 int targetMaxScore = 0;
200 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
201 if (p.getValue().equals(obj)) {
202 targetScore = (targetScore >= proximity.apply(apiPath, p.getKey())) ?
203 proximity.apply(apiPath, p.getKey()) : targetScore;
205 (targetScore >= proximity.apply(apiPath, p.getKey())) ? p.getKey() : targetPath;
206 targetMaxScore = (targetMaxScore <= proximity.apply(apiPath, p.getKey())) ?
207 proximity.apply(apiPath, p.getKey()) : targetScore;
208 logger.trace(proximity.apply(apiPath, p.getKey()) + ":" + p.getKey());
209 logger.trace(proximity.apply(apiPath, p.getKey()) + ":" + apiPath);
215 private static String getUnrelatedObjectPaths(String obj, String apiPath) {
216 StringBuilder targetPath = new StringBuilder();
217 logger.trace("Obj:" + obj + "\n" + apiPath);
218 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
219 if (p.getValue().equals(obj)) {
220 logger.trace("p.getvalue:" + p.getValue() + "p.getkey:" + p.getKey());
221 targetPath.append(targetPath.length() == 0 ? "" : "|").append(p.getKey());
222 logger.trace("Match:" + apiPath + "\n" + targetPath);
225 return targetPath.toString();
228 public void generateRelations(EdgeIngestor edgeIngestor) {
229 putRelationPaths.forEach((k, v) -> {
230 logger.trace("k=" + k + "\n" + "v=" + v + v.equals(
231 "/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"));
232 logger.debug("apiPath(Operation): " + v);
233 logger.debug("Target object: " + v.replace("/relationship-list/relationship", ""));
234 logger.debug("Relations: ");
235 PutRelationPathSet prp = new PutRelationPathSet(k, v, this.version);
236 prp.process(edgeIngestor);