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.logging.log4j.util;
018
019import java.io.Serializable;
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.List;
025import java.util.Map;
026import java.util.Objects;
027import java.util.concurrent.ConcurrentHashMap;
028import java.util.regex.Matcher;
029import java.util.regex.Pattern;
030
031/**
032 * A source for global configuration properties.
033 *
034 * @since 2.10.0
035 */
036public interface PropertySource {
037
038    /**
039     * Returns the order in which this PropertySource has priority. A higher value means that the source will be
040     * searched later and can be overridden by other property sources.
041     *
042     * @return priority value
043     */
044    int getPriority();
045
046    /**
047     * Iterates over all properties and performs an action for each key/value pair.
048     *
049     * @param action action to perform on each key/value pair
050     */
051    default void forEach(BiConsumer<String, String> action) {
052    }
053
054    /**
055     * Returns the list of all property names.
056     * 
057     * @return list of property names
058     */
059    default Collection<String> getPropertyNames() {
060        return Collections.emptySet();
061    }
062
063    /**
064     * Converts a list of property name tokens into a normal form. For example, a list of tokens such as
065     * "foo", "bar", "baz", might be normalized into the property name "log4j2.fooBarBaz".
066     *
067     * @param tokens list of property name tokens
068     * @return a normalized property name using the given tokens
069     */
070    default CharSequence getNormalForm(Iterable<? extends CharSequence> tokens) {
071        return null;
072    }
073
074    /**
075     * For PropertySources that cannot iterate over all the potential properties this provides a direct lookup.
076     * @param key The key to search for.
077     * @return The value or null;
078     * @since 2.13.0
079     */
080    default String getProperty(String key) {
081        return null;
082    }
083
084
085    /**
086     * For PropertySources that cannot iterate over all the potential properties this provides a direct lookup.
087     * @param key The key to search for.
088     * @return The value or null;
089     * @since 2.13.0
090     */
091    default boolean containsProperty(String key) {
092        return false;
093    }
094
095    /**
096     * Comparator for ordering PropertySource instances by priority.
097     *
098     * @since 2.10.0
099     */
100    class Comparator implements java.util.Comparator<PropertySource>, Serializable {
101        private static final long serialVersionUID = 1L;
102
103        @Override
104        public int compare(final PropertySource o1, final PropertySource o2) {
105            return Integer.compare(Objects.requireNonNull(o1).getPriority(), Objects.requireNonNull(o2).getPriority());
106        }
107    }
108
109    /**
110     * Utility methods useful for PropertySource implementations.
111     *
112     * @since 2.10.0
113     */
114    final class Util {
115        private static final Pattern PREFIX_PATTERN = Pattern.compile(
116                // just lookahead for AsyncLogger
117                "(^log4j2?[-._/]?|^org\\.apache\\.logging\\.log4j\\.)|(?=AsyncLogger(Config)?\\.)",
118                Pattern.CASE_INSENSITIVE);
119        private static final Pattern PROPERTY_TOKENIZER = Pattern.compile("([A-Z]*[a-z0-9]+|[A-Z0-9]+)[-._/]?");
120        private static final Map<CharSequence, List<CharSequence>> CACHE = new ConcurrentHashMap<>();
121        static {
122            // Add legacy properties without Log4j prefix
123            CACHE.put("disableThreadContext", Arrays.asList("disable", "thread", "context"));
124            CACHE.put("disableThreadContextStack", Arrays.asList("disable", "thread", "context", "stack"));
125            CACHE.put("disableThreadContextMap", Arrays.asList("disable", "thread", "context", "map"));
126            CACHE.put("isThreadContextMapInheritable", Arrays.asList("is", "thread", "context", "map", "inheritable"));
127        }
128
129        /**
130         * Converts a property name string into a list of tokens. This will strip a prefix of {@code log4j},
131         * {@code log4j2}, {@code Log4j}, or {@code org.apache.logging.log4j}, along with separators of
132         * dash {@code -}, dot {@code .}, underscore {@code _}, and slash {@code /}. Tokens can also be separated
133         * by camel case conventions without needing a separator character in between.
134         *
135         * @param value property name
136         * @return the property broken into lower case tokens
137         */
138        public static List<CharSequence> tokenize(final CharSequence value) {
139            if (CACHE.containsKey(value)) {
140                return CACHE.get(value);
141            }
142            final List<CharSequence> tokens = new ArrayList<>();
143            int start = 0;
144            final Matcher prefixMatcher = PREFIX_PATTERN.matcher(value);
145            if (prefixMatcher.find(start)) {
146                start = prefixMatcher.end();
147                final Matcher matcher = PROPERTY_TOKENIZER.matcher(value);
148                while (matcher.find(start)) {
149                    tokens.add(matcher.group(1).toLowerCase());
150                    start = matcher.end();
151                }
152            }
153            CACHE.put(value, tokens);
154            return tokens;
155        }
156
157        /**
158         * Joins a list of strings using camelCaseConventions.
159         *
160         * @param tokens tokens to convert
161         * @return tokensAsCamelCase
162         */
163        public static CharSequence joinAsCamelCase(final Iterable<? extends CharSequence> tokens) {
164            final StringBuilder sb = new StringBuilder();
165            boolean first = true;
166            for (final CharSequence token : tokens) {
167                if (first) {
168                    sb.append(token);
169                } else {
170                    sb.append(Character.toUpperCase(token.charAt(0)));
171                    if (token.length() > 1) {
172                        sb.append(token.subSequence(1, token.length()));
173                    }
174                }
175                first = false;
176            }
177            return sb.toString();
178        }
179
180        private Util() {
181        }
182    }
183}