Java Code Examples for org.apache.camel.support.PropertyBindingSupport

The following examples show how to use org.apache.camel.support.PropertyBindingSupport. These examples are extracted from open source projects. 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 Project: camel-kafka-connector   Author: apache   File: CamelMainSupport.java    License: Apache License 2.0 5 votes vote down vote up
private DataFormat lookupAndInstantiateDataformat(String dataformatName) {
    DataFormat df = camel.resolveDataFormat(dataformatName);

    if (df == null) {
        df = camel.createDataFormat(dataformatName);

        final String prefix = CAMEL_DATAFORMAT_PROPERTIES_PREFIX + dataformatName + ".";
        final Properties props = camel.getPropertiesComponent().loadProperties(k -> k.startsWith(prefix));

        CamelContextAware.trySetCamelContext(df, camel);

        if (!props.isEmpty()) {
            PropertyBindingSupport.build()
                    .withCamelContext(camel)
                    .withOptionPrefix(prefix)
                    .withRemoveParameters(false)
                    .withProperties((Map) props)
                    .withTarget(df)
                    .bind();
        }
    }

    //TODO: move it to the caller?
    if (df == null) {
        throw new UnsupportedOperationException("No DataFormat found with name " + dataformatName);
    }
    return df;
}
 
Example #2
Source Project: camel-k-runtime   Author: apache   File: PropertiesSupport.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static boolean bindProperties(CamelContext context, Object target, String prefix) {
    final PropertiesComponent component = context.getPropertiesComponent();
    final Properties properties = component.loadProperties(k -> k.startsWith(prefix));

    return PropertyBindingSupport.build()
        .withCamelContext(context)
        .withTarget(target)
        .withProperties((Map)properties)
        .withRemoveParameters(false)
        .withOptionPrefix(prefix)
        .bind();
}
 
Example #3
Source Project: camel-k-runtime   Author: apache   File: KnativeComponent.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    if (ObjectHelper.isEmpty(remaining)) {
        throw new IllegalArgumentException("Expecting URI in the form of: 'knative:type/name', got '" + uri + "'");
    }

    final String type = ObjectHelper.supplyIfEmpty(StringHelper.before(remaining, "/"), () -> remaining);
    final String name = StringHelper.after(remaining, "/");
    final KnativeConfiguration conf = getKnativeConfiguration();

    conf.getFilters().putAll(
        PropertiesHelper.extractProperties(parameters, "filter.", true)
    );
    conf.getTransportOptions().putAll(
        PropertiesHelper.extractProperties(parameters, "transport.", true)
    );
    conf.getCeOverride().putAll(
        PropertiesHelper.extractProperties(parameters, "ce.override.", true)
    );

    // set properties from the endpoint uri
    PropertyBindingSupport.bindProperties(getCamelContext(), conf, parameters);

    if (ObjectHelper.isEmpty(conf.getServiceName())) {
        conf.setServiceName(name);
    }

    return new KnativeEndpoint(uri, this, Knative.Type.valueOf(type), name, conf);
}
 
Example #4
Source Project: syndesis   Author: syndesisio   File: HandlerCustomizer.java    License: Apache License 2.0 5 votes vote down vote up
public static void setProperties(final CamelContext context, final Object target, final Map<String, Object> properties) {
    final Iterator<Map.Entry<String, Object>> iterator = properties.entrySet().iterator();

    while (iterator.hasNext()) {
        final Map.Entry<String, Object> entry = iterator.next();

        final String key = entry.getKey();
        Object val = entry.getValue();

        try {
            if (val instanceof String) {
                val = context.resolvePropertyPlaceholders((String) val);
            }

            // Bind properties to the customizer
            if (new PropertyBindingSupport.Builder()
                                                .withCamelContext(context)
                                                .withProperty(key, val)
                                                .withTarget(target)
                                                .bind()) {
                // Remove property if bound to the customizer.
                iterator.remove();
            }
        } catch (final Exception e) {
            throw new IllegalStateException("Unable to set property `" + key + "` = `" + val + "`", e);
        }
    }
}
 
