KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > web > server > J2EEInstanceListener


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23 package com.sun.web.server;
24
25 import java.util.*;
26 import java.security.AccessController JavaDoc;
27 import java.security.PrivilegedAction JavaDoc;
28 import java.security.AccessControlException JavaDoc;
29 import java.security.Policy JavaDoc;
30 import java.security.ProtectionDomain JavaDoc;
31 import java.security.Principal JavaDoc;
32 import javax.security.auth.Subject JavaDoc;
33 import javax.transaction.Transaction JavaDoc;
34 import javax.servlet.Servlet JavaDoc;
35 import javax.servlet.ServletRequest JavaDoc; // IASRI 4713234
36
import javax.servlet.ServletRequestWrapper JavaDoc;
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import org.apache.catalina.Realm;
39 import org.apache.catalina.InstanceEvent;
40 import org.apache.catalina.InstanceListener;
41 import org.apache.catalina.Context;
42 import org.apache.catalina.Wrapper;
43 import org.apache.jasper.servlet.JspServlet;
44 import org.apache.catalina.servlets.DefaultServlet;
45 import org.apache.coyote.tomcat5.CoyoteRequestFacade;
46 import com.sun.enterprise.*;
47 import com.sun.enterprise.deployment.*;
48 import com.sun.enterprise.appverification.factory.AppVerification;
49 import com.sun.enterprise.security.LoginContext;
50 import com.sun.enterprise.security.SecurityContext; // IASRI 4688449
51
import com.sun.enterprise.log.Log;
52 import com.sun.web.security.RealmAdapter;
53 import com.sun.web.security.WebPrincipal;
54
55
56 //START OF IASRI 4660742
57
import java.util.logging.*;
58 import com.sun.logging.*;
59 //END OF IASRI 4660742
60

61 /**
62  * This class implements the Tomcat InstanceListener interface and
63  * handles the INIT,DESTROY and SERVICE, FILTER events.
64  * @author Vivek Nagar
65  * @author Tony Ng
66  */

