Added mac-address attribute to p-interface
[aai/aai-common.git] / aai-core / src / main / java / org / openecomp / aai / dbmodel / DbEdgeRulesConverter.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * org.openecomp.aai
4  * ================================================================================
5  * Copyright (C) 2017 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
21 package org.openecomp.aai.dbmodel;
22
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.OutputStreamWriter;
28 import java.io.Writer;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34
35 import org.openecomp.aai.introspection.Version;
36
37 import com.google.common.collect.Multimap;
38
39 import freemarker.template.Configuration;
40 import freemarker.template.Template;
41 import freemarker.template.TemplateException;
42 import freemarker.template.TemplateExceptionHandler;
43
44 /**
45  * Converts the old DbEdgeRules multimap to new json format
46  */
47 public class DbEdgeRulesConverter {
48         private static final int LABEL = 0;
49         private static final int DIRECTION = 1;
50         private static final int MULTIPLICITY = 2;
51         private static final int ISPARENT = 3;
52         private static final int USESRESOURCE = 4;
53         private static final int HASDELTARGET = 5;
54         private static final int SVCINFRA = 6;
55         
56         private Configuration config = new Configuration();
57         private Template template;
58         private String destDirectory;
59         private FileOutputStream writeStream;
60         
61         public DbEdgeRulesConverter(){ /*pretty much just so I can test functionality without dealing with template setup*/ }
62         
63         public DbEdgeRulesConverter(String destinationDir) {
64                 destDirectory = destinationDir;
65                 try {
66                         setup(destinationDir);
67                 } catch (IOException e) {
68                         e.printStackTrace();
69                 }
70         }
71         
72         /**
73          * Sets up the freemarker template and the directory to be written to. Run this once before
74          * doing any converting, does not need to be run per file generated (unless you want different directories for each file).
75          * 
76          * @param destinationDir - String of the path to the directory where you want the new format files written to,
77          *                                                      relative to aai-core/
78          * @throws IOException if it can't find the template loading directory or the template file itself
79          */
80         public void setup(String destinationDir) throws IOException {
81                 config.setDirectoryForTemplateLoading(new File("src/main/resources/dbedgerules/conversion"));
82                 config.setDefaultEncoding("UTF-8");
83                 config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
84                 template = config.getTemplate("edgerulesTemplate.ftlh");
85                 
86                 File destination = new File(destinationDir);
87                 if (!destination.exists()) {
88                         destination.mkdir();
89                 }
90         }
91         
92         /**
93          * Converts the given DbEdgeRules multimap representation into a json file of the new format.
94          * 
95          * @param rules - a Multimap<String, String> of the old DbEdgeRules format
96          * @param writer - writes to the output file (designate that file when you instantiate the writer)
97          */
98         public void convert(Multimap<String, String> rules, Writer writer) {
99                 
100                 List<EdgeRuleBean> rulesToWrite = new ArrayList<>();
101                 for (Entry<String, String> rule : rules.entries()) {
102                         rulesToWrite.add(extractData(rule));
103                 }
104                 Map<String, List<EdgeRuleBean>> wrappedRules = new HashMap<>();
105                 wrappedRules.put("wrappedRules", rulesToWrite);
106                 try {
107                         template.process(wrappedRules, writer);
108                 } catch (TemplateException e) {
109                         System.out.println("Something went wrong when trying to combine the data and the template");
110                         e.printStackTrace();
111                 } catch (IOException e) {
112                         System.out.println("There was a problem writing to the output file");
113                         e.printStackTrace();
114                 } 
115         }
116         
117         /**
118          * Extracts the pieces of information that go in each field of the new json format from the old
119          * DbEdgeRules format.
120          * 
121          * @param rule - one <String, String> entry from the DbEdgeRules multimap representation
122          *              Takes the form <"from-node|to-node", "label,direction,multiplicity,isParent,usesResource,hasDelTarget,svc-infra">
123          * @return EdgeRuleBean with the pieces of information the template needs, in a format the template can understand
124          */
125         public EdgeRuleBean extractData(Entry<String, String> rule){
126                 EdgeRuleBean data = new EdgeRuleBean();
127                 
128                 String oldName = rule.getKey();
129                 String[] nodes = oldName.split("\\|");
130                 data.setFrom(nodes[0]);
131                 data.setTo(nodes[1]);
132                 
133                 String oldSpecs = rule.getValue();
134                 String[] specs = oldSpecs.split(",");
135                 data.setLabel(specs[LABEL]);
136                 data.setDirection(specs[DIRECTION]);
137                 data.setMultiplicity(specs[MULTIPLICITY]);
138                 data.setParent(specs[ISPARENT]);
139                 data.setUsesResource(specs[USESRESOURCE]);
140                 data.setHasDelTarget(specs[HASDELTARGET]);
141                 data.setSvcInfra(specs[SVCINFRA]);
142                 
143                 return data;
144         }
145         
146         private Multimap<String, String> getEdgeRules(Version v) {
147                 try {
148                         Class <?> dbEdgeRules;
149                         //use reflection to get the corresponding DbEdgeRules class
150                         //need this weird if-else bc current version doesn't sit in a v.gen subdirectory
151                         if (Version.isLatest(v)) {
152                                         dbEdgeRules = Class.forName("org.openecomp.aai.dbmodel.DbEdgeRules");
153                         } else {
154                                 dbEdgeRules = Class.forName("org.openecomp.aai.dbmodel." + v + ".gen.DbEdgeRules");
155                         }
156                         
157                         @SuppressWarnings("unchecked")
158                         Multimap<String, String> rules = (Multimap<String,String>)dbEdgeRules.getDeclaredField("EdgeRules").get(null);
159                         
160                         return rules;
161                 } catch (ClassNotFoundException e) {
162                         System.out.println("could not find DbEdgeRules class for version " + v);
163                         e.printStackTrace();
164                         return null;
165                 } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
166                         System.out.println("Something went wrong trying to retrieve the rules");
167                         e.printStackTrace();
168                         return null;
169                 }
170         }
171         
172         private Writer buildOutputWriter(Version v) {
173                 try {
174                         File output = new File(destDirectory + "DbEdgeRules_" + v + ".json");
175                         writeStream = new FileOutputStream(output);
176                         return new OutputStreamWriter(writeStream);
177                 } catch (FileNotFoundException e) {
178                         e.printStackTrace();
179                         return null;
180                 }
181         }
182         
183         /**
184          * Runs all the conversion steps for the specified version.
185          * 
186          * @param v
187          */
188         public void convertVersion(Version v) {
189                 try {
190                         Multimap<String, String> rules = getEdgeRules(v);
191                         if (rules == null) { //something went wrong, we've already logged it in the helper so just stop execution
192                                 return;
193                         }
194                         
195                         Writer writer = buildOutputWriter(v); 
196                         if (writer == null) { //something went wrong, we've already logged it in the helper so just stop execution
197                                 return;
198                         }
199                         convert(rules, writer);
200                         
201                         writer.close();
202                         writeStream.close();
203                 } catch (IOException e) {
204                         System.out.println("Something went wrong closing the writer/writestream");
205                         e.printStackTrace();
206                 }
207         }
208         
209         /**
210          * Runs the converter for each DbEdgeRules version currently supported (2, 7, 8, 9, and 10)
211          * 
212          * @param args - none actually
213          */
214         public static void main(String[] args) {
215                 String destDirectory = "src/main/resources/dbedgerules/";
216                 DbEdgeRulesConverter dberConverter = new DbEdgeRulesConverter(destDirectory);
217                 
218                 for (Version v : Version.values()) {
219                         dberConverter.convertVersion(v);
220                 }
221         }
222 }