1   // ========================================================================
2   // $Id: PojoContextListener.java 3353 2008-07-22 10:39:41Z janb $
3   // Copyright 2008 Mort Bay Consulting Pty. Ltd.
4   // ------------------------------------------------------------------------
5   // Licensed under the Apache License, Version 2.0 (the "License");
6   // you may not use this file except in compliance with the License.
7   // You may obtain a copy of the License at 
8   // http://www.apache.org/licenses/LICENSE-2.0
9   // Unless required by applicable law or agreed to in writing, software
10  // distributed under the License is distributed on an "AS IS" BASIS,
11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  // See the License for the specific language governing permissions and
13  // limitations under the License.
14  // ========================================================================
15  
16  package org.mortbay.jetty.plus.annotation;
17  
18  import java.lang.reflect.Method;
19  
20  import javax.servlet.ServletContextEvent;
21  import javax.servlet.ServletContextListener;
22  
23  public class PojoContextListener implements ServletContextListener, PojoWrapper
24  {
25      private Object _pojo;
26      private Method _contextDestroyedMethod;
27      private Method _contextInitializedMethod;
28      private static final Class[] __params = new Class[]{ServletContextEvent.class};
29      
30      public PojoContextListener(Object pojo)
31      throws IllegalArgumentException
32      {
33          if (pojo==null)
34              throw new IllegalArgumentException("Pojo is null");
35  
36          _pojo = pojo;
37          try
38          {
39              _contextDestroyedMethod = _pojo.getClass().getDeclaredMethod("contextDestroyed", __params);
40              _contextInitializedMethod = _pojo.getClass().getDeclaredMethod("contextInitialized", __params);
41          }
42          catch (NoSuchMethodException e)
43          {
44              throw new IllegalStateException (e.getLocalizedMessage());   
45          }
46      }
47      
48      public Object getPojo()
49      {
50          return _pojo;
51      }
52  
53      public void contextDestroyed(ServletContextEvent event)
54      {
55          try
56          {
57              _contextDestroyedMethod.invoke(_pojo, new Object[]{event});
58          }
59          catch (Exception e)
60          {
61              event.getServletContext().log("Error invoking contextInitialized", e);
62          }
63  
64      }
65  
66      public void contextInitialized(ServletContextEvent event)
67      {
68          try
69          {
70              _contextInitializedMethod.invoke(_pojo, new Object[]{event});
71          }
72          catch (Exception e)
73          {
74              event.getServletContext().log("Error invoking contextInitialized", e);
75          }
76      }
77  
78  }