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 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 host part only. 035 * 036 * @see ServicePropertiesFunction 037 * @see ServicePortPropertiesFunction 038 */ 039public class ServiceHostPropertiesFunction implements PropertiesFunction { 040 041 private static final String HOST_PREFIX = "_SERVICE_HOST"; 042 043 @Override 044 public String getName() { 045 return "service.host"; 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 = StringHelper.before(remainder, ":"); 055 defaultValue = StringHelper.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 host = System.getenv(key + HOST_PREFIX); 065 066 if (host != null) { 067 return host; 068 } else { 069 return defaultValue; 070 } 071 } 072 073 return defaultValue; 074 } 075} 076