use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-kafka-connector by apache.
the class CamelKafkaConnectorUpdateMojo method createClasses.
private void createClasses(String sanitizedName, File connectorDir, ComponentModel model, ConnectorType ct) throws MojoFailureException, ResourceNotFoundException, FileResourceCreationException, IOException, MojoExecutionException {
String ctCapitalizedName = StringUtils.capitalize(ct.name().toLowerCase());
String ctLowercaseName = ct.name().toLowerCase();
String packageName = "org.apache.camel.kafkaconnector." + RESERVED_WORDS_SUBSTITUTION_MAP.getOrDefault(sanitizedName.replace("-", ""), sanitizedName.replace("-", ""));
Map<String, String> additionalProperties = new HashMap<>();
Properties properties = new Properties();
try (InputStream stream = new FileInputStream(rm.getResourceAsFile(fixDependenciesProperties))) {
properties.load(stream);
}
String commonPropertyValue = properties.getProperty(ADDITIONAL_COMMON_PROPERTIES_PROPERTY_PREFIX + getMainDepArtifactId());
getLog().debug("Additional common connector properties: " + commonPropertyValue);
addProperties(additionalProperties, commonPropertyValue);
String sourceOrSinkPropertyValue = properties.getProperty(ADDITIONAL_COMMON_PROPERTIES_PROPERTY_PREFIX + ctLowercaseName + "_" + getMainDepArtifactId());
getLog().debug("Additional " + ctLowercaseName + " connector properties: " + sourceOrSinkPropertyValue);
addProperties(additionalProperties, sourceOrSinkPropertyValue);
// Camel{sanitizedName}{Sink,Source}ConnectorConfig.java
String javaClassConnectorConfigName = "Camel" + StringUtils.capitalize(sanitizedName.replace("-", "")) + ctCapitalizedName + "ConnectorConfig";
final JavaClass javaClassConnectorConfig = new JavaClass(getProjectClassLoader());
javaClassConnectorConfig.setPackage(packageName);
javaClassConnectorConfig.setName(javaClassConnectorConfigName);
javaClassConnectorConfig.addAnnotation(Generated.class).setStringValue("value", "This class has been generated by camel-kafka-connector-generator-maven-plugin, remove this annotation to prevent it from being generated.");
javaClassConnectorConfig.extendSuperType("Camel" + ctCapitalizedName + "ConnectorConfig");
javaClassConnectorConfig.addImport("java.util.Map");
javaClassConnectorConfig.addImport("org.apache.camel.kafkaconnector.Camel" + ctCapitalizedName + "ConnectorConfig");
javaClassConnectorConfig.addImport("org.apache.kafka.common.config.ConfigDef");
javaClassConnectorConfig.addMethod().setConstructor(true).setName(javaClassConnectorConfigName).addParameter("ConfigDef", "config").addParameter("Map<String, String>", "parsedConfig").setPublic().setBody("super(config, parsedConfig);");
javaClassConnectorConfig.addMethod().setConstructor(true).setName(javaClassConnectorConfigName).addParameter("Map<String, String>", "parsedConfig").setPublic().setBody("this(conf(), parsedConfig);");
Method confMethod = javaClassConnectorConfig.addMethod().setConstructor(false).setName("conf").setReturnType("ConfigDef").setPublic().setStatic().setBody("ConfigDef conf = new ConfigDef(Camel" + ctCapitalizedName + "ConnectorConfig.conf());\n");
Predicate<? super BaseOptionModel> filterEndpointOptions;
switch(ct) {
case SINK:
filterEndpointOptions = new Predicate<BaseOptionModel>() {
@Override
public boolean test(BaseOptionModel optionModel) {
return optionModel.getLabel() == null || optionModel.getLabel().contains("producer") || (!optionModel.getLabel().contains("producer") && !optionModel.getLabel().contains("consumer"));
}
};
break;
case SOURCE:
filterEndpointOptions = new Predicate<BaseOptionModel>() {
@Override
public boolean test(BaseOptionModel optionModel) {
return optionModel.getLabel() == null || optionModel.getLabel().contains("consumer") || (!optionModel.getLabel().contains("producer") && !optionModel.getLabel().contains("consumer"));
}
};
break;
default:
throw new UnsupportedOperationException("Connector type not supported: " + ct + " must be one of " + ConnectorType.SINK + ", " + ConnectorType.SOURCE);
}
List<CamelKafkaConnectorOptionModel> listOptions = new ArrayList<>();
model.getEndpointPathOptions().stream().filter(filterEndpointOptions).forEachOrdered(epo -> addConnectorOptions(sanitizedName, ct, javaClassConnectorConfig, confMethod, "PATH", ctLowercaseName, "path", epo, listOptions));
model.getEndpointParameterOptions().stream().filter(filterEndpointOptions).forEachOrdered(epo -> addConnectorOptions(sanitizedName, ct, javaClassConnectorConfig, confMethod, "ENDPOINT", ctLowercaseName, "endpoint", epo, listOptions));
model.getComponentOptions().stream().filter(filterEndpointOptions).forEachOrdered(co -> addConnectorOptions(sanitizedName, ct, javaClassConnectorConfig, confMethod, "COMPONENT", "component", sanitizedName, co, listOptions));
confMethod.setBody(confMethod.getBody() + "return conf;");
String javaClassConnectorConfigFileName = packageName.replaceAll("\\.", "\\/") + File.separator + javaClassConnectorConfigName + ".java";
MavenUtils.writeSourceIfChanged(javaClassConnectorConfig, javaClassConnectorConfigFileName, false, connectorDir, rm.getResourceAsFile(javaFilesHeader));
// Camel{sanitizedName}{Sink,Source}Task.java
String javaClassTaskName = "Camel" + StringUtils.capitalize(sanitizedName.replace("-", "")) + ctCapitalizedName + "Task";
final JavaClass javaClassTask = new JavaClass(getProjectClassLoader());
javaClassTask.setPackage(packageName);
javaClassTask.setName(javaClassTaskName);
javaClassTask.addAnnotation(Generated.class).setStringValue("value", "This class has been generated by camel-kafka-connector-generator-maven-plugin, remove this annotation to prevent it from being generated.");
javaClassTask.extendSuperType("Camel" + ctCapitalizedName + "Task");
javaClassTask.addImport("java.util.HashMap");
javaClassTask.addImport("java.util.Map");
javaClassTask.addImport("org.apache.camel.kafkaconnector.Camel" + ctCapitalizedName + "ConnectorConfig");
javaClassTask.addImport("org.apache.camel.kafkaconnector.Camel" + ctCapitalizedName + "Task");
javaClassTask.addMethod().setConstructor(false).setName("getCamel" + ctCapitalizedName + "ConnectorConfig").setProtected().addParameter("Map<String, String>", "props").setReturnType("Camel" + ctCapitalizedName + "ConnectorConfig").setBody("return new Camel" + StringUtils.capitalize(sanitizedName.replace("-", "")) + ctCapitalizedName + "ConnectorConfig(props);").addAnnotation(Override.class);
Method getDefaultConfigMethod = javaClassTask.addMethod().setConstructor(false).setName("getDefaultConfig").setProtected().setReturnType("Map<String, String>").setBody("return new HashMap<String, String>() {{\n");
getDefaultConfigMethod.setBody(getDefaultConfigMethod.getBody() + " put(Camel" + ctCapitalizedName + "ConnectorConfig.CAMEL_" + ct + "_COMPONENT_CONF, \"" + model.getScheme() + "\");\n");
for (String key : new TreeSet<String>(additionalProperties.keySet())) {
getDefaultConfigMethod.setBody(getDefaultConfigMethod.getBody() + " put(\"" + key + "\", \"" + additionalProperties.get(key) + "\");\n");
}
getDefaultConfigMethod.setBody(getDefaultConfigMethod.getBody() + "}};\n");
getDefaultConfigMethod.addAnnotation(Override.class);
String javaClassTaskFileName = packageName.replaceAll("\\.", "\\/") + File.separator + javaClassTaskName + ".java";
MavenUtils.writeSourceIfChanged(javaClassTask, javaClassTaskFileName, false, connectorDir, rm.getResourceAsFile(javaFilesHeader));
// Camel{sanitizedName}{Sink,Source}Connector.java
String javaClassConnectorName = "Camel" + StringUtils.capitalize(sanitizedName.replace("-", "")) + ctCapitalizedName + "Connector";
final JavaClass javaClassConnector = new JavaClass(getProjectClassLoader());
javaClassConnector.setPackage(packageName);
javaClassConnector.setName(javaClassConnectorName);
javaClassConnector.addAnnotation(Generated.class).setStringValue("value", "This class has been generated by camel-kafka-connector-generator-maven-plugin, remove this annotation to prevent it from being generated.");
javaClassConnector.extendSuperType("Camel" + ctCapitalizedName + "Connector");
javaClassConnector.addImport("org.apache.camel.kafkaconnector.Camel" + ctCapitalizedName + "Connector");
javaClassConnector.addImport("org.apache.kafka.common.config.ConfigDef");
javaClassConnector.addImport("org.apache.kafka.connect.connector.Task");
javaClassConnector.addMethod().setConstructor(false).setName("config").setPublic().setReturnType("ConfigDef").setBody("return Camel" + StringUtils.capitalize(sanitizedName.replace("-", "")) + ctCapitalizedName + "ConnectorConfig.conf();").addAnnotation(Override.class);
javaClassConnector.addMethod().setConstructor(false).setName("taskClass").setPublic().setReturnType("Class<? extends Task>").setBody("return Camel" + StringUtils.capitalize(sanitizedName.replace("-", "")) + ctCapitalizedName + "Task.class;").addAnnotation(Override.class);
String javaClassConnectorFileName = packageName.replaceAll("\\.", "\\/") + File.separator + javaClassConnectorName + ".java";
MavenUtils.writeSourceIfChanged(javaClassConnector, javaClassConnectorFileName, false, connectorDir, rm.getResourceAsFile(javaFilesHeader));
List<String> convertersList = new ArrayList<>();
List<String> transformsList = new ArrayList<>();
List<String> aggregationStrategiesList = new ArrayList<>();
if (connectorDir != null && connectorDir.isDirectory()) {
File[] files = connectorDir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
Collection<File> convertersElements = FileUtils.listFiles(file, new RegexFileFilter(".*Converter.java"), DirectoryFileFilter.DIRECTORY);
Collection<File> transformElements = FileUtils.listFiles(file, new RegexFileFilter(".*Transforms.java"), DirectoryFileFilter.DIRECTORY);
Collection<File> aggStrategiesElements = FileUtils.listFiles(file, new RegexFileFilter(".*AggregationStrategy.java"), DirectoryFileFilter.DIRECTORY);
for (File p : convertersElements) {
String filePath = p.getCanonicalPath();
String f = StringUtils.removeStart(filePath, connectorDir.getAbsolutePath() + "/src/main/java/");
String finalElement = StringUtils.replace(f, File.separator, ".");
String finalPath = StringUtils.removeEnd(finalElement, ".java");
convertersList.add(finalPath);
}
for (File p : transformElements) {
String filePath = p.getCanonicalPath();
String f = StringUtils.removeStart(filePath, connectorDir.getAbsolutePath() + "/src/main/java/");
String finalElement = StringUtils.replace(f, File.separator, ".");
String finalPath = StringUtils.removeEnd(finalElement, ".java");
transformsList.add(finalPath);
}
for (File p : aggStrategiesElements) {
String filePath = p.getCanonicalPath();
String f = StringUtils.removeStart(filePath, connectorDir.getAbsolutePath() + "/src/main/java/");
String finalElement = StringUtils.replace(f, File.separator, ".");
String finalPath = StringUtils.removeEnd(finalElement, ".java");
aggregationStrategiesList.add(finalPath);
}
}
}
}
}
// docs/examples/Camel{sanitizedName}{Sink,Source}.properties
try {
String examplesPropertiestemplate = null;
switch(ct) {
case SOURCE:
examplesPropertiestemplate = loadText(rm.getResourceAsFile(exampleSourcePropertiesFileTemplate));
break;
case SINK:
examplesPropertiestemplate = loadText(rm.getResourceAsFile(exampleSinkPropertiesFileTemplate));
break;
default:
break;
}
HashMap<String, Object> templateParams = new HashMap<>();
templateParams.put("connectorName", StringUtils.capitalize(sanitizedName));
templateParams.put("connectorClass", packageName + "." + javaClassConnectorName);
List<CamelKafkaConnectorOptionModel> mandatoryOptions = listOptions.stream().filter(o -> "HIGH".equalsIgnoreCase(o.getPriority())).sorted(Comparator.comparing(CamelKafkaConnectorOptionModel::getName, String.CASE_INSENSITIVE_ORDER)).collect(Collectors.toList());
templateParams.put("options", mandatoryOptions);
String examplePropertiesFileContent = (String) TemplateRuntime.eval(examplesPropertiestemplate, templateParams);
writeFileIfChanged(examplePropertiesFileContent, new File(connectorDir, "src/main/docs/examples/" + javaClassConnectorName + ".properties"), getLog());
} catch (Exception e) {
throw new MojoExecutionException("Error processing mvel examples properties template. Reason: " + e, e);
}
// generate json descriptor src/generated/resources/<connector-name>.json
writeJson(listOptions, model.getDescription(), connectorDir, ct, packageName + "." + javaClassConnectorName, convertersList, transformsList, aggregationStrategiesList);
// generate descriptor src/generated/descriptors/connector-{sink,source}.properties
writeDescriptors(connectorDir, ct);
}
use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.
the class SpringBootAutoConfigurationMojo method createRestConfigurationSource.
private void createRestConfigurationSource(String packageName, EipModel model, String propertiesPrefix) throws MojoFailureException {
final int pos = model.getJavaType().lastIndexOf(".");
final String className = model.getJavaType().substring(pos + 1) + "Properties";
generateDummyClass(packageName + "." + className);
// Common base class
JavaClass javaClass = new JavaClass(getProjectClassLoader());
javaClass.setPackage(packageName);
javaClass.setName(className);
javaClass.addAnnotation(Generated.class).setStringValue("value", SpringBootAutoConfigurationMojo.class.getName());
javaClass.addAnnotation("org.springframework.boot.context.properties.ConfigurationProperties").setStringValue("prefix", propertiesPrefix);
String doc = "Generated by camel-package-maven-plugin - do not edit this file!";
if (!Strings.isNullOrEmpty(model.getDescription())) {
doc = model.getDescription() + "\n\n" + doc;
}
javaClass.getJavaDoc().setFullText(doc);
for (EipOptionModel option : model.getOptions()) {
String type = option.getJavaType();
String name = option.getName();
if ("id".equalsIgnoreCase(name) || "parent".equalsIgnoreCase(name) || "camelContext".equalsIgnoreCase(name)) {
// Skip them as they should not be set via spring boot
continue;
}
if ("java.util.List<org.apache.camel.model.PropertyDefinition>".equalsIgnoreCase(type)) {
type = "java.util.Map<java.lang.String, java.lang.String>";
} else if ("java.util.List<org.apache.camel.model.rest.RestPropertyDefinition>".equalsIgnoreCase(type)) {
type = "java.util.Map<java.lang.String, java.lang.Object>";
}
// to avoid ugly names such as c-o-r-s
if ("enableCORS".equalsIgnoreCase(name)) {
name = "enableCors";
}
// generate inner class for non-primitive options
Property prop = javaClass.addProperty(type, name);
if (!Strings.isNullOrEmpty(option.getDescription())) {
prop.getField().getJavaDoc().setFullText(option.getDescription());
}
if (!isBlank(option.getDefaultValue())) {
if ("java.lang.String".equals(type)) {
prop.getField().setStringInitializer(option.getDefaultValue().toString());
} else if ("long".equals(type) || "java.lang.Long".equals(type)) {
// the value should be a Long number
String value = option.getDefaultValue() + "L";
prop.getField().setLiteralInitializer(value);
} else if ("integer".equals(option.getType()) || "java.lang.Integer".equals(option.getJavaType()) || "boolean".equals(option.getType()) || "java.lang.Boolean".equals(option.getJavaType())) {
prop.getField().setLiteralInitializer(option.getDefaultValue().toString());
} else if (!isBlank(option.getEnums())) {
String enumShortName = type.substring(type.lastIndexOf(".") + 1);
prop.getField().setLiteralInitializer(enumShortName + "." + option.getDefaultValue());
javaClass.addImport(model.getJavaType());
}
}
}
String fileName = packageName.replaceAll("\\.", "\\/") + "/" + className + ".java";
writeSourceIfChanged(javaClass, fileName, true);
}
use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.
the class SpringBootAutoConfigurationMojo method readJavaType.
// read java type from project, returns null if not found
private JavaClass readJavaType(String type) {
if (!type.startsWith("java.lang.") && (!type.contains("<") || !type.contains(">"))) {
String sourceCode = "";
try {
Class<?> clazz = getProjectClassLoader().loadClass(type);
URL url = clazz != null ? getProjectClassLoader().getResource(clazz.getName().replace('.', '/') + ".class") : null;
Artifact mainDep = project.getArtifactMap().get(getMainDepGroupId() + ":" + getMainDepArtifactId());
if (url == null || mainDep == null || !url.toString().contains(mainDep.getFile().toURI().toString())) {
return null;
}
JavaClass nestedType = new JavaClass(getProjectClassLoader()).setPackage(clazz.getPackage().getName()).setName(clazz.getSimpleName()).setEnum(clazz.isEnum()).setClass(!clazz.isInterface()).setAbstract((clazz.getModifiers() & Modifier.ABSTRACT) != 0).setStatic((clazz.getModifiers() & Modifier.STATIC) != 0).extendSuperType(clazz.getGenericSuperclass() != null ? new GenericType(clazz.getGenericSuperclass()).toString() : null);
List<java.lang.reflect.Method> publicMethods = Stream.of(clazz.getDeclaredMethods()).filter(m -> Modifier.isPublic(m.getModifiers())).collect(Collectors.toList());
List<java.lang.reflect.Method> allSetters = publicMethods.stream().filter(m -> m.getReturnType() == void.class || m.getReturnType() == clazz).filter(m -> m.getParameterCount() == 1).filter(m -> m.getName().matches("set[A-Z][a-zA-Z0-9]*")).collect(Collectors.toList());
List<java.lang.reflect.Method> allGetters = publicMethods.stream().filter(m -> m.getReturnType() != void.class).filter(m -> m.getParameterCount() == 0).filter(m -> m.getName().matches("(get|is)[A-Z][a-zA-Z0-9]*")).collect(Collectors.toList());
allSetters.stream().sorted(Comparator.<java.lang.reflect.Method>comparingInt(m -> getSetterPosition(sourceCode, m)).thenComparing(java.lang.reflect.Method::getName)).map(m -> StringUtils.uncapitalize(m.getName().substring(3))).forEach(fn -> {
Class<?> ft;
Type wft;
boolean isBoolean;
java.lang.reflect.Field field = Stream.of(clazz.getDeclaredFields()).filter(f -> f.getName().equals(fn)).findAny().orElse(null);
List<java.lang.reflect.Method> setters = allSetters.stream().filter(m -> m.getName().equals("set" + StringUtils.capitalize(fn))).collect(Collectors.toList());
List<java.lang.reflect.Method> getters = allGetters.stream().filter(m -> m.getName().equals("get" + StringUtils.capitalize(fn)) || m.getName().equals("is" + StringUtils.capitalize(fn))).collect(Collectors.toList());
java.lang.reflect.Method mutator;
java.lang.reflect.Method accessor;
if (setters.size() == 1) {
mutator = setters.get(0);
ft = mutator.getParameterTypes()[0];
wft = PRIMITIVE_CLASSES.getOrDefault(ft, ft);
isBoolean = ft == boolean.class || ft == Boolean.class;
accessor = allGetters.stream().filter(m -> m.getName().equals("get" + StringUtils.capitalize(fn)) || isBoolean && m.getName().equals("is" + StringUtils.capitalize(fn))).filter(m -> PRIMITIVE_CLASSES.getOrDefault(m.getReturnType(), m.getReturnType()) == wft).findAny().orElse(null);
} else if (field != null) {
ft = field.getType();
wft = PRIMITIVE_CLASSES.getOrDefault(ft, ft);
isBoolean = ft == boolean.class || ft == Boolean.class;
mutator = allSetters.stream().filter(m -> m.getName().equals("set" + StringUtils.capitalize(fn))).filter(m -> PRIMITIVE_CLASSES.getOrDefault(m.getParameterTypes()[0], m.getParameterTypes()[0]) == wft).findAny().orElse(null);
accessor = allGetters.stream().filter(m -> m.getName().equals("get" + StringUtils.capitalize(fn)) || isBoolean && m.getName().equals("is" + StringUtils.capitalize(fn))).filter(m -> PRIMITIVE_CLASSES.getOrDefault(m.getReturnType(), m.getReturnType()) == wft).findAny().orElse(null);
} else {
if (getters.size() == 1) {
ft = getters.get(0).getReturnType();
} else {
throw new IllegalStateException("Unable to determine type for property " + fn);
}
wft = PRIMITIVE_CLASSES.getOrDefault(ft, ft);
mutator = setters.stream().filter(m -> PRIMITIVE_CLASSES.getOrDefault(m.getParameterTypes()[0], m.getParameterTypes()[0]) == wft).findAny().orElse(null);
accessor = getters.stream().filter(m -> PRIMITIVE_CLASSES.getOrDefault(m.getReturnType(), m.getReturnType()) == wft).findAny().orElse(null);
}
if (mutator == null) {
throw new IllegalStateException("Could not find mutator for property " + fn);
}
Property property = nestedType.addProperty(new GenericType(wft), fn);
property.getMutator().getJavaDoc().setText(getSetterJavaDoc(sourceCode, fn));
for (java.lang.annotation.Annotation ann : mutator.getAnnotations()) {
addAnnotation(ac -> property.getMutator().addAnnotation(ac), ann);
}
if (accessor != null) {
for (java.lang.annotation.Annotation ann : accessor.getAnnotations()) {
addAnnotation(ac -> property.getAccessor().addAnnotation(ac), ann);
}
} else {
property.removeAccessor();
}
if (field != null) {
for (java.lang.annotation.Annotation ann : field.getAnnotations()) {
addAnnotation(ac -> property.getField().addAnnotation(ac), ann);
}
} else {
property.removeField();
}
});
return nestedType;
} catch (ClassNotFoundException e) {
return null;
}
}
return null;
}
use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.
the class SpringBootAutoConfigurationMojo method createLanguageConverterSource.
private void createLanguageConverterSource(String packageName, LanguageModel model) throws MojoFailureException {
final String name = model.getJavaType().substring(model.getJavaType().lastIndexOf(".") + 1).replace("Language", "LanguageConverter");
// create converter class and write source
JavaClass javaClass = new JavaClass(getProjectClassLoader());
javaClass.setPackage(packageName);
javaClass.setName(name);
javaClass.getJavaDoc().setFullText("Generated by camel-package-maven-plugin - do not edit this file!");
javaClass.addAnnotation(Generated.class).setStringValue("value", SpringBootAutoConfigurationMojo.class.getName());
javaClass.addImport("java.util.LinkedHashSet");
javaClass.addImport("java.util.Set");
javaClass.addImport("org.apache.camel.CamelContext");
javaClass.addImport("org.springframework.core.convert.TypeDescriptor");
javaClass.addImport("org.springframework.core.convert.converter.GenericConverter");
javaClass.implementInterface("org.springframework.core.convert.converter.GenericConverter");
javaClass.addField().setPrivate().setFinal(true).setName("camelContext").setType(loadClass("org.apache.camel.CamelContext"));
javaClass.addMethod().setConstructor(true).setPublic().setName(name).addParameter("org.apache.camel.CamelContext", "camelContext").setBody("this.camelContext = camelContext;\n");
String body = createConverterPairBody(model);
javaClass.addMethod().setName("getConvertibleTypes").setPublic().setReturnType("Set<ConvertiblePair>").setBody(body);
body = createConvertBody(model);
javaClass.addMethod().setName("convert").setPublic().setReturnType("Object").addParameter("Object", "source").addParameter("TypeDescriptor", "sourceType").addParameter("TypeDescriptor", "targetType").setBody(body);
sortImports(javaClass);
String fileName = packageName.replaceAll("\\.", "\\/") + "/" + name + ".java";
writeSourceIfChanged(javaClass, fileName, false);
}
use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.
the class SpringBootAutoConfigurationMojo method createComponentAutoConfigurationSource.
private void createComponentAutoConfigurationSource(String packageName, ComponentModel model, String overrideName, boolean complexOptions) throws MojoFailureException {
final String name = model.getJavaType().substring(model.getJavaType().lastIndexOf(".") + 1).replace("Component", "ComponentAutoConfiguration");
final String configurationName = name.replace("ComponentAutoConfiguration", "ComponentConfiguration");
final String componentName = camelCaseToDash(overrideName != null ? overrideName : model.getScheme()).toLowerCase(Locale.US);
final Class<?> configClass = generateDummyClass(packageName + "." + configurationName);
JavaClass javaClass = new JavaClass(getProjectClassLoader());
javaClass.setPackage(packageName);
javaClass.setName(name);
javaClass.getJavaDoc().setFullText("Generated by camel-package-maven-plugin - do not edit this file!");
javaClass.addAnnotation(Generated.class).setStringValue("value", SpringBootAutoConfigurationMojo.class.getName());
javaClass.addAnnotation(Configuration.class).setLiteralValue("proxyBeanMethods", "false");
javaClass.addAnnotation(Conditional.class).setLiteralValue("ConditionalOnCamelContextAndAutoConfigurationBeans.class");
javaClass.addAnnotation(EnableConfigurationProperties.class).setLiteralValue("{ComponentConfigurationProperties.class," + configurationName + ".class}");
javaClass.addAnnotation("org.apache.camel.spring.boot.util.ConditionalOnHierarchicalProperties").setStringArrayValue("value", new String[] { "camel.component", "camel.component." + componentName });
if (complexOptions) {
String cn = name.replace("ComponentAutoConfiguration", "ComponentConverter");
javaClass.addAnnotation(AutoConfigureAfter.class).setLiteralValue("{CamelAutoConfiguration.class, " + cn + ".class}");
} else {
javaClass.addAnnotation(AutoConfigureAfter.class).setLiteralValue("CamelAutoConfiguration.class");
}
javaClass.addImport(ApplicationContext.class);
javaClass.addImport("org.apache.camel.CamelContext");
javaClass.addImport("org.apache.camel.Component");
javaClass.addImport("org.apache.camel.spi.ComponentCustomizer");
javaClass.addImport("org.apache.camel.spring.boot.CamelAutoConfiguration");
javaClass.addImport("org.apache.camel.spring.boot.ComponentConfigurationProperties");
javaClass.addImport("org.apache.camel.spring.boot.util.CamelPropertiesHelper");
javaClass.addImport("org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans");
javaClass.addImport("org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator");
javaClass.addImport(model.getJavaType());
javaClass.addField().setPrivate().setName("applicationContext").setType(ApplicationContext.class).addAnnotation(Autowired.class);
javaClass.addField().setPrivate().setFinal(true).setName("camelContext").setType(loadClass("org.apache.camel.CamelContext"));
javaClass.addField().setPrivate().setName("configuration").setType(configClass).addAnnotation(Autowired.class);
Method ctr = javaClass.addMethod().setConstructor(true).setPublic().setName(name).addParameter("org.apache.camel.CamelContext", "camelContext");
ctr.setBody("this.camelContext = camelContext;\n");
// add method for auto configure
String body = createComponentBody(model.getShortJavaType(), componentName);
String methodName = "configure" + model.getShortJavaType();
Method method = javaClass.addMethod().setName(methodName).setPublic().setBody(body).setReturnType(loadType("org.apache.camel.spi.ComponentCustomizer"));
method.addAnnotation(Lazy.class);
method.addAnnotation(Bean.class);
sortImports(javaClass);
String fileName = packageName.replaceAll("\\.", "\\/") + "/" + name + ".java";
writeSourceIfChanged(javaClass, fileName, false);
}
Aggregations