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.StringHelper; 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 */ 034public class ServicePropertiesFunction implements PropertiesFunction { 035 036 private static final String HOST_PREFIX = "_SERVICE_HOST"; 037 private static final String PORT_PREFIX = "_SERVICE_PORT"; 038 039 @Override 040 public String getName() { 041 return "service"; 042 } 043 044 @Override 045 public String apply(String remainder) { 046 String key = remainder; 047 String defaultValue = null; 048 049 if (remainder.contains(":")) { 050 key = StringHelper.before(remainder, ":"); 051 defaultValue = StringHelper.after(remainder, ":"); 052 } 053 054 // make sure to use upper case 055 if (key != null) { 056 // make sure to use underscore as dash is not supported as ENV variables 057 key = key.toUpperCase(Locale.ENGLISH).replace('-', '_'); 058 059 // a service should have both the host and port defined 060 String host = System.getenv(key + HOST_PREFIX); 061 String port = System.getenv(key + PORT_PREFIX); 062 063 if (host != null && port != null) { 064 return host + ":" + port; 065 } else { 066 return defaultValue; 067 } 068 } 069 070 return defaultValue; 071 } 072} 073