67 public final class J2EEInstanceListener implements InstanceListener {
68
69     // START OF IASRI 4660742
70
static Logger _logger=LogDomains.getLogger(LogDomains.WEB_LOGGER);
71     // END OF IASRI 4660742
72

73
74     private InvocationManager im;
75     private J2EETransactionManager tm;
76     private InjectionManager injectionMgr;
77     // private LoginContext lc = null;
78

79     public J2EEInstanceListener() {
80         im = Switch.getSwitch().getInvocationManager();
81         tm = Switch.getSwitch().getTransactionManager();
82         injectionMgr = Switch.getSwitch().getInjectionManager();
83     // lc = new LoginContext();
84
}
85
86     public void instanceEvent(InstanceEvent event) {
87         String JavaDoc eventType = event.getType();
88     if(_logger.isLoggable(Level.FINEST)) {
89             _logger.log(Level.FINEST,"*** InstanceEvent: " + eventType);
90         }
91         if (eventType.equals(InstanceEvent.BEFORE_SERVICE_EVENT) ||
92             eventType.equals(InstanceEvent.BEFORE_FILTER_EVENT) ||
93             eventType.equals(InstanceEvent.BEFORE_INIT_EVENT) ||
94             eventType.equals(InstanceEvent.BEFORE_DESTROY_EVENT) ||
95             eventType.equals(InstanceEvent.BEFORE_DISPATCH_EVENT)) {
96
97             handleBeforeEvent(event, eventType);
98         } else if (eventType.equals(InstanceEvent.AFTER_SERVICE_EVENT) ||
99                    eventType.equals(InstanceEvent.AFTER_FILTER_EVENT) ||
100                    eventType.equals(InstanceEvent.AFTER_INIT_EVENT) ||
101                    eventType.equals(InstanceEvent.AFTER_DESTROY_EVENT) ||
102                    eventType.equals(InstanceEvent.AFTER_DISPATCH_EVENT)) {
103             handleAfterEvent(event, eventType);
104         } else {
105             // ignore additional events
106
//throw new IllegalStateException("Invalid event type: " +
107
//eventType);
108
}
109     }
110
111     private void handleBeforeEvent(InstanceEvent event, String JavaDoc eventType) {
112
113         Object JavaDoc instance = null;
114         if (eventType.equals(InstanceEvent.BEFORE_FILTER_EVENT)) {
115             instance = event.getFilter();
116         } else {
117             instance = event.getServlet();
118         }
119         Context context = (Context) event.getWrapper().getParent();
120
121         // set context class loader for use by RMIClassLoader
122
final ClassLoader JavaDoc cl = context.getLoader().getClassLoader();
123         AccessController.doPrivileged
124             (new PrivilegedAction JavaDoc() {
125                 public Object JavaDoc run() {
126                     Thread.currentThread().setContextClassLoader(cl);
127                     return null;
128                 }
129             });
130
131         // set security context
132
// BEGIN IASRI 4688449
133
//try {
134
Realm ra = context.getRealm();
135         /** IASRI 4713234
136         if (ra != null) {
137             HttpServletRequest request =
138                 (HttpServletRequest) event.getRequest();
139             if (request != null && request.getUserPrincipal() != null) {
140                 WebPrincipal prin =
141                     (WebPrincipal) request.getUserPrincipal();
142                 // ra.authenticate(prin);
143                 
144                 // It is inefficient to call authenticate just to set
145                 // sec.ctx. Instead, WebPrincipal modified to keep the
146                 // previously created secctx, and set it here directly.
147
148                 SecurityContext.setCurrent(prin.getSecurityContext());
149             }
150         }
151         **/

152         // START OF IASRI 4713234
153
if (ra != null) {
154
155             ServletRequest JavaDoc request =
156         (ServletRequest JavaDoc) event.getRequest();
157             if (request != null && request instanceof HttpServletRequest JavaDoc) {
158
159                 HttpServletRequest JavaDoc hreq = (HttpServletRequest JavaDoc)request;
160         HttpServletRequest JavaDoc base = hreq;
161         
162         Principal JavaDoc prin = hreq.getUserPrincipal();
163         Principal JavaDoc basePrincipal = prin;
164         
165         boolean wrapped = false;
166
167         while (prin != null && base != null) {
168             
169             if (base instanceof ServletRequestWrapper JavaDoc) {
170             // unwarp any wrappers to find the base object
171
ServletRequest JavaDoc sr =
172                 ((ServletRequestWrapper JavaDoc) base).getRequest();
173
174             if (sr instanceof HttpServletRequest JavaDoc) {
175
176                 base = (HttpServletRequest JavaDoc) sr;
177                 wrapped = true;
178                 continue;
179             }
180             }
181
182             if (wrapped) {
183             basePrincipal = base.getUserPrincipal();
184             }
185
186             else if (base instanceof CoyoteRequestFacade) {
187             // try to avoid the getUnWrappedCoyoteRequest call
188
// when we can identify see we have the texact class.
189
if (base.getClass() != CoyoteRequestFacade.class) {
190                 basePrincipal = ((CoyoteRequestFacade)base).
191                 getUnwrappedCoyoteRequest().getUserPrincipal();
192             }
193             } else {
194             basePrincipal = base.getUserPrincipal();
195             }
196
197             break;
198         }
199
200         if (prin != null && prin == basePrincipal &&
201             prin instanceof WebPrincipal) {
202
203             SecurityContext.setCurrent
204             (getSecurityContextForPrincipal(prin));
205             
206         } else if (prin != basePrincipal) {
207             
208             // the wrapper has overridden getUserPrincipal
209
// reject the request if the wrapper does not have
210
// the necessary permission.
211

212             checkObjectForDoAsPermission(hreq);
213
214             SecurityContext.setCurrent
215             (getSecurityContextForPrincipal(prin));
216         }
217         }
218         }
219         // END OF IASRI 4713234
220
//} catch (Exception ex) {
221
/** IASRI 4660742
222             ex.printStackTrace();
223               **/

224               // START OF IASRI 4660742
225
//_logger.log(Level.SEVERE,"web_server.excep_handle_before_event",ex);
226
// END OF IASRI 4660742
227
//}
228
// END IASRI 4688449
229

230         ComponentInvocation inv = new ComponentInvocation(instance, context);
231         try {
232             im.preInvoke(inv);
233             if (eventType.equals(InstanceEvent.BEFORE_SERVICE_EVENT)) {
234                 // enlist resources with TM for service method
235
Transaction JavaDoc tran = null;
236                 if ((tran = tm.getTransaction()) != null) {
237                     inv.setTransaction(tran);
238                 }
239                 tm.enlistComponentResources();
240             } else if(eventType.equals(InstanceEvent.BEFORE_INIT_EVENT)) {
241                 
242                 // Perform any required resource injection on the servlet
243
// instance. This needs to be done after the invocation
244
// preInvoke step but before any of the servlet's
245
// application code can execute.
246
JndiNameEnvironment desc = (JndiNameEnvironment)
247                     Switch.getSwitch().getDescriptorFor(context);
248
249                 // There won't be a corresponding J2EE naming environment
250
// descriptor for certain internal servlets so just skip
251
// injection for those ones.
252
if( desc != null
253                         && instance.getClass() != DefaultServlet.class
254                         && instance.getClass() != JspServlet.class) {
255                     injectionMgr.injectInstance(instance, desc);
256                 }
257
258             }
259         } catch (Exception JavaDoc ex) {
260             throw new RuntimeException JavaDoc(
261                 _logger.getResourceBundle().getString(
262                     "web_server.excep_handle_before_event"),
263                 ex);
264         }
265     }
266
267     private static javax.security.auth.AuthPermission JavaDoc doAsPrivilegedPerm =
268     new javax.security.auth.AuthPermission JavaDoc("doAsPrivileged");
269  
270     private static void
271     checkObjectForDoAsPermission(final Object JavaDoc o) throws AccessControlException JavaDoc{
272     if (System.getSecurityManager() != null) {
273         AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
274         public Object JavaDoc run() {
275             ProtectionDomain JavaDoc pD = o.getClass().getProtectionDomain();
276             Policy JavaDoc p = Policy.getPolicy();
277             if (!p.implies(pD,doAsPrivilegedPerm)) {
278             throw new AccessControlException JavaDoc
279                 ("permission required to override getUserPrincipal",
280                  doAsPrivilegedPerm);
281             }
282             return null;
283         }
284         });
285     }
286     }
287
288     private static SecurityContext
289     getSecurityContextForPrincipal(final Principal JavaDoc p) {
290     if (p == null) {
291         return null;
292     } else if (p instanceof WebPrincipal) {
293         return ((WebPrincipal) p).getSecurityContext();
294     } else {
295         return (SecurityContext)
296         AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
297             public Object JavaDoc run() {
298             Subject JavaDoc s = new Subject JavaDoc();
299             s.getPrincipals().add(p);
300             return new SecurityContext(p.getName(),s);
301             }
302         });
303     }
304     }
305
306     private void handleAfterEvent(InstanceEvent event, String JavaDoc eventType) {
307
308         if (AppVerification.doInstrument()
309                 && (eventType.equals(InstanceEvent.AFTER_SERVICE_EVENT)
310                         || eventType.equals(InstanceEvent.AFTER_INIT_EVENT)
311                         || eventType.equals(InstanceEvent.AFTER_DISPATCH_EVENT))) {
312             
313             AppVerification.getInstrumentLogger().doInstrumentForWeb(event);
314         }
315         
316         Object JavaDoc instance = null;
317         if (eventType.equals(InstanceEvent.AFTER_FILTER_EVENT)) {
318             instance = event.getFilter();
319         } else {
320             instance = event.getServlet();
321         }
322         Context context = (Context) event.getWrapper().getParent();
323         ComponentInvocation inv = new ComponentInvocation(instance, context);
324         try {
325             im.postInvoke(inv);
326         } catch (Exception JavaDoc ex) {
327             throw new RuntimeException JavaDoc(
328                 _logger.getResourceBundle().getString(
329                     "web_server.excep_handle_after_event"),
330                 ex);
331         } finally {
332             if (eventType.equals(InstanceEvent.AFTER_DESTROY_EVENT)) {
333                 tm.componentDestroyed(instance);
334             }
335             if (eventType.equals(InstanceEvent.AFTER_FILTER_EVENT) ||
336                 eventType.equals(InstanceEvent.AFTER_SERVICE_EVENT)) {
337                 // check it's top level invocation
338
// BEGIN IASRI# 4646060
339
if (im.getCurrentInvocation() == null) {
340                 // END IASRI# 4646060
341
try {
342                         // clear security context
343
Realm ra = context.getRealm();
344                         if (ra != null && (ra instanceof RealmAdapter)) {
345                             ((RealmAdapter)ra).logout();
346                         }
347                     } catch (Exception JavaDoc ex) {
348                         /** IASRI 4660742
349                         ex.printStackTrace();
350                         **/

351                         // START OF IASRI 4660742
352
_logger.log(Level.SEVERE,
353                                         "web_server.excep_handle_after_event",
354                                         ex);
355                         // END OF IASRI 4660742
356
}
357                     try {
358                         if (tm.getTransaction() != null) {
359                             tm.rollback();
360                         }
361                         tm.cleanTxnTimeout();
362                     } catch (Exception JavaDoc ex) {}
363                 }
364                 tm.componentDestroyed(instance);
365             }
366         }
367     }
368 }
369
370
Popular Tags