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