org.apache.camel.tooling.model.ComponentModel Java Examples

The following examples show how to use org.apache.camel.tooling.model.ComponentModel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CamelKafkaConnectorCreateMojo.java    From camel-kafka-connector with Apache License 2.0 6 votes vote down vote up
private void generateAndWritePom(String sanitizedName, File directory) throws Exception {
    //create initial connector pom
    ComponentModel cm = JsonMapper.generateComponentModel(componentJson);
    getLog().info("Creating a new pom.xml for the connector from scratch");
    Template pomTemplate = MavenUtils.getTemplate(rm.getResourceAsFile(initialPomTemplate));
    Map<String, String> props = new HashMap<>();
    props.put("version", project.getVersion());
    props.put("dependencyId", cm.getArtifactId());
    props.put("dependencyGroup", cm.getGroupId());
    props.put("componentName", name);
    props.put("componentSanitizedName", sanitizedName);
    props.put("componentDescription", name);
    try {
        Document pom = MavenUtils.createCrateXmlDocumentFromTemplate(pomTemplate, props);
        // Write the starter pom
        File pomFile = new File(directory, "pom.xml");
        writeXmlFormatted(pom, pomFile, getLog());
    } catch (Exception e) {
        getLog().error("Cannot create pom.xml file from Template: " + pomTemplate + " with properties: " + props, e);
        throw e;
    }
}
 
Example #2
Source File: ExtMvelHelper.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
public String getDocLink(Object model) {
    if (localDocExists(model)) {
        return getLocalDocLink(model);
    } else if (model instanceof ComponentModel) {
        return String.format("link:https://camel.apache.org/%s/latest/%s", "components",
                invokeGetter(model, "getScheme") + "-component.html");
    } else if (model instanceof DataFormatModel) {
        return String.format("link:https://camel.apache.org/%s/latest/%s", "components",  
        		"dataformats/" + invokeGetter(model, "getName") + "-dataformat.html");
    } else if (model instanceof LanguageModel) {
        return String.format("link:https://camel.apache.org/%s/latest/%s", "components", 
        		"languages/" +invokeGetter(model, "getName") + "-language.html");
    } else if (model instanceof OtherModel) {
        return String.format("link:https://camel.apache.org/%s/latest/%s", "components", 
        		"others/" + invokeGetter(model, "getName") + ".html");
    } else {
        return null;
    }
}
 
Example #3
Source File: UpdateDocComponentsListMojo.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
private String templateComponents(List<ComponentModel> models, int artifacts, long deprecated)
        throws MojoExecutionException {
    try {
        String template = loadText(
                UpdateDocComponentsListMojo.class.getClassLoader().getResourceAsStream("readme-components.mvel"));
        Map<String, Object> map = new HashMap<>();
        map.put("components", models);
        map.put("numberOfArtifacts", artifacts);
        map.put("numberOfDeprecated", deprecated);
        String out = (String) TemplateRuntime.eval(template, map,
                Collections.singletonMap("util", new ExtMvelHelper(getComponentsStarterDocPath())));
        return out;
    } catch (Exception e) {
        throw new MojoExecutionException("Error processing mvel template. Reason: " + e, e);
    }
}
 
