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.util; 018 019/** 020 * A resolver for file paths that supports resolving with system and environment properties. 021 */ 022public final class FilePathResolver { 023 024 private FilePathResolver() { 025 } 026 027 /** 028 * Resolves the path. 029 * <p/> 030 * The pattern is: 031 * <ul> 032 * <li><tt>${env.key}</tt> for environment variables.</li> 033 * <li><tt>${key}</tt> for JVM system properties.</li> 034 * </ul> 035 * For example: <tt>${env.KARAF_HOME}/data/logs</tt> 036 * 037 * @param path the path 038 * @return the resolved path 039 * @throws IllegalArgumentException is thrown if system property / environment not found 040 */ 041 public static String resolvePath(String path) throws IllegalArgumentException { 042 int count = StringHelper.countChar(path, '}') + 1; 043 if (count <= 1) { 044 return path; 045 } 046 047 String[] functions = StringHelper.splitOnCharacter(path, "}", count); 048 for (String fun : functions) { 049 int pos = fun.indexOf("${env."); 050 if (pos != -1) { 051 String key = fun.substring(pos + 6); 052 String value = System.getenv(key); 053 if (value != null) { 054 path = path.replace("${env." + key + "}", value); 055 } 056 } 057 } 058 059 count = StringHelper.countChar(path, '}') + 1; 060 if (count <= 1) { 061 return path; 062 } 063 functions = StringHelper.splitOnCharacter(path, "}", count); 064 for (String fun : functions) { 065 int pos = fun.indexOf("${"); 066 if (pos != -1) { 067 String key = fun.substring(pos + 2); 068 String value = System.getProperty(key); 069 if (value != null) { 070 path = path.replace("${" + key + "}", value); 071 } 072 } 073 } 074 075 return path; 076 } 077 078}