Search in sources :

Example 11 with JavaClass

use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.

the class SpringBootAutoConfigurationMojo method createComponentConfigurationSource.

private void createComponentConfigurationSource(String packageName, ComponentModel model, String overrideComponentName) throws MojoFailureException {
    int pos = model.getJavaType().lastIndexOf(".");
    String name = model.getJavaType().substring(pos + 1);
    name = name.replace("Component", "ComponentConfiguration");
    final JavaClass javaClass = new JavaClass(getProjectClassLoader());
    javaClass.setPackage(packageName);
    javaClass.setName(name);
    javaClass.extendSuperType("ComponentConfigurationPropertiesCommon");
    javaClass.addImport("org.apache.camel.spring.boot.ComponentConfigurationPropertiesCommon");
    // add bogus field for enabled so spring boot tooling can get the
    // javadoc as description in its metadata
    Property bogus = javaClass.addProperty("java.lang.Boolean", "enabled");
    String scheme = overrideComponentName != null ? overrideComponentName : model.getScheme();
    bogus.getField().getJavaDoc().setText("Whether to enable auto configuration of the " + scheme + " component. This is enabled by default.");
    bogus.removeAccessor();
    bogus.removeMutator();
    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().setText(doc);
    String prefix = "camel.component." + camelCaseToDash(overrideComponentName != null ? overrideComponentName : model.getScheme());
    // make sure prefix is in lower case
    prefix = prefix.toLowerCase(Locale.US);
    javaClass.addAnnotation(Generated.class.getName()).setStringValue("value", SpringBootAutoConfigurationMojo.class.getName());
    javaClass.addAnnotation("org.springframework.boot.context.properties.ConfigurationProperties").setStringValue("prefix", prefix);
    for (ComponentOptionModel option : model.getComponentOptions()) {
        if (skipComponentOption(model, option)) {
            // some component options should be skipped
            continue;
        }
        String type = option.getJavaType();
        // generate inner class for non-primitive options
        type = getSimpleJavaType(type);
        Property prop = javaClass.addProperty(type, option.getName());
        if (option.isDeprecated()) {
            prop.getField().addAnnotation(Deprecated.class);
            prop.getAccessor().addAnnotation(Deprecated.class);
            prop.getMutator().addAnnotation(Deprecated.class);
            // DeprecatedConfigurationProperty must be on getter when deprecated
            prop.getAccessor().addAnnotation(DeprecatedConfigurationProperty.class);
        }
        if (!Strings.isNullOrEmpty(option.getDescription())) {
            String desc = option.getDescription();
            boolean complex = isComplexTypeOrDuration(option) && isBlank(option.getEnums());
            if (complex) {
                if (!desc.endsWith(".")) {
                    desc = desc + ".";
                }
                desc = desc + " The option is a " + option.getJavaType() + " type.";
            }
            prop.getField().getJavaDoc().setFullText(desc);
        }
        if (!isBlank(option.getDefaultValue())) {
            if ("java.lang.String".equals(option.getJavaType())) {
                prop.getField().setStringInitializer(option.getDefaultValue().toString());
            } else if ("duration".equals(option.getType())) {
                String value = convertDurationToMills(option.getDefaultValue().toString());
                // duration is either long or int java type
                if ("long".equals(option.getJavaType()) || "java.lang.Long".equals(option.getJavaType())) {
                    value = value + "L";
                }
                prop.getField().setLiteralInitializer(value);
            } else if ("long".equals(option.getJavaType()) || "java.lang.Long".equals(option.getJavaType())) {
                // 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("\\.", "\\/") + "/" + name + ".java";
    writeSourceIfChanged(javaClass, fileName, true);
}
Also used : JavaClass(org.apache.camel.tooling.util.srcgen.JavaClass) Property(org.apache.camel.tooling.util.srcgen.Property) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) DeprecatedConfigurationProperty(org.springframework.boot.context.properties.DeprecatedConfigurationProperty) ComponentOptionModel(org.apache.camel.tooling.model.ComponentModel.ComponentOptionModel)

Example 12 with JavaClass

use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.

the class SpringBootAutoConfigurationMojo method createDataFormatConverterSource.

private void createDataFormatConverterSource(String packageName, DataFormatModel model) throws MojoFailureException {
    final String name = model.getJavaType().substring(model.getJavaType().lastIndexOf(".") + 1).replace("DataFormat", "DataFormatConverter");
    // 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().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);
}
Also used : Generated(javax.annotation.Generated) JavaClass(org.apache.camel.tooling.util.srcgen.JavaClass)

Example 13 with JavaClass

use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.

the class SpringBootAutoConfigurationMojo method createLanguageConfigurationSource.

private void createLanguageConfigurationSource(String packageName, LanguageModel model, String overrideLanguageName) throws MojoFailureException {
    final JavaClass javaClass = new JavaClass(getProjectClassLoader());
    int pos = model.getJavaType().lastIndexOf(".");
    String name = model.getJavaType().substring(pos + 1);
    name = name.replace("Language", "LanguageConfiguration");
    javaClass.setPackage(packageName).setName(name);
    javaClass.extendSuperType("LanguageConfigurationPropertiesCommon");
    javaClass.addImport("org.apache.camel.spring.boot.LanguageConfigurationPropertiesCommon");
    // add bogus field for enabled so spring boot tooling can get the
    // javadoc as description in its metadata
    Property bogus = javaClass.addProperty("java.lang.Boolean", "enabled");
    bogus.getField().getJavaDoc().setText("Whether to enable auto configuration of the " + model.getName() + " language. This is enabled by default.");
    bogus.removeAccessor();
    bogus.removeMutator();
    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);
    String prefix = "camel.language." + (camelCaseToDash(overrideLanguageName != null ? overrideLanguageName : model.getName()));
    // make sure prefix is in lower case
    prefix = prefix.toLowerCase(Locale.US);
    javaClass.addAnnotation(Generated.class).setStringValue("value", SpringBootAutoConfigurationMojo.class.getName());
    javaClass.addAnnotation("org.springframework.boot.context.properties.ConfigurationProperties").setStringValue("prefix", prefix);
    for (LanguageOptionModel option : model.getOptions()) {
        // need that and skip resultType as they are not global options
        if ("id".equals(option.getName()) || "expression".equals(option.getName()) || "resultType".equals(option.getName())) {
            continue;
        }
        // CHECKSTYLE:OFF
        if ("bean".equals(model.getName())) {
            // and skip following as they are not global options
            if ("bean".equals(option.getName()) || "ref".equals(option.getName()) || "method".equals(option.getName()) || "beanType".equals(option.getName())) {
                continue;
            }
        } else if ("tokenize".equals(model.getName())) {
            // and skip following as they are not global options
            if ("token".equals(option.getName()) || "endToken".equals(option.getName()) || "inheritNamespaceTagName".equals(option.getName()) || "headerName".equals(option.getName()) || "regex".equals(option.getName()) || "xml".equals(option.getName()) || "includeTokens".equals(option.getName()) || "group".equals(option.getName()) || "skipFirst".equals(option.getName())) {
                continue;
            }
        } else if ("xtokenize".equals(model.getName())) {
            // and skip following as they are not global options
            if ("headerName".equals(option.getName()) || "group".equals(option.getName())) {
                continue;
            }
        } else if ("xpath".equals(model.getName())) {
            // and skip following as they are not global options
            if ("headerName".equals(option.getName())) {
                continue;
            }
        } else if ("xquery".equals(model.getName())) {
            // and skip following as they are not global options
            if ("headerName".equals(option.getName())) {
                continue;
            }
        }
        // CHECKSTYLE:ON
        String type = option.getJavaType();
        type = getSimpleJavaType(type);
        // spring-boot auto configuration does not support complex types
        // (unless they are enum, nested)
        // and if so then we should use a String type so spring-boot and its
        // tooling support that
        // as Camel will be able to convert the string value into a lookup
        // of the bean in the registry anyway
        // and therefore there is no problem, eg
        // camel.component.jdbc.data-source = myDataSource
        // where the type would have been javax.sql.DataSource
        boolean complex = isComplexType(option) && isBlank(option.getEnums());
        if (complex) {
            // force to use a string type
            type = "java.lang.String";
        }
        Property prop = javaClass.addProperty(type, option.getName());
        if (option.isDeprecated()) {
            prop.getField().addAnnotation(Deprecated.class);
            prop.getAccessor().addAnnotation(Deprecated.class);
            prop.getMutator().addAnnotation(Deprecated.class);
            // DeprecatedConfigurationProperty must be on getter when
            // deprecated
            prop.getAccessor().addAnnotation(DeprecatedConfigurationProperty.class);
        }
        if (!Strings.isNullOrEmpty(option.getDescription())) {
            String desc = option.getDescription();
            if (complex) {
                if (!desc.endsWith(".")) {
                    desc = desc + ".";
                }
                desc = desc + " The option is a " + option.getJavaType() + " type.";
            }
            prop.getField().getJavaDoc().setFullText(desc);
        }
        if (!isBlank(option.getDefaultValue())) {
            if ("java.lang.String".equals(option.getJavaType())) {
                prop.getField().setStringInitializer(option.getDefaultValue().toString());
            } else if ("long".equals(option.getJavaType()) || "java.lang.Long".equals(option.getJavaType())) {
                // 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("\\.", "\\/") + "/" + name + ".java";
    writeSourceIfChanged(javaClass, fileName, true);
}
Also used : Generated(javax.annotation.Generated) JavaClass(org.apache.camel.tooling.util.srcgen.JavaClass) LanguageOptionModel(org.apache.camel.tooling.model.LanguageModel.LanguageOptionModel) Property(org.apache.camel.tooling.util.srcgen.Property) ConditionalOnProperty(org.springframework.boot.autoconfigure.condition.ConditionalOnProperty) DeprecatedConfigurationProperty(org.springframework.boot.context.properties.DeprecatedConfigurationProperty)

Example 14 with JavaClass

use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-spring-boot by apache.

the class SpringBootAutoConfigurationMojo method createDataFormatAutoConfigurationSource.

private void createDataFormatAutoConfigurationSource(String packageName, DataFormatModel model, String overrideName, boolean complexOptions) throws MojoFailureException {
    final String name = model.getJavaType().substring(model.getJavaType().lastIndexOf(".") + 1).replace("DataFormat", "DataFormatAutoConfiguration");
    final String configurationName = name.replace("DataFormatAutoConfiguration", "DataFormatConfiguration");
    final String dataformatName = camelCaseToDash(overrideName != null ? overrideName : model.getName()).toLowerCase(Locale.US);
    final Class<?> configClass = generateDummyClass(packageName + "." + configurationName);
    final 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(AutoConfigureAfter.class).setLiteralValue("CamelAutoConfiguration.class");
    javaClass.addAnnotation(Conditional.class).setLiteralValue("ConditionalOnCamelContextAndAutoConfigurationBeans.class");
    javaClass.addAnnotation(EnableConfigurationProperties.class).setLiteralValue("{DataFormatConfigurationProperties.class," + configurationName + ".class}");
    javaClass.addAnnotation("org.apache.camel.spring.boot.util.ConditionalOnHierarchicalProperties").setStringArrayValue("value", new String[] { "camel.dataformat", "camel.dataformat." + dataformatName });
    javaClass.addImport(ApplicationContext.class);
    javaClass.addImport("org.springframework.boot.convert.ApplicationConversionService");
    javaClass.addImport("org.apache.camel.CamelContext");
    javaClass.addImport("org.apache.camel.spring.boot.CamelAutoConfiguration");
    javaClass.addImport("org.apache.camel.spring.boot.DataFormatConfigurationProperties");
    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("org.apache.camel.spi.DataFormat");
    javaClass.addImport("org.apache.camel.spi.DataFormatCustomizer");
    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");
    String body = createDataFormatBody(model.getShortJavaType(), dataformatName);
    String methodName = "configure" + model.getShortJavaType() + "Factory";
    Method method = javaClass.addMethod().setName(methodName).setPublic().setBody(body).setReturnType(loadType("org.apache.camel.spi.DataFormatCustomizer"));
    method.addAnnotation(Lazy.class);
    method.addAnnotation(Bean.class);
    sortImports(javaClass);
    String fileName = packageName.replaceAll("\\.", "\\/") + "/" + name + ".java";
    writeSourceIfChanged(javaClass, fileName, false);
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) Generated(javax.annotation.Generated) JavaClass(org.apache.camel.tooling.util.srcgen.JavaClass) Configuration(org.springframework.context.annotation.Configuration) EnableConfigurationProperties(org.springframework.boot.context.properties.EnableConfigurationProperties) AutoConfigureAfter(org.springframework.boot.autoconfigure.AutoConfigureAfter) Conditional(org.springframework.context.annotation.Conditional) Method(org.apache.camel.tooling.util.srcgen.Method)

Example 15 with JavaClass

use of org.apache.camel.tooling.util.srcgen.JavaClass in project camel-kafka-connector by apache.

the class CamelKafkaConnectorKameletUpdateMojo method createClassesAndDocumentation.

private void createClassesAndDocumentation(String sanitizedName, File connectorDir, KameletModel kamelet, 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(fixKameletDependenciesProperties))) {
        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");
    // instantiate CamelKafkaConnectorOptionModel for further use during documentation generation
    List<CamelKafkaConnectorOptionModel> listOptions = new ArrayList<>();
    List<KameletPropertyModel> kameletProperties = kamelet.getProperties();
    kameletProperties.forEach(kameletProperty -> addConnectorOptions(sanitizedName, ct, javaClassConnectorConfig, confMethod, "KAMELET", kameletProperty, listOptions, kamelet.getRequiredProperties()));
    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);
    if (!additionalProperties.keySet().isEmpty()) {
        Method getDefaultConfigMethod = javaClassTask.addMethod().setConstructor(false).setName("getDefaultConfig").setProtected().setReturnType("Map<String, String>").setBody("return new HashMap<String, String>() {{\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);
    }
    Method getSinkOrSourceKameletMethod = javaClassTask.addMethod().setConstructor(false).setName("get" + ctCapitalizedName + "Kamelet").setProtected().setReturnType("String").setBody("return \"kamelet:" + name + "\";");
    getSinkOrSourceKameletMethod.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, kamelet.getDescription(), connectorDir, ct, packageName + "." + javaClassConnectorName, convertersList, transformsList, aggregationStrategiesList);
    // generate descriptor src/generated/descriptors/connector-{sink,source}.properties
    writeDescriptors(connectorDir, ct);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Properties(java.util.Properties) KameletPropertyModel(org.apache.camel.kafkaconnector.maven.model.KameletPropertyModel) TreeSet(java.util.TreeSet) Generated(javax.annotation.Generated) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) RegexFileFilter(org.apache.commons.io.filefilter.RegexFileFilter) Method(org.apache.camel.tooling.util.srcgen.Method) FileInputStream(java.io.FileInputStream) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SAXException(org.xml.sax.SAXException) ResourceNotFoundException(org.codehaus.plexus.resource.loader.ResourceNotFoundException) IOException(java.io.IOException) FileResourceCreationException(org.codehaus.plexus.resource.loader.FileResourceCreationException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) JavaClass(org.apache.camel.tooling.util.srcgen.JavaClass) CamelKafkaConnectorOptionModel(org.apache.camel.kafkaconnector.model.CamelKafkaConnectorOptionModel) JsonObject(org.apache.camel.util.json.JsonObject) File(java.io.File)

Aggregations

JavaClass (org.apache.camel.tooling.util.srcgen.JavaClass)15 Generated (javax.annotation.Generated)14 Method (org.apache.camel.tooling.util.srcgen.Method)8 Property (org.apache.camel.tooling.util.srcgen.Property)6 ConditionalOnProperty (org.springframework.boot.autoconfigure.condition.ConditionalOnProperty)6 DeprecatedConfigurationProperty (org.springframework.boot.context.properties.DeprecatedConfigurationProperty)6 Configuration (org.springframework.context.annotation.Configuration)6 AutoConfigureAfter (org.springframework.boot.autoconfigure.AutoConfigureAfter)5 EnableConfigurationProperties (org.springframework.boot.context.properties.EnableConfigurationProperties)5 ApplicationContext (org.springframework.context.ApplicationContext)4 Conditional (org.springframework.context.annotation.Conditional)4 File (java.io.File)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 EipOptionModel (org.apache.camel.tooling.model.EipModel.EipOptionModel)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 MojoFailureException (org.apache.maven.plugin.MojoFailureException)3 ConditionalOnClass (org.springframework.boot.autoconfigure.condition.ConditionalOnClass)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileInputStream (java.io.FileInputStream)2