View Javadoc

1   /*
2    * Copyright 2005,2009 Ivan SZKIBA
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.ini4j;
17  
18  import java.net.MalformedURLException;
19  import java.net.URL;
20  
21  import javax.servlet.ServletContext;
22  import javax.servlet.ServletContextEvent;
23  import javax.servlet.ServletContextListener;
24  
25  public class IniPreferencesFactoryListener extends IniPreferencesFactory implements ServletContextListener
26  {
27      public static final String DEFAULT_USER_LOCATION = "/WEB-INF/user.ini";
28      public static final String DEFAULT_SYSTEM_LOCATION = "/WEB-INF/system.ini";
29      private ServletContext _context;
30  
31      @Override public void contextDestroyed(ServletContextEvent event)
32      {
33          _context = null;
34      }
35  
36      @Override public void contextInitialized(ServletContextEvent event)
37      {
38          _context = event.getServletContext();
39          System.setProperty("java.util.prefs.PreferencesFactory", getClass().getName());
40      }
41  
42      @Override protected String getIniLocation(String key)
43      {
44          String location = _context.getInitParameter(key);
45  
46          if (location == null)
47          {
48              location = key.equals(KEY_USER) ? DEFAULT_USER_LOCATION : DEFAULT_SYSTEM_LOCATION;
49          }
50  
51          return location;
52      }
53  
54      @Override protected URL getResource(String location) throws IllegalArgumentException
55      {
56          try
57          {
58              URL url = _context.getResource(location);
59  
60              if (url == null)
61              {
62                  url = super.getResource(location);
63              }
64  
65              return url;
66          }
67          catch (MalformedURLException x)
68          {
69              throw (IllegalArgumentException) new IllegalArgumentException().initCause(x);
70          }
71      }
72  }