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