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.util.ArrayList;
25 import java.util.HashMap;
27 import java.util.SortedSet;
28 import java.util.TreeSet;
30 import org.apache.commons.text.similarity.LevenshteinDistance;
31 import org.onap.aai.setup.SchemaVersion;
32 import org.onap.aai.config.SpringContextAware;
33 import org.onap.aai.edges.EdgeIngestor;
34 import org.onap.aai.edges.EdgeRule;
35 import org.onap.aai.edges.EdgeRuleQuery;
36 import org.onap.aai.util.GenerateXsd;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
40 import com.google.common.collect.Multimap;
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>();
46 public static void add(String useOpId, String path) {
47 putRelationPaths.put(useOpId, path);
52 SchemaVersion version;
53 protected ArrayList<String> relations = new ArrayList<String>();
54 String objectName = "";
56 public PutRelationPathSet(SchemaVersion v) {
60 public PutRelationPathSet(String opId, String path, SchemaVersion v) {
61 this.apiPath = path.replace("/relationship-list/relationship", "");
64 objectName = DeleteOperation.deletePaths.get(apiPath);
65 logger.debug("II-apiPath: "+apiPath+"\nPath: "+path+"\nopId="+opId+"\nobjectName="+objectName);
67 private void process(EdgeIngestor edgeIngestor) {
68 this.ei = edgeIngestor;
71 this.writeRelationsFile();
74 private void toRelations() {
75 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
76 logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName);
79 EdgeRuleQuery q1 = new EdgeRuleQuery.Builder("ToOnly",objectName).version(version).build();
80 Multimap<String, EdgeRule> results = ei.getRules(q1);
81 relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
82 SortedSet<String> ss=new TreeSet<String>(results.keySet());
83 for(String key : ss) {
84 results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } );
86 } catch(Exception e) {
87 logger.debug("objectName: "+objectName+"\n"+e);
90 private String selectedRelation(EdgeRule rule) {
91 String selectedRelation = "";
92 EdgeDescription ed = new EdgeDescription(rule);
93 logger.debug(ed.getRuleKey()+"Type="+ed.getType());
94 String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
96 if(ed.getType() == EdgeDescription.LineageType.UNRELATED) {
97 String selectObj = getUnrelatedObjectPaths(obj, apiPath);
98 logger.debug("SelectedObj"+selectObj);
99 selectedRelation = formatObjectRelationSet(obj,selectObj);
100 logger.trace("ObjectRelationSet"+selectedRelation);
102 String selectObj = getKinObjectPath(obj, apiPath);
103 logger.debug("SelectedObj"+selectObj);
104 selectedRelation = formatObjectRelation(obj,selectObj);
105 logger.trace("ObjectRelationSet"+selectedRelation);
107 return selectedRelation;
110 private void fromRelations() {
111 logger.debug("“comment”: “Valid FROM Relations that can be added”");
114 EdgeRuleQuery q1 = new EdgeRuleQuery.Builder(objectName,"FromOnly").version(version).build();
115 Multimap<String, EdgeRule> results = ei.getRules(q1);
116 relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
117 SortedSet<String> ss=new TreeSet<String>(results.keySet());
118 for(String key : ss) {
119 results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } );
121 } catch(Exception e) {
122 logger.debug("objectName: "+objectName+"\n"+e);
125 private void writeRelationsFile() {
126 File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString()+"/"+opId.replace("RelationshipListRelationship", "") + ".json");
128 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
129 FileOutputStream fop = null;
131 if (!examplefilePath.exists()) {
132 examplefilePath.getParentFile().mkdirs();
133 examplefilePath.createNewFile();
135 fop = new FileOutputStream(examplefilePath);
136 } catch(Exception e) {
141 if(relations.size() > 0) {fop.write("[\n".getBytes());}
142 fop.write(String.join(",\n", relations).getBytes());
143 if(relations.size() > 0) {fop.write("\n]\n".getBytes());}
146 } catch (Exception e) {
150 logger.debug(String.join(",\n", relations));
154 private static String formatObjectRelationSet(String obj, String selectObj) {
155 StringBuffer pathSb = new StringBuffer();
156 String[] paths = selectObj.split("[|]");
157 for (String s: paths) {
158 logger.trace("SelectOBJ"+s);
159 pathSb.append(formatObjectRelation(obj, s)+",\n");
161 pathSb.deleteCharAt(pathSb.length()-2);
162 return pathSb.toString();
165 private static String formatObjectRelation(String obj, String selectObj) {
166 StringBuffer pathSb = new StringBuffer();
167 pathSb.append("{\n");
168 pathSb.append("\"related-to\" : \""+obj+"\",\n");
169 pathSb.append("\"related-link\" : \""+selectObj+"\"\n");
171 return pathSb.toString();
174 private static String getKinObjectPath(String obj, String apiPath) {
175 LevenshteinDistance proximity = new LevenshteinDistance();
176 String targetPath = "";
177 int targetScore = Integer.MAX_VALUE;
178 int targetMaxScore = 0;
179 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
180 if(p.getValue().equals(obj)) {
181 targetScore = (targetScore >= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore;
182 targetPath = (targetScore >= proximity.apply(apiPath, p.getKey())) ? p.getKey() : targetPath;
183 targetMaxScore = (targetMaxScore <= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore;
184 logger.trace(proximity.apply(apiPath, p.getKey())+":"+p.getKey());
185 logger.trace(proximity.apply(apiPath, p.getKey())+":"+apiPath);
191 private static String getUnrelatedObjectPaths(String obj, String apiPath) {
192 String targetPath = "";
193 logger.trace("Obj:"+obj +"\n" + apiPath);
194 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
195 if(p.getValue().equals(obj)) {
196 logger.trace("p.getvalue:"+p.getValue()+"p.getkey:"+p.getKey());
197 targetPath += ((targetPath.length() == 0 ? "" : "|") + p.getKey());
198 logger.trace("Match:"+apiPath +"\n" + targetPath);
204 public void generateRelations(EdgeIngestor edgeIngestor) {
205 putRelationPaths.forEach((k,v)->{
206 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"));
207 logger.debug("apiPath(Operation): "+v);
208 logger.debug("Target object: "+v.replace("/relationship-list/relationship", ""));
209 logger.debug("Relations: ");
210 PutRelationPathSet prp = new PutRelationPathSet(k, v, this.version);
211 prp.process(edgeIngestor);