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.core.lookup;
018
019import java.util.MissingResourceException;
020import java.util.ResourceBundle;
021
022import org.apache.logging.log4j.core.LogEvent;
023import org.apache.logging.log4j.core.config.plugins.Plugin;
024
025/**
026 * Looks up keys from resource bundles.
027 */
028@Plugin(name = "bundle", category = "Lookup")
029public class ResourceBundleLookup implements StrLookup {
030
031    /**
032     * Looks up the value for the key in the format "BundleName:BundleKey".
033     * 
034     * For example: "com.domain.messages:MyKey".
035     * 
036     * @param key
037     *            the key to be looked up, may be null
038     * @return The value for the key.
039     */
040    @Override
041    public String lookup(final String key) {
042        if (key == null) {
043            return null;
044        }
045        final String[] keys = key.split(":");
046        final int keyLen = keys.length;
047        if (keyLen != 2) {
048            // throw new IllegalArgumentException("Bad key format " + key + ", format is BundleName:Value");
049            // log?
050            return null;
051        }
052        final String bundleName = keys[0];
053        final String bundleKey = keys[1];
054        try {
055            // The ResourceBundle class caches bundles, no need to cache here.
056            return ResourceBundle.getBundle(bundleName).getString(bundleKey);
057        } catch (final MissingResourceException e) {
058            // log?
059            return null;
060        }
061    }
062
063    /**
064     * Looks up the value for the key in the format "BundleName:BundleKey".
065     * 
066     * For example: "com.domain.messages:MyKey".
067     * 
068     * @param event
069     *            The current LogEvent.
070     * @param key
071     *            the key to be looked up, may be null
072     * @return The value associated with the key.
073     */
074    @Override
075    public String lookup(final LogEvent event, final String key) {
076        return lookup(key);
077    }
078}