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