001    /*
002     * Copyright 2005,2009 Ivan SZKIBA
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     *      http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    package org.ini4j;
017    
018    import java.net.MalformedURLException;
019    import java.net.URL;
020    
021    import javax.servlet.ServletContext;
022    import javax.servlet.ServletContextEvent;
023    import javax.servlet.ServletContextListener;
024    
025    public class IniPreferencesFactoryListener extends IniPreferencesFactory implements ServletContextListener
026    {
027        public static final String DEFAULT_USER_LOCATION = "/WEB-INF/user.ini";
028        public static final String DEFAULT_SYSTEM_LOCATION = "/WEB-INF/system.ini";
029        private ServletContext _context;
030    
031        @Override public void contextDestroyed(ServletContextEvent event)
032        {
033            _context = null;
034        }
035    
036        @Override public void contextInitialized(ServletContextEvent event)
037        {
038            _context = event.getServletContext();
039            System.setProperty("java.util.prefs.PreferencesFactory", getClass().getName());
040        }
041    
042        @Override protected String getIniLocation(String key)
043        {
044            String location = _context.getInitParameter(key);
045    
046            if (location == null)
047            {
048                location = key.equals(KEY_USER) ? DEFAULT_USER_LOCATION : DEFAULT_SYSTEM_LOCATION;
049            }
050    
051            return location;
052        }
053    
054        @Override protected URL getResource(String location) throws IllegalArgumentException
055        {
056            try
057            {
058                URL url = _context.getResource(location);
059    
060                if (url == null)
061                {
062                    url = super.getResource(location);
063                }
064    
065                return url;
066            }
067            catch (MalformedURLException x)
068            {
069                throw (IllegalArgumentException) new IllegalArgumentException().initCause(x);
070            }
071        }
072    }