0b0fd946288bd329ab6d0321e6c3d793a75a4756
[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.io.IOException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.SortedSet;
29 import java.util.TreeSet;
30
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;
40
41 import com.google.common.collect.Multimap;
42
43 public class PutRelationPathSet {
44         EdgeIngestor ei;
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);
49         }
50         
51         String apiPath;
52         String opId;
53         SchemaVersion version;
54         protected ArrayList<String> relations = new ArrayList<String>();
55         String objectName = "";
56         
57         public PutRelationPathSet(SchemaVersion v) {
58                 this.version = v;
59         }
60
61         public PutRelationPathSet(String opId, String path, SchemaVersion v) {
62                 this.apiPath = path.replace("/relationship-list/relationship", "");
63                 this.opId = opId;
64                 this.version = v;
65                 objectName = DeleteOperation.deletePaths.get(apiPath);          
66                 logger.debug("II-apiPath: "+apiPath+"\nPath: "+path+"\nopId="+opId+"\nobjectName="+objectName);
67         }
68         private void process(EdgeIngestor edgeIngestor) {
69                 this.ei =  edgeIngestor;
70                 this.toRelations();
71                 this.fromRelations();
72                 this.writeRelationsFile();
73
74         }
75         private void toRelations() {
76                 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
77                 logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName);
78                 try {
79
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); } );
86                         }
87                 } catch(Exception e) {
88                         logger.debug("objectName: "+objectName+"\n"+e);
89                 }
90         }
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("|","");
96                 
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);
102                 } else {
103                         String selectObj = getKinObjectPath(obj, apiPath);
104                         logger.debug("SelectedObj"+selectObj);
105                         selectedRelation = formatObjectRelation(obj,selectObj);
106                         logger.trace("ObjectRelationSet"+selectedRelation);
107                 }
108                 return selectedRelation;
109         }
110         
111         private void fromRelations() {
112                 logger.debug("“comment”: “Valid FROM Relations that can be added”");
113                 try {
114
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); } );
121                         }
122                 } catch(Exception e) {
123                         logger.debug("objectName: "+objectName+"\n"+e);
124                 }
125         }
126         private void writeRelationsFile() {
127                 File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString()+"/"+opId.replace("RelationshipListRelationship", "") + ".json");
128
129                 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
130                 FileOutputStream fop = null;
131                 try {
132                         if (!examplefilePath.exists()) {
133                                 examplefilePath.getParentFile().mkdirs();
134                                 examplefilePath.createNewFile();
135                         }
136                         fop = new FileOutputStream(examplefilePath);
137                 } catch(Exception e) {
138                         e.printStackTrace();
139                         return;
140                 }
141                 finally{
142                         try {
143                                 fop.close();
144                         } catch (IOException e) {
145                                 e.printStackTrace();
146                         }
147                 }
148                 try {
149                         if(relations.size() > 0) {fop.write("[\n".getBytes());}
150                         fop.write(String.join(",\n", relations).getBytes());
151                         if(relations.size() > 0) {fop.write("\n]\n".getBytes());}
152                         fop.flush();
153                         fop.close();
154                 } catch (Exception e) {
155                         e.printStackTrace();
156                         return;
157                 }
158                 logger.debug(String.join(",\n", relations));
159                 return;
160         }
161         
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");
168                 }
169                 pathSb.deleteCharAt(pathSb.length()-2);
170                 return pathSb.toString();
171         }
172
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");
178                 pathSb.append("}");
179                 return pathSb.toString();
180         }
181
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);
194                                 }
195                 }
196                 return targetPath;
197         }
198
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);
207                                 }
208                 }
209                 return targetPath;
210         }
211         
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);
220                 });
221         }
222
223 }
224