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
9 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
18 package org.onap.dcae.genprocessor;
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;
31 import java.util.ArrayList;
32 import java.util.List;
33 import java.util.stream.Collectors;
35 import org.apache.commons.text.StringEscapeUtils;
36 import org.apache.nifi.annotation.documentation.CapabilityDescription;
37 import org.apache.nifi.annotation.documentation.Tags;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public class ProcessorBuilder {
44 static final Logger LOG = LoggerFactory.getLogger(ProcessBuilder.class);
46 public static class ProcessorBuilderError extends RuntimeException {
47 public ProcessorBuilderError(Throwable e) {
48 super("Error while generating DCAEProcessor", e);
52 private static Annotation createAnnotationDescription(String description, ConstPool constPool) {
53 // https://www.codota.com/code/java/packages/javassist.bytecode showed me that
55 // adds a UTF8 object thing so I'm guessing that the index value when doing
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
62 annDescrip.addMemberValue("value", new StringMemberValue(description, constPool));
66 private static Annotation createAnnotationTags(String[] tags, ConstPool constPool) {
67 Annotation annTags = new Annotation(Tags.class.getName(), constPool);
68 ArrayMemberValue mv = new ArrayMemberValue(constPool);
70 List<MemberValue> elements = new ArrayList<MemberValue>();
71 for (String tag : tags) {
72 elements.add(new StringMemberValue(tag, constPool));
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
79 annTags.addMemberValue("value", mv);
83 public static String[] createTags(CompSpec compSpec) {
84 List<String> tags = new ArrayList<>();
87 // TODO: Need to source type from spec
88 if (compSpec.name.toLowerCase().contains("collector")) {
89 tags.add("collector");
92 if (!compSpec.getPublishes().isEmpty()) {
93 tags.add("publisher");
96 if (!compSpec.getSubscribes().isEmpty()) {
97 tags.add("subscriber");
100 String[] tagArray = new String[tags.size()];
101 return tags.toArray(tagArray);
104 public static void addAnnotationsProcessor(CtClass target, String description, String[] tags) {
105 ClassFile ccFile = target.getClassFile();
106 ConstPool constPool = ccFile.getConstPool();
108 AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
109 attr.addAnnotation(createAnnotationDescription(description, constPool));
110 attr.addAnnotation(createAnnotationTags(tags, constPool));
112 ccFile.addAttribute(attr);
115 private static void addMethod(CtClass target, String methodCode) {
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);
126 private static String createCodeGetter(String methodName, String returnValue) {
127 return String.format("public java.lang.String get%s() { return \"%s\"; }", methodName, returnValue);
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));
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();
147 private static String createCodePropertyDescriptors(CompSpec compSpec) {
148 List<String> linesParams = compSpec.parameters.stream().map(p -> convertParameterToCode(p)).collect(Collectors.toList());
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()]))
157 return String.join("\n", lines);
160 public static void setProcessorPropertyDescriptors(CtClass target, CompSpec compSpec) {
161 addMethod(target, createCodePropertyDescriptors(compSpec));
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);
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();
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());
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()]))
188 return String.join("\n", lines);
191 public static void setProcessorRelationships(CtClass target, CompSpec compSpec) {
192 addMethod(target, createCodeRelationships(compSpec));