Example #5
Source Project: syndesis   Author: syndesisio   File: ServiceNowMetaDataExtension.java    License: Apache License 2.0 5 votes vote down vote up
MetaContext(Map<String, Object> parameters) {
    this.parameters = parameters;
    this.configuration = new ServiceNowConfiguration();
    this.stack = new ArrayDeque<>();

    try {
        PropertyBindingSupport.bindProperties(getCamelContext(), configuration, new HashMap<>(parameters));
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    this.instanceName = ConnectorOptions.extractOption(parameters, "instanceName");
    this.objectType = ConnectorOptions.extractOption(parameters, OBJECT_TYPE, ServiceNowConstants.RESOURCE_TABLE);
    this.objectName = ConnectorOptions.extractOption(parameters, OBJECT_NAME, configuration.getTable());

    ObjectHelper.notNull(instanceName, "instanceName");

    // Configure Api and OAuthToken ULRs using instanceName
    if (!configuration.hasApiUrl()) {
        configuration.setApiUrl(String.format("https://%s.service-now.com/api", instanceName));
    }
    if (!configuration.hasOauthTokenUrl()) {
        configuration.setOauthTokenUrl(String.format("https://%s.service-now.com/oauth_token.do", instanceName));
    }

    this.client = new ServiceNowClient(getCamelContext(), configuration);
}
 
Example #6
Source Project: camel-spring-boot   Author: apache   File: CamelPropertiesHelper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Sets the properties on the target bean.
 * <p/>
 * This method uses {@link PropertyBindingSupport} and therefore offers its capabilities such as:
 * <ul>
 *     <li>property placeholders - Keys and values using Camels property placeholder will be resolved</li>
 *     <li>nested - Properties can be nested using the dot syntax (OGNL and builder pattern using with as prefix), eg foo.bar=123</li>
 *     <li>map</li> - Properties can lookup in Map's using map syntax, eg foo[bar] where foo is the name of the property that is a Map instance, and bar is the name of the key.</li>
 *     <li>list</li> - Properties can refer or add to in List's using list syntax, eg foo[0] where foo is the name of the property that is a
 *                     List instance, and 0 is the index. To refer to the last element, then use last as key.</li>
 * </ul>
 * This implementation sets the properties using the following algorithm in the given order:
 * <ul>
 *     <li>reference by bean id - Values can refer to other beans in the registry by prefixing with with # or #bean: eg #myBean or #bean:myBean</li>
 *     <li>reference by type - Values can refer to singleton beans by their type in the registry by prefixing with #type: syntax, eg #type:com.foo.MyClassType</li>
 *     <li>autowire by type - Values can refer to singleton beans by auto wiring by setting the value to #autowired</li>
 *     <li>reference new class - Values can refer to creating new beans by their class name by prefixing with #class, eg #class:com.foo.MyClassType</li>
 *     <li>value as lookup - The value is used as-is (eg like #value) to lookup in the Registry if there is a bean then its set on the target</li>
 * </ul>
 * When an option has been set on the target bean, then its removed from the given properties map. If all the options has been set, then the map will be empty.
 * The implementation ignores case for the property keys.
 *
 * @param context        the CamelContext
 * @param target         the target bean
 * @param properties     the properties
 * @param failIfNotSet   whether to fail if an option either does not exists on the target bean or if the option cannot be due no suitable setter methods with the given type
 * @return <tt>true</tt> if at least one option was configured
 * @throws IllegalArgumentException is thrown if an option cannot be configured on the bean because there is no suitable setter method and failOnNoSet is true.
 * @throws Exception for any other kind of error
 */
public static boolean setCamelProperties(CamelContext context, Object target, Map<String, Object> properties, boolean failIfNotSet) throws Exception {
    ObjectHelper.notNull(context, "context");
    ObjectHelper.notNull(target, "target");
    ObjectHelper.notNull(properties, "properties");
    boolean rc = false;

    PropertyConfigurer configurer = null;
    if (target instanceof Component) {
        // the component needs to be initialized to have the configurer ready
        ServiceHelper.initService(target);
        configurer = ((Component) target).getComponentPropertyConfigurer();
    }

    Iterator<Map.Entry<String, Object>> it = properties.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        String name = entry.getKey();
        Object value = entry.getValue();
        String stringValue = value != null ? value.toString() : null;
        boolean hit = false;
        try {
            hit = PropertyBindingSupport.build()
                    .withConfigurer(configurer)
                    .withIgnoreCase(true)
                    .bind(context, target, name, value);
        } catch (PropertyBindingException e) {
            // no we could not and this would be thrown if we attempted to set a value on a property which we cannot do type conversion as
            // then maybe the value refers to a spring bean in the registry so try this
            if (stringValue != null) {
                if (stringValue.startsWith("#")) {
                    stringValue = stringValue.substring(1);
                }
                // use #bean: to lookup
                stringValue = "#bean:" + stringValue;
                hit = PropertyBindingSupport.build().withIgnoreCase(true).bind(context, target, name, stringValue);
            }
        }

        if (hit) {
            // must remove as its a valid option and we could configure it
            it.remove();
            rc = true;
        } else if (failIfNotSet) {
            throw new IllegalArgumentException("Cannot configure option [" + name + "] with value [" + stringValue
                + "] as the bean class [" + ObjectHelper.classCanonicalName(target)
                + "] has no suitable setter method, or not possible to lookup a bean with the id [" + stringValue + "] in Spring Boot registry");
        }
    }

    return rc;
}