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.component.properties;
018
019import java.util.Locale;
020
021import org.apache.camel.util.ObjectHelper;
022
023/**
024 * A {@link org.apache.camel.component.properties.PropertiesFunction} that lookup the property value from
025 * OS environment variables using the service idiom.
026 * <p/>
027 * A service is defined using two environment variables where name is name of the service:
028 * <ul>
029 *   <li><tt>NAME_SERVICE_HOST</tt></li>
030 *   <li><tt>NAME_SERVICE_PORT</tt></li>
031 * </ul>
032 * in other words the service uses <tt>_SERVICE_HOST</tt> and <tt>_SERVICE_PORT</tt> as prefix.
033 * <p/>
034 * This implementation is to return the port part only.
035 *
036 * @see ServicePropertiesFunction
037 * @see ServiceHostPropertiesFunction
038 */
039public class ServicePortPropertiesFunction implements PropertiesFunction {
040
041    private static final String PORT_PREFIX = "_SERVICE_PORT";
042
043    @Override
044    public String getName() {
045        return "service.port";
046    }
047
048    @Override
049    public String apply(String remainder) {
050        String key = remainder;
051        String defaultValue = null;
052
053        if (remainder.contains(":")) {
054            key = ObjectHelper.before(remainder, ":");
055            defaultValue = ObjectHelper.after(remainder, ":");
056        }
057
058        // make sure to use upper case
059        if (key != null) {
060            // make sure to use underscore as dash is not supported as ENV variables
061            key = key.toUpperCase(Locale.ENGLISH).replace('-', '_');
062
063            // a service should have both the host and port defined
064            String port = System.getenv(key + PORT_PREFIX);
065
066            if (port != null) {
067                return port;
068            } else {
069                return defaultValue;
070            }
071        }
072
073        return defaultValue;
074    }
075}
076