Example #4
Source File: CamelKafkaConnectorUpdateMojo.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
private void updateConnector() throws Exception {
    String sanitizedName = sanitizeMavenArtifactId(name);
    // create the starter directory
    File connectorDir = new File(projectDir, "camel-" + sanitizedName + KAFKA_CONNECTORS_SUFFIX);
    if (!connectorDir.exists() || !connectorDir.isDirectory()) {
        getLog().info("Connector " + name + " can not be updated since directory " + connectorDir.getAbsolutePath() + " dose not exist.");
        throw new MojoFailureException("Directory already exists: " + connectorDir);
    }

    // create the base pom.xml
    Document pom = createBasePom(connectorDir);

    // Apply changes to the starter pom
    fixExcludedDependencies(pom);
    fixAdditionalDependencies(pom, additionalDependencies);
    fixAdditionalRepositories(pom);

    // Write the starter pom
    File pomFile = new File(connectorDir, "pom.xml");
    writeXmlFormatted(pom, pomFile, getLog());

    // write package
    Document pkg = createPackageFile();
    File pkgFile = new File(connectorDir, "src/main/assembly/package.xml");
    writeXmlFormatted(pkg, pkgFile, getLog());

    // write LICENSE, USAGE
    writeStaticFiles(connectorDir);

    // generate classes
    ComponentModel model = JsonMapper.generateComponentModel(componentJson);
    if (model.isConsumerOnly()) {
        createClasses(sanitizedName, connectorDir, model, ConnectorType.SOURCE);
    } else if (model.isProducerOnly()) {
        createClasses(sanitizedName, connectorDir, model, ConnectorType.SINK);
    } else {
        createClasses(sanitizedName, connectorDir, model, ConnectorType.SOURCE);
        createClasses(sanitizedName, connectorDir, model, ConnectorType.SINK);
    }
}
 
Example #5
Source File: CqCatalog.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public static boolean isFirstScheme(ArtifactModel<?> model) {
    if (model.getKind().equals("component")) {
        final String altSchemes = ((ComponentModel) model).getAlternativeSchemes();
        if (altSchemes == null || altSchemes.isEmpty()) {
            return true;
        } else {
            final String scheme = model.getName();
            return altSchemes.equals(scheme) || altSchemes.startsWith(scheme + ",");
        }
    } else {
        return true;
    }
}
 
Example #6
Source File: SpringBootAutoConfigurationMojo.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
private void beforeGenerateComponentSource(ComponentModel model) {
    if ("activemq".equals(model.getScheme()) || "amqp".equals(model.getScheme()) || "stomp".equals(model.getScheme())) {
        // we want brokerURL to be brokerUrl so its generated with a nice name for spring boot (and some other options too)
        model.getComponentOptions().stream()
                .filter(o -> "brokerURL".equals(o.getName())).findFirst().ifPresent(o -> o.setName("brokerUrl"));
        model.getComponentOptions().stream()
                .filter(o -> "useMessageIDAsCorrelationID".equals(o.getName())).findFirst().ifPresent(o -> o.setName("useMessageIdAsCorrelationId"));
        model.getComponentOptions().stream()
                .filter(o -> "includeAllJMSXProperties".equals(o.getName())).findFirst().ifPresent(o -> o.setName("includeAllJmsxProperties"));
        model.getComponentOptions().stream()
                .filter(o -> "includeSentJMSMessageID".equals(o.getName())).findFirst().ifPresent(o -> o.setName("includeSentJmsMessageId"));
    }
}
 
Example #7
Source File: SpringBootAutoConfigurationMojo.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
private static boolean skipComponentOption(ComponentModel model, ComponentOptionModel option) {
    if ("netty-http".equals(model.getScheme())) {
        String name = option.getName();
        if (name.equals("textline") || name.equals("delimiter") || name.equals("autoAppendDelimiter") || name.equals("decoderMaxLineLength") || name.equals("encoding")
            || name.equals("allowDefaultCodec") || name.equals("udpConnectionlessSending") || name.equals("networkInterface") || name.equals("clientMode")
            || name.equals("reconnect") || name.equals("reconnectInterval") || name.equals("useByteBuf") || name.equals("udpByteArrayCodec") || name.equals("broadcast")) {
            return true;
        }
    }
    return false;
}
 
Example #8
Source File: SpringBootAutoConfigurationMojo.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
private void createComponentSpringFactorySource(String packageName, ComponentModel model) throws MojoFailureException {
    int pos = model.getJavaType().lastIndexOf(".");
    String name = model.getJavaType().substring(pos + 1);
    name = name.replace("Component", "ComponentAutoConfiguration");

    writeComponentSpringFactorySource(packageName, name);
}
 
