ca87bda9662bbea01d64aee2492be9fc95fb054f
[dcaegen2/platform.git] / mod / genprocessor / src / main / java / org / onap / dcae / genprocessor / ProcessorBuilder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * ============LICENSE_END=========================================================
17  */
18 package org.onap.dcae.genprocessor;
19
20 import javassist.CannotCompileException;
21 import javassist.CtClass;
22 import javassist.CtMethod;
23 import javassist.bytecode.AnnotationsAttribute;
24 import javassist.bytecode.ClassFile;
25 import javassist.bytecode.ConstPool;
26 import javassist.bytecode.annotation.Annotation;
27 import javassist.bytecode.annotation.ArrayMemberValue;
28 import javassist.bytecode.annotation.MemberValue;
29 import javassist.bytecode.annotation.StringMemberValue;
30
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.stream.Collectors;
34
35 import org.apache.commons.text.StringEscapeUtils;
36 import org.apache.nifi.annotation.documentation.CapabilityDescription;
37 import org.apache.nifi.annotation.documentation.Tags;
38
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public class ProcessorBuilder {
43
44     static final Logger LOG = LoggerFactory.getLogger(ProcessBuilder.class);
45
46     public static class ProcessorBuilderError extends RuntimeException {
47         public ProcessorBuilderError(Throwable e) {
48             super("Error while generating DCAEProcessor", e);
49         }
50     }
51
52     private static Annotation createAnnotationDescription(String description, ConstPool constPool) {
53         // https://www.codota.com/code/java/packages/javassist.bytecode showed me that
54         // the constructor
55         // adds a UTF8 object thing so I'm guessing that the index value when doing
56         // addMemberValue
57         // should match that of the newly added object otherwise you get a nullpointer
58         Annotation annDescrip = new Annotation(CapabilityDescription.class.getName(), constPool);
59         // Tried to use the index version of addMemberValue with index of
60         // constPool.getSize()-1
61         // but didn't work
62         annDescrip.addMemberValue("value", new StringMemberValue(description, constPool));
63         return annDescrip;
64     }
65
66     private static Annotation createAnnotationTags(String[] tags, ConstPool constPool) {
67         Annotation annTags = new Annotation(Tags.class.getName(), constPool);
68         ArrayMemberValue mv = new ArrayMemberValue(constPool);
69
70         List<MemberValue> elements = new ArrayList<MemberValue>();
71         for (String tag : tags) {
72             elements.add(new StringMemberValue(tag, constPool));
73         }
74
75         mv.setValue(elements.toArray(new MemberValue[elements.size()]));
76         // Tried to use the index version of addMemberValue with index of
77         // constPool.getSize()-1
78         // but didn't work
79         annTags.addMemberValue("value", mv);
80         return annTags;
81     }
82
83     public static String[] createTags(CompSpec compSpec) {
84         List<String> tags = new ArrayList<>();
85         tags.add("DCAE");
86
87         // TODO: Need to source type from spec
88         if (compSpec.name.toLowerCase().contains("collector")) {
89             tags.add("collector");
90         }
91
92         if (!compSpec.getPublishes().isEmpty()) {
93             tags.add("publisher");
94         }
95
96         if (!compSpec.getSubscribes().isEmpty()) {
97             tags.add("subscriber");
98         }
99
100         String[] tagArray = new String[tags.size()];
101         return tags.toArray(tagArray);
102     }
103
104     public static void addAnnotationsProcessor(CtClass target, String description, String[] tags) {
105         ClassFile ccFile = target.getClassFile();
106         ConstPool constPool = ccFile.getConstPool();
107
108         AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
109         attr.addAnnotation(createAnnotationDescription(description, constPool));
110         attr.addAnnotation(createAnnotationTags(tags, constPool));
111
112         ccFile.addAttribute(attr);
113     }
114
115     private static void addMethod(CtClass target, String methodCode) {
116         try {
117             CtMethod method = CtMethod.make(methodCode, target);
118             target.addMethod(method);
119         } catch (CannotCompileException e) {
120             LOG.error(String.format("Issue with this code:\n%s", methodCode));
121             LOG.error(e.toString(), e);
122             throw new ProcessorBuilderError(e);
123         }
124     }
125
126     private static String createCodeGetter(String methodName, String returnValue) {
127         return String.format("public java.lang.String get%s() { return \"%s\"; }", methodName, returnValue);
128     }
129
130     public static void setComponentPropertyGetters(CtClass target, Comp comp) {
131         addMethod(target, createCodeGetter("Name", comp.compSpec.name));
132         addMethod(target, createCodeGetter("Version", comp.compSpec.version));
133         addMethod(target, createCodeGetter("ComponentId", comp.id));
134         addMethod(target, createCodeGetter("ComponentUrl", comp.selfUrl));
135     }
136
137     private static String convertParameterToCode(CompSpec.Parameter param) {
138         StringBuilder sb = new StringBuilder("props.add(new org.apache.nifi.components.PropertyDescriptor.Builder()");
139         sb.append(String.format(".name(\"%s\")", param.name));
140         sb.append(String.format(".displayName(\"%s\")", param.name));
141         sb.append(String.format(".description(\"%s\")", StringEscapeUtils.escapeJava(param.description)));
142         sb.append(String.format(".defaultValue(\"%s\")", StringEscapeUtils.escapeJava(param.value)));
143         sb.append(".build());");
144         return sb.toString();
145     }
146
147     private static String createCodePropertyDescriptors(CompSpec compSpec) {
148         List<String> linesParams = compSpec.parameters.stream().map(p -> convertParameterToCode(p)).collect(Collectors.toList());
149
150         // NOTE: Generics are only partially supported https://www.javassist.org/tutorial/tutorial3.html#generics
151         String[] lines = new String[] {"protected java.util.List buildSupportedPropertyDescriptors() {"
152             , "java.util.List props = new java.util.LinkedList();"
153             , String.join("\n", linesParams.toArray(new String[linesParams.size()]))
154             , "return props; }"
155         };
156
157         return String.join("\n", lines);
158     }
159
160     public static void setProcessorPropertyDescriptors(CtClass target, CompSpec compSpec) {
161         addMethod(target, createCodePropertyDescriptors(compSpec));
162     }
163
164     private static String createRelationshipName(CompSpec.Connection connection, String direction) {
165         // TODO: Revisit this name thing ugh
166         return String.format("%s:%s:%s:%s:%s",
167             direction, connection.format.toLowerCase(), connection.version, connection.type, connection.configKey);
168     }
169
170     private static String convertConnectionToCode(CompSpec.Connection connection, String direction) {
171         StringBuilder sb = new StringBuilder("rels.add(new org.apache.nifi.processor.Relationship.Builder()");
172         sb.append(String.format(".name(\"%s\")", createRelationshipName(connection, direction)));
173         sb.append(".build());");
174         return sb.toString();
175     }
176
177     private static String createCodeRelationships(CompSpec compSpec) {
178         List<String> linesPubs = compSpec.getPublishes().stream().map(c -> convertConnectionToCode(c, "publishes")).collect(Collectors.toList());
179         List<String> linesSubs = compSpec.getSubscribes().stream().map(c -> convertConnectionToCode(c, "subscribes")).collect(Collectors.toList());
180
181         String [] lines = new String[] {"protected java.util.Set buildRelationships() {"
182             , "java.util.Set rels = new java.util.HashSet();"
183             , String.join("\n", linesPubs.toArray(new String[linesPubs.size()]))
184             , String.join("\n", linesSubs.toArray(new String[linesSubs.size()]))
185             , "return rels; }"
186         };
187
188         return String.join("\n", lines);
189     }
190
191     public static void setProcessorRelationships(CtClass target, CompSpec compSpec) {
192         addMethod(target, createCodeRelationships(compSpec));
193     }
194
195 }