001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.camel.impl;
018
019import java.lang.reflect.Field;
020import java.net.URI;
021import java.net.URISyntaxException;
022import java.util.Map;
023
024import org.apache.camel.CamelContext;
025import org.apache.camel.Component;
026import org.apache.camel.EndpointConfiguration;
027import org.apache.camel.RuntimeCamelException;
028import org.apache.camel.URIField;
029import org.apache.camel.util.IntrospectionSupport;
030import org.apache.camel.util.URISupport;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033
034/**
035 * Some helper methods for working with {@link EndpointConfiguration} instances
036 *
037 */
038public final class ConfigurationHelper {
039
040    private static final Logger LOG = LoggerFactory.getLogger(ConfigurationHelper.class);
041
042    private ConfigurationHelper() {
043        //Utility Class
044    }
045
046    public interface ParameterSetter {
047
048        /**
049         * Sets the parameter on the configuration.
050         *
051         * @param camelContext  the camel context
052         * @param config        the configuration
053         * @param name          the name of the parameter
054         * @param value         the value to set
055         * @throws RuntimeCamelException is thrown if error setting the parameter
056         */
057        <T> void set(CamelContext camelContext, EndpointConfiguration config, String name, T value) throws RuntimeCamelException;
058    }
059
060    public static EndpointConfiguration createConfiguration(String uri, CamelContext context) throws Exception {
061        int schemeSeparator = uri.indexOf(':');
062        if (schemeSeparator == -1) {
063            // not an URIConfiguration
064            return null;
065        }
066        String scheme = uri.substring(0, schemeSeparator);
067        
068        Component component = context.getComponent(scheme);
069        if (LOG.isTraceEnabled()) {
070            LOG.trace("Lookup for Component handling \"{}:\" configuration returned {}",
071                new Object[]{scheme, component != null ? component.getClass().getName() : "<null>"});
072        }
073        if (component != null) {
074            EndpointConfiguration config = component.createConfiguration(scheme);
075            if (config instanceof DefaultEndpointConfiguration) {
076                ((DefaultEndpointConfiguration) config).setURI(uri);
077            }
078            return config;
079        } else {
080            // no component to create the configuration
081            return null;
082        }
083    }
084    
085    public static void populateFromURI(CamelContext camelContext, EndpointConfiguration config, ParameterSetter setter) {
086        URI uri = config.getURI();
087        
088        setter.set(camelContext, config, EndpointConfiguration.URI_SCHEME, uri.getScheme());
089        setter.set(camelContext, config, EndpointConfiguration.URI_SCHEME_SPECIFIC_PART, uri.getSchemeSpecificPart());
090        setter.set(camelContext, config, EndpointConfiguration.URI_AUTHORITY, uri.getAuthority());
091        setter.set(camelContext, config, EndpointConfiguration.URI_USER_INFO, uri.getUserInfo());
092        setter.set(camelContext, config, EndpointConfiguration.URI_HOST, uri.getHost());
093        setter.set(camelContext, config, EndpointConfiguration.URI_PORT, Integer.toString(uri.getPort()));
094        setter.set(camelContext, config, EndpointConfiguration.URI_PATH, uri.getPath());
095        setter.set(camelContext, config, EndpointConfiguration.URI_QUERY, uri.getQuery());
096        setter.set(camelContext, config, EndpointConfiguration.URI_FRAGMENT, uri.getFragment());
097        
098        // now parse query and set custom parameters
099        Map<String, Object> parameters;
100        try {
101            parameters = URISupport.parseParameters(uri);
102            for (Map.Entry<String, Object> pair : parameters.entrySet()) {
103                setter.set(camelContext, config, pair.getKey(), pair.getValue());
104            }
105        } catch (URISyntaxException e) {
106            throw new RuntimeCamelException(e);
107        }
108    }
109
110    public static Field findConfigurationField(EndpointConfiguration config, String name) {
111        if (config != null && name != null) {
112            Class<?> clazz = config.getClass();
113            Field[] fields = clazz.getDeclaredFields();
114    
115            Field found;
116            URIField anno;
117            for (final Field field : fields) {
118                anno = field.getAnnotation(URIField.class);
119                if (anno == null ? field.getName().equals(name) : anno.component().equals(name) 
120                    || (anno.component().equals(EndpointConfiguration.URI_QUERY) && anno.parameter().equals(name))) { 
121    
122                    found = field;
123                    LOG.trace("Found field {}.{} as candidate for parameter {}", new Object[]{clazz.getName(), found.getName(), name});
124                    return found;
125                }
126            }
127        }            
128        return null;
129    }
130
131    public static Object getConfigurationParameter(EndpointConfiguration config, String name) {
132        Field field = findConfigurationField(config, name);
133        return getConfigurationParameter(config, field);
134    }
135
136    public static Object getConfigurationParameter(EndpointConfiguration config, Field field) {
137        if (field != null) {
138            try {
139                return IntrospectionSupport.getProperty(config, field.getName());
140            } catch (Exception e) {
141                throw new RuntimeCamelException("Failed to get property '" + field.getName() + "' on " + config + " due " + e.getMessage(), e);
142            }
143        }
144        return null;
145    }
146
147    public static <T> void setConfigurationField(CamelContext camelContext, EndpointConfiguration config, String name, T value) {
148        Field field = findConfigurationField(config, name);
149        if (field == null) {
150            return;
151        }
152
153        try {
154            IntrospectionSupport.setProperty(camelContext.getTypeConverter(), config, name, value);
155        } catch (Exception e) {
156            throw new RuntimeCamelException("Failed to set property '" + name + "' on " + config + " due " + e.getMessage(), e);
157        }
158    }
159    
160    public static class FieldParameterSetter implements ParameterSetter {
161        @Override
162        public <T> void set(CamelContext camelContext, EndpointConfiguration config, String name, T value) {
163            setConfigurationField(camelContext, config, name, value);
164        }
165    }
166}