001// Copyright 2009 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.ioc.internal.services;
016
017import org.apache.tapestry5.commons.Resource;
018import org.apache.tapestry5.commons.util.CollectionFactory;
019import org.apache.tapestry5.ioc.internal.util.InternalUtils;
020import org.apache.tapestry5.ioc.services.SymbolProvider;
021
022import java.io.IOException;
023import java.io.InputStream;
024import java.util.Map;
025import java.util.Properties;
026
027/**
028 * Makes a {@link org.apache.tapestry5.commons.Resource} available as a {@link org.apache.tapestry5.ioc.services.SymbolProvider}
029 *
030 * @since 5.1.0.5
031 */
032public class ResourceSymbolProvider implements SymbolProvider
033{
034    private final Resource resource;
035
036    private final Map<String, String> properties = CollectionFactory.newCaseInsensitiveMap();
037
038    public ResourceSymbolProvider(final Resource resource)
039    {
040        this.resource = resource;
041
042        readProperties();
043    }
044
045    private void readProperties()
046    {
047        Properties p = new Properties();
048
049        InputStream is = null;
050
051        try
052        {
053            is = resource.openStream();
054
055            p.load(is);
056
057            is.close();
058
059            is = null;
060
061            for (Map.Entry<Object, Object> entry : p.entrySet())
062            {
063                String key = entry.getKey().toString();
064
065                properties.put(key, p.getProperty(key));
066            }
067        }
068        catch (IOException ex)
069        {
070            throw new RuntimeException(ex);
071        }
072        finally
073        {
074            InternalUtils.close(is);
075        }
076    }
077
078    @Override
079    public String valueForSymbol(String symbolName)
080    {
081        return properties.get(symbolName);
082    }
083}