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=========================================================
20 package org.onap.aai.util.genxsd;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
28 import java.util.SortedSet;
29 import java.util.TreeSet;
31 import org.apache.commons.text.similarity.LevenshteinDistance;
32 import org.onap.aai.setup.SchemaVersion;
33 import org.onap.aai.config.SpringContextAware;
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.util.GenerateXsd;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 import com.google.common.collect.Multimap;
43 public class PutRelationPathSet {
45 private static final Logger logger = LoggerFactory.getLogger("PutRelationPathSet.class");
46 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+"\nobjectName="+objectName);
68 private void process(EdgeIngestor edgeIngestor) {
69 this.ei = edgeIngestor;
72 this.writeRelationsFile();
75 private void toRelations() {
76 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
77 logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName);
80 EdgeRuleQuery q1 = new EdgeRuleQuery.Builder("ToOnly",objectName).version(version).build();
81 Multimap<String, EdgeRule> results = ei.getRules(q1);
82 relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
83 SortedSet<String> ss=new TreeSet<String>(results.keySet());
84 for(String key : ss) {
85 results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } );
87 } catch(Exception e) {
88 logger.debug("objectName: "+objectName+"\n"+e);
91 private String selectedRelation(EdgeRule rule) {
92 String selectedRelation = "";
93 EdgeDescription ed = new EdgeDescription(rule);
94 logger.debug(ed.getRuleKey()+"Type="+ed.getType());
95 String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
97 if(ed.getType() == EdgeDescription.LineageType.UNRELATED) {
98 String selectObj = getUnrelatedObjectPaths(obj, apiPath);
99 logger.debug("SelectedObj"+selectObj);
100 selectedRelation = formatObjectRelationSet(obj,selectObj);
101 logger.trace("ObjectRelationSet"+selectedRelation);
103 String selectObj = getKinObjectPath(obj, apiPath);
104 logger.debug("SelectedObj"+selectObj);
105 selectedRelation = formatObjectRelation(obj,selectObj);
106 logger.trace("ObjectRelationSet"+selectedRelation);
108 return selectedRelation;
111 private void fromRelations() {
112 logger.debug("“comment”: “Valid FROM Relations that can be added”");
115 EdgeRuleQuery q1 = new EdgeRuleQuery.Builder(objectName,"FromOnly").version(version).build();
116 Multimap<String, EdgeRule> results = ei.getRules(q1);
117 relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
118 SortedSet<String> ss=new TreeSet<String>(results.keySet());
119 for(String key : ss) {
120 results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } );
122 } catch(Exception e) {
123 logger.debug("objectName: "+objectName+"\n"+e);
126 private void writeRelationsFile() {
127 File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString()+"/"+opId.replace("RelationshipListRelationship", "") + ".json");
129 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
130 FileOutputStream fop = null;
132 if (!examplefilePath.exists()) {
133 examplefilePath.getParentFile().mkdirs();
134 examplefilePath.createNewFile();
136 fop = new FileOutputStream(examplefilePath);
137 } catch(Exception e) {
142 if(relations.size() > 0) {fop.write("[\n".getBytes());}
143 fop.write(String.join(",\n", relations).getBytes());
144 if(relations.size() > 0) {fop.write("\n]\n".getBytes());}
147 } catch (Exception e) {
154 } catch (IOException e) {
158 logger.debug(String.join(",\n", relations));
162 private static String formatObjectRelationSet(String obj, String selectObj) {
163 StringBuffer pathSb = new StringBuffer();
164 String[] paths = selectObj.split("[|]");
165 for (String s: paths) {
166 logger.trace("SelectOBJ"+s);
167 pathSb.append(formatObjectRelation(obj, s)+",\n");
169 pathSb.deleteCharAt(pathSb.length()-2);
170 return pathSb.toString();
173 private static String formatObjectRelation(String obj, String selectObj) {
174 StringBuffer pathSb = new StringBuffer();
175 pathSb.append("{\n");
176 pathSb.append("\"related-to\" : \""+obj+"\",\n");
177 pathSb.append("\"related-link\" : \""+selectObj+"\"\n");
179 return pathSb.toString();
182 private static String getKinObjectPath(String obj, String apiPath) {
183 LevenshteinDistance proximity = new LevenshteinDistance();
184 String targetPath = "";
185 int targetScore = Integer.MAX_VALUE;
186 int targetMaxScore = 0;
187 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
188 if(p.getValue().equals(obj)) {
189 targetScore = (targetScore >= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore;
190 targetPath = (targetScore >= proximity.apply(apiPath, p.getKey())) ? p.getKey() : targetPath;
191 targetMaxScore = (targetMaxScore <= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore;
192 logger.trace(proximity.apply(apiPath, p.getKey())+":"+p.getKey());
193 logger.trace(proximity.apply(apiPath, p.getKey())+":"+apiPath);
199 private static String getUnrelatedObjectPaths(String obj, String apiPath) {
200 String targetPath = "";
201 logger.trace("Obj:"+obj +"\n" + apiPath);
202 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
203 if(p.getValue().equals(obj)) {
204 logger.trace("p.getvalue:"+p.getValue()+"p.getkey:"+p.getKey());
205 targetPath += ((targetPath.length() == 0 ? "" : "|") + p.getKey());
206 logger.trace("Match:"+apiPath +"\n" + targetPath);
212 public void generateRelations(EdgeIngestor edgeIngestor) {
213 putRelationPaths.forEach((k,v)->{
214 logger.trace("k="+k+"\n"+"v="+v+v.equals("/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"));
215 logger.debug("apiPath(Operation): "+v);
216 logger.debug("Target object: "+v.replace("/relationship-list/relationship", ""));
217 logger.debug("Relations: ");
218 PutRelationPathSet prp = new PutRelationPathSet(k, v, this.version);
219 prp.process(edgeIngestor);