Move the aai-schema, annotations and
[aai/schema-service.git] / aai-schema-gen / src / main / java / org / onap / aai / schemagen / 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.schemagen.genxsd;
21
22 import com.google.common.collect.Multimap;
23 import org.apache.commons.text.similarity.LevenshteinDistance;
24 import org.onap.aai.edges.EdgeIngestor;
25 import org.onap.aai.edges.EdgeRule;
26 import org.onap.aai.edges.EdgeRuleQuery;
27 import org.onap.aai.setup.SchemaVersion;
28 import org.onap.aai.schemagen.GenerateXsd;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import java.io.File;
33 import java.io.FileOutputStream;
34 import java.io.IOException;
35 import java.util.*;
36
37 public class PutRelationPathSet {
38         EdgeIngestor ei;
39         private static final Logger logger = LoggerFactory.getLogger("PutRelationPathSet.class");
40         protected static HashMap<String, String> putRelationPaths = new HashMap<String, String>();
41         public static void add(String useOpId, String path) {
42                 putRelationPaths.put(useOpId, path);
43         }
44
45         String apiPath;
46         String opId;
47         SchemaVersion version;
48         protected ArrayList<String> relations = new ArrayList<String>();
49         String objectName = "";
50
51         public PutRelationPathSet(SchemaVersion v) {
52                 this.version = v;
53         }
54
55         public PutRelationPathSet(String opId, String path, SchemaVersion v) {
56                 this.apiPath = path.replace("/relationship-list/relationship", "");
57                 this.opId = opId;
58                 this.version = v;
59                 objectName = DeleteOperation.deletePaths.get(apiPath);
60                 logger.debug("II-apiPath: "+apiPath+"\nPath: "+path+"\nopId="+opId+"\nobjectName="+objectName);
61         }
62         private void process(EdgeIngestor edgeIngestor) {
63                 this.ei =  edgeIngestor;
64                 this.toRelations();
65                 this.fromRelations();
66                 this.writeRelationsFile();
67
68         }
69         private void toRelations() {
70                 logger.debug("{“comment”: “Valid TO Relations that can be added”},");
71                 logger.debug("apiPath: "+apiPath+"\nopId="+opId+"\nobjectName="+objectName);
72                 try {
73
74                         EdgeRuleQuery q1 = new EdgeRuleQuery.Builder("ToOnly",objectName).version(version).build();
75                         Multimap<String, EdgeRule> results = ei.getRules(q1);
76                         relations.add("{\"comment\": \"Valid TO Relations that can be added\"}\n");
77                         SortedSet<String> ss=new TreeSet<String>(results.keySet());
78                         for(String key : ss) {
79                                 results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } );
80                         }
81                 } catch(Exception e) {
82                         logger.debug("objectName: "+objectName+"\n"+e);
83                 }
84         }
85         private String selectedRelation(EdgeRule rule) {
86                 String selectedRelation = "";
87                 EdgeDescription ed = new EdgeDescription(rule);
88                 logger.debug(ed.getRuleKey()+"Type="+ed.getType());
89                 String obj = ed.getRuleKey().replace(objectName,"").replace("|","");
90
91                 if(ed.getType() == EdgeDescription.LineageType.UNRELATED) {
92                         String selectObj = getUnrelatedObjectPaths(obj, apiPath);
93                         logger.debug("SelectedObj"+selectObj);
94                         selectedRelation = formatObjectRelationSet(obj,selectObj);
95                         logger.trace("ObjectRelationSet"+selectedRelation);
96                 } else {
97                         String selectObj = getKinObjectPath(obj, apiPath);
98                         logger.debug("SelectedObj"+selectObj);
99                         selectedRelation = formatObjectRelation(obj,selectObj);
100                         logger.trace("ObjectRelationSet"+selectedRelation);
101                 }
102                 return selectedRelation;
103         }
104
105         private void fromRelations() {
106                 logger.debug("“comment”: “Valid FROM Relations that can be added”");
107                 try {
108
109                         EdgeRuleQuery q1 = new EdgeRuleQuery.Builder(objectName,"FromOnly").version(version).build();
110                         Multimap<String, EdgeRule> results = ei.getRules(q1);
111                         relations.add("{\"comment\": \"Valid FROM Relations that can be added\"}\n");
112                         SortedSet<String> ss=new TreeSet<String>(results.keySet());
113                         for(String key : ss) {
114                                 results.get(key).stream().filter((i) -> (! i.isPrivateEdge())).forEach((i) ->{ String rel = selectedRelation(i); relations.add(rel); logger.debug("Relation added: "+rel); } );
115                         }
116                 } catch(Exception e) {
117                         logger.debug("objectName: "+objectName+"\n"+e);
118                 }
119         }
120         private void writeRelationsFile() {
121                 File examplefilePath = new File(GenerateXsd.getYamlDir() + "/relations/" + version.toString()+"/"+opId.replace("RelationshipListRelationship", "") + ".json");
122
123                 logger.debug(String.join("exampleFilePath: ", examplefilePath.toString()));
124                 FileOutputStream fop = null;
125                 try {
126                         if (!examplefilePath.exists()) {
127                                 examplefilePath.getParentFile().mkdirs();
128                                 examplefilePath.createNewFile();
129                         }
130                         fop = new FileOutputStream(examplefilePath);
131                 } catch(Exception e) {
132                         e.printStackTrace();
133                         return;
134                 }
135                 try {
136                         if(relations.size() > 0) {fop.write("[\n".getBytes());}
137                         fop.write(String.join(",\n", relations).getBytes());
138                         if(relations.size() > 0) {fop.write("\n]\n".getBytes());}
139                         fop.flush();
140                         fop.close();
141                 } catch (Exception e) {
142                         e.printStackTrace();
143                         return;
144                 }
145                 finally{
146                         try {
147                                 fop.close();
148                         } catch (IOException e) {
149                                 e.printStackTrace();
150                         }
151                 }
152                 logger.debug(String.join(",\n", relations));
153                 return;
154         }
155
156         private static String formatObjectRelationSet(String obj, String selectObj) {
157                 StringBuffer pathSb = new StringBuffer();
158                 String[] paths = selectObj.split("[|]");
159                 for (String s: paths) {
160                         logger.trace("SelectOBJ"+s);
161                         pathSb.append(formatObjectRelation(obj, s)+",\n");
162                 }
163                 pathSb.deleteCharAt(pathSb.length()-2);
164                 return pathSb.toString();
165         }
166
167         private static String formatObjectRelation(String obj, String selectObj) {
168                 StringBuffer pathSb = new StringBuffer();
169                 pathSb.append("{\n");
170                 pathSb.append("\"related-to\" : \""+obj+"\",\n");
171                 pathSb.append("\"related-link\" : \""+selectObj+"\"\n");
172                 pathSb.append("}");
173                 return pathSb.toString();
174         }
175
176         private static String getKinObjectPath(String obj, String apiPath) {
177                 LevenshteinDistance proximity = new LevenshteinDistance();
178                 String targetPath = "";
179                 int targetScore = Integer.MAX_VALUE;
180                 int targetMaxScore = 0;
181                 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
182                                 if(p.getValue().equals(obj)) {
183                                         targetScore = (targetScore >= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore;
184                                         targetPath = (targetScore >= proximity.apply(apiPath, p.getKey())) ? p.getKey() : targetPath;
185                                         targetMaxScore = (targetMaxScore <= proximity.apply(apiPath, p.getKey())) ? proximity.apply(apiPath, p.getKey()) : targetScore;
186                                         logger.trace(proximity.apply(apiPath, p.getKey())+":"+p.getKey());
187                                         logger.trace(proximity.apply(apiPath, p.getKey())+":"+apiPath);
188                                 }
189                 }
190                 return targetPath;
191         }
192
193         private static String getUnrelatedObjectPaths(String obj, String apiPath) {
194                 String targetPath = "";
195                 logger.trace("Obj:"+obj +"\n" + apiPath);
196                 for (Map.Entry<String, String> p : DeleteOperation.deletePaths.entrySet()) {
197                                 if(p.getValue().equals(obj)) {
198                                         logger.trace("p.getvalue:"+p.getValue()+"p.getkey:"+p.getKey());
199                                         targetPath +=  ((targetPath.length() == 0 ? "" : "|") + p.getKey());
200                                         logger.trace("Match:"+apiPath +"\n" + targetPath);
201                                 }
202                 }
203                 return targetPath;
204         }
205
206         public void generateRelations(EdgeIngestor edgeIngestor) {
207                 putRelationPaths.forEach((k,v)->{
208                         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"));
209                         logger.debug("apiPath(Operation): "+v);
210                         logger.debug("Target object: "+v.replace("/relationship-list/relationship", ""));
211                         logger.debug("Relations: ");
212                         PutRelationPathSet prp = new PutRelationPathSet(k, v, this.version);
213                         prp.process(edgeIngestor);
214                 });
215         }
216
217 }
218