d6eaa5c975a3f563ef04767251ae17b07597aa1b
[aai/aai-common.git] / aai-core / src / main / java / org / onap / aai / util / genxsd / PutRelationPathSet.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 package org.onap.aai.util.genxsd;
21
22 import java.io.File;
23 import java.io.FileOutputStream;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.SortedSet;
28 import java.util.TreeSet;
29
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;
39
40 import com.google.common.collect.Multimap;
41
42 public class PutRelationPathSet {
43         EdgeIngestor ei;
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);
48         }
49         
50         String apiPath;
51         String opId;
52         SchemaVersion version;
53         protected ArrayList<String> relations = new ArrayList<String>();
54         String objectName = "";
55         
56         public PutRelationPathSet(SchemaVersion v) {
57                 this.version = v;
58         }
59
60         public PutRelationPathSet(String opId, String path, SchemaVersion v) {
61                 this.apiPath = path.replace("/relationship-list/relationship", "");
62                 this.opId = opId;
63                 this.version = v;
64                 objectName = DeleteOperation.deletePaths.get(apiPath);          
65                 logger.debug("II-apiPath: "+apiPath+"\nPath: "+path+"\nopId="+opId+"\nobjectName="+objectName);
66         }
67         private void process(EdgeIngestor edgeIngestor) {
68                 this.ei =  edgeIngestor;
69                 this.toRelations();
70                 this.fromRelations();
71                 this.writeRelationsFile();
72
73         }
74         private void toRelations() {
75                 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
76                 logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName);
77                 try {
78
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); } );
85                         }
86                 } catch(Exception e) {
87                         logger.debug("objectName: "+objectName+"\n"+e);
88                 }
89         }
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("|","");
95                 
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);
101                 } else {
102                         String selectObj = getKinObjectPath(obj, apiPath);
103                         logger.debug("SelectedObj"+selectObj);
104                         selectedRelation = formatObjectRelation(obj,selectObj);
105                         logger.trace("ObjectRelationSet"+selectedRelation);
106                 }
107                 return selectedRelation;
108         }
109         
110         private void fromRelations() {
111                 logger.debug("“comment”: “Valid FROM Relations that can be added”");
112                 try {
113
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); } );
120                         }
121                 } catch(Exception e) {
122                         logger.debug("objectName: "+objectName+"\n"+e);
123                 }
124         }
125         private void writeRelationsFile() {
126                 File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString()+"/"+opId.replace("RelationshipListRelationship", "") + ".json");
127
128                 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
129                 FileOutputStream fop = null;
130                 try {
131                         if (!examplefilePath.exists()) {
132                                 examplefilePath.getParentFile().mkdirs();
133                                 examplefilePath.createNewFile();
134                         }
135                         fop = new FileOutputStream(examplefilePath);
136                 } catch(Exception e) {
137                         e.printStackTrace();
138                         return;
139                 }
140                 try {
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());}
144                         fop.flush();
145                         fop.close();
146                 } catch (Exception e) {
147                         e.printStackTrace();
148                         return;
149                 }
150                 logger.debug(String.join(",\n", relations));
151                 return;
152         }
153         
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");
160                 }
161                 pathSb.deleteCharAt(pathSb.length()-2);
162                 return pathSb.toString();
163         }
164
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");
170                 pathSb.append("}");
171                 return pathSb.toString();
172         }
173
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);
186                                 }
187                 }
188                 return targetPath;
189         }
190
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);
199                                 }
200                 }
201                 return targetPath;
202         }
203         
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);
212                 });
213         }
214
215 }
216