Example #9
Source File: SpringBootAutoConfigurationMojo.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
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." + (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);

        // 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()) || "duration".equals(option.getType())) {
                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);
}
 
Example #10
Source File: SpringBootAutoConfigurationMojo.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
private void createComponentAutoConfigurationSource(String packageName, ComponentModel model, List<String> componentAliases, String overrideComponentName)
    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 = (overrideComponentName != null ? overrideComponentName : model.getScheme()).toLowerCase(Locale.US);

    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(Conditional.class).setLiteralValue("{ConditionalOnCamelContextAndAutoConfigurationBeans.class,\n        " + name + ".GroupConditions.class}");
    javaClass.addAnnotation(AutoConfigureAfter.class).setLiteralValue("CamelAutoConfiguration.class");
    javaClass.addAnnotation(EnableConfigurationProperties.class).setLiteralValue("{ComponentConfigurationProperties.class,\n        " + configurationName + ".class}");

    javaClass.addImport(HashMap.class);
    javaClass.addImport(List.class);
    javaClass.addImport(Map.class);
    javaClass.addImport(ApplicationContext.class);
    javaClass.addImport("org.slf4j.Logger");
    javaClass.addImport("org.slf4j.LoggerFactory");
    javaClass.addImport("org.apache.camel.CamelContext");
    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.GroupCondition");
    javaClass.addImport("org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator");
    javaClass.addImport("org.apache.camel.support.IntrospectionSupport");
    javaClass.addImport("org.apache.camel.util.ObjectHelper");
    javaClass.addImport("org.apache.camel.spi.HasId");
    javaClass.addImport(model.getJavaType());

    javaClass.addField().setPrivate().setStatic(true).setFinal(true).setName("LOGGER").setType(loadClass("org.slf4j.Logger"))
        .setLiteralInitializer("LoggerFactory\n            .getLogger(" + name + ".class)");
    javaClass.addField().setPrivate().setName("applicationContext").setType(ApplicationContext.class).addAnnotation(Autowired.class);
    javaClass.addField().setPrivate().setName("camelContext").setType(loadClass("org.apache.camel.CamelContext")).addAnnotation(Autowired.class);
    javaClass.addField().setPrivate().setName("configuration").setType(configClass).addAnnotation(Autowired.class);
    javaClass.addField().setPrivate().setName("customizers").setType(loadType("java.util.List<org.apache.camel.spi.ComponentCustomizer<" + model.getJavaType() + ">>"))
        .addAnnotation(Autowired.class).setLiteralValue("required", "false");

    javaClass.addNestedType().setName("GroupConditions").setStatic(true).setPackagePrivate().extendSuperType("GroupCondition").addMethod().setName("GroupConditions")
        .setConstructor(true).setPublic().setBody("super(\"camel.component\", \"camel.component." + componentName + "\");");

    // 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(model.getJavaType())).addThrows(Exception.class);

    // Determine all the aliases
    String[] springBeanAliases = componentAliases.stream().map(alias -> alias + "-component").toArray(size -> new String[size]);

    method.addAnnotation(Lazy.class);
    method.addAnnotation(Bean.class).setStringArrayValue("name", springBeanAliases);
    method.addAnnotation(ConditionalOnMissingBean.class).setLiteralValue(model.getShortJavaType() + ".class");

    sortImports(javaClass);

    String fileName = packageName.replaceAll("\\.", "\\/") + "/" + name + ".java";
    writeSourceIfChanged(javaClass, fileName, false);
}
 
Example #11
Source File: UpdateDocComponentsListMojo.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public int compare(ComponentModel o1, ComponentModel o2) {
    // lets sort by title
    return o1.getTitle().compareToIgnoreCase(o2.getTitle());
}
 
Example #12
Source File: UpdateDocComponentsListMojo.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
private ComponentModel generateComponentModel(String json) {
    return JsonMapper.generateComponentModel(json);
}