KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > server > core > ConfigInterceptor


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
24 package com.sun.enterprise.admin.server.core;
25
26 import java.util.List JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.logging.Level JavaDoc;
30 import java.util.logging.Logger JavaDoc;
31 import java.util.Properties JavaDoc;
32 import java.util.Enumeration JavaDoc;
33
34 import javax.management.ObjectName JavaDoc;
35 import javax.management.Attribute JavaDoc;
36
37 import com.sun.enterprise.admin.AdminContext;
38 import com.sun.enterprise.admin.event.AdminEvent;
39 import com.sun.enterprise.admin.event.AdminEventCache;
40 import com.sun.enterprise.admin.event.AdminEventMulticaster;
41 import com.sun.enterprise.admin.event.AdminEventResult;
42 import com.sun.enterprise.admin.event.ElementChangeHelper;
43 import com.sun.enterprise.admin.util.proxy.CallStack;
44 import com.sun.enterprise.admin.util.proxy.Call;
45 import com.sun.enterprise.admin.util.proxy.InterceptorImpl;
46 import com.sun.enterprise.admin.event.EventStack;
47 import com.sun.enterprise.admin.event.EventContext;
48 import com.sun.enterprise.config.ConfigContext;
49 import com.sun.enterprise.config.ConfigException;
50 import com.sun.enterprise.admin.event.ResourceDeployEvent;
51 import com.sun.enterprise.admin.event.BaseDeployEvent;
52 import com.sun.enterprise.security.SecurityContext;
53 import com.sun.enterprise.security.audit.AuditManager;
54 import com.sun.enterprise.security.audit.AuditManagerFactory;
55
56 import com.sun.enterprise.admin.event.pluggable.RestartEventHelper;
57 import com.sun.enterprise.server.pluggable.PluggableFeatureFactory;
58 import com.sun.enterprise.server.ApplicationServer;
59 import com.sun.enterprise.server.ServerContext;
60 import com.sun.enterprise.admin.event.pluggable.NotificationFactory;
61
62
63 /**
64  * Config interceptor for MBeans
65  */

66 public class ConfigInterceptor extends InterceptorImpl {
67
68     private AdminContext adminContext;
69     private Logger JavaDoc _logger;
70     private static AuditManager auditManager =
71             AuditManagerFactory.getAuditManagerInstance();
72
73     public ConfigInterceptor() {
74     }
75
76     public ConfigInterceptor(AdminContext ctx) {
77         adminContext = ctx;
78         if (adminContext != null) {
79             _logger = adminContext.getAdminLogger();
80         } else {
81             _logger = Logger.getLogger("global");
82         }
83     }
84
85     /**
86      * We flush configcontext only in the last return of
87      * setAttribute, setAttributes or invoke.
88      * Send notification if flush is successfull
89      *
90      * Failure cases will be handled later
91      */

92     public void postInvoke(CallStack callStack) {
93
94         
95         if (callStack.getStackSize() == 1) {
96             Call call = callStack.getActiveCall();
97             if (call.getState().isSuccess() && isFlushNeeded(call)) {
98                 try {
99                     ConfigContext ctx = adminContext.getAdminConfigContext();
100                     if (ctx.isChanged()) {
101                         ctx.flush();
102                     }
103                 } catch (ConfigException ce) {
104                     _logger.log(Level.WARNING,
105                         "core.config_exception_occurred", ce);
106                 }
107             }
108             if (isFlushNeeded(call)) {
109                 new AdminNotificationHelper(adminContext).sendNotification();
110             }
111         }
112         auditInvocation(callStack.getActiveCall());
113
114         
115     }
116     
117     /**
118      * Flush is needed only for those methods that change
119      * configcontext. These are setAttribute(s) and invoke
120      */

121     private boolean isFlushNeeded(Call call) {
122         String JavaDoc methodName = call.getMethod().getName();
123         if( methodName.equals("setAttribute") ||
124             methodName.equals("setAttributes") ||
125             (methodName.equals("invoke") && !isReadonlyInvokeOperation(call))) {
126                 return true;
127         }
128         return false;
129     }
130
131     private boolean isReadonlyInvokeOperation(Call call) {
132
133         try {
134             Object JavaDoc[] args = call.getArguments();
135             if(args!=null && args.length>1)
136             {
137                 String JavaDoc operationName = (String JavaDoc) (args[1]);
138
139                 // skips notification if this is a ping for deployment status
140
if("takeNotifications".equals(operationName)) {
141                     return true;
142                 }
143             }
144         } catch(Throwable JavaDoc t){ }
145
146         return false;
147     }
148
149     public void preInvoke(CallStack callstack) {
150
151         if (callstack.getStackSize() == 1) {
152             EventStack stack = new EventStack();
153             stack.setConfigContext(adminContext.getAdminConfigContext());
154             EventContext.setEventStackToThreadLocal(stack);
155         }
156
157     }
158
159 /*
160     private void sendNotification() {
161         ConfigContext context = adminContext.getAdminConfigContext();
162         String instanceName = adminContext.getServerName();
163         AdminEventCache cache =
164                 AdminEventCache.getInstance(instanceName);
165         cache.setAdminConfigContext(context);
166         ArrayList changeList = context.getConfigChangeList();
167         context.resetConfigChangeList();
168         ArrayList eventList = null;
169         if (changeList.size() <= 0) {
170             eventList = new ArrayList();
171             // Return, no changes to process
172             //return;
173         }
174         else
175         {
176             cache.processConfigChangeList(changeList, false, false);
177             eventList = cache.getAndResetCachedEvents();
178
179             //***********************************
180             //ElementChange events
181             try {
182             ElementChangeHelper elementHelper = new ElementChangeHelper(); //FIXME: need to put it as member
183             AdminEvent[] elementChangeEvents = elementHelper.generateElementChangeEventsFromChangeList(instanceName, changeList, context);
184             if(elementChangeEvents!=null)
185                 for(int i=0; i<elementChangeEvents.length; i++)
186                     eventList.add(elementChangeEvents[i]);
187             } catch (Exception e) {
188                 // ignore
189             }
190             //***********************************
191
192         }
193         EventStack stack = EventContext.getEventStackFromThreadLocal();
194         List newEventList = stack.getEvents();
195         newEventList.addAll(eventList);
196
197         boolean requiresRestart = false;
198
199         Iterator iter = newEventList.iterator();
200         while (iter.hasNext()) {
201             AdminEvent event = (AdminEvent)iter.next();
202             if (_logger.isLoggable(Level.FINEST)) {
203                 _logger.log(Level.FINEST, "mbean.event_sent",
204                         event.getEventInfo());
205             } else {
206                 _logger.log(Level.INFO, "mbean.send_event", event.toString());
207             }
208             AdminEventResult result=AdminEventMulticaster.multicastEvent(event);
209             _logger.log(Level.FINE, "mbean.event_res", result.getResultCode());
210             _logger.log(Level.FINEST, "mbean.event_reply",
211                     result.getAllMessagesAsString());
212             if (!AdminEventResult.SUCCESS.equals(result.getResultCode())) {
213                 requiresRestart = true;
214                 cache.setRestartNeeded(true);
215                 // if there was an error in the listener, admin event
216                 // multicaster already sets the restart required to true
217                 //_logger.log(Level.INFO, "mbean.notif_failed");
218                 _logger.log(Level.INFO, "mbean.event_result_error",
219                         result.getAllResultCodesAsString() );
220             }
221
222         }
223         ServerContext svcCtx = ApplicationServer.getServerContext();
224         PluggableFeatureFactory featureFactory = null;
225         if (svcCtx != null) {
226             featureFactory = svcCtx.getPluggableFeatureFactory();
227             
228             // see if there were any non reconfigurabled changes
229             NotificationFactory nFactory =
230                 featureFactory.getNotificationFactory();
231             RestartEventHelper helper = nFactory.createRestartEventHelper();
232             helper.setRestartRequiredForTarget(context, changeList);
233             
234         }
235         return;
236     }
237 */

238
239
240     //*****************************************************************************
241
/*
242      * ADMIN AUDIT FOR CALL
243      */

244     private void auditInvocation(Call call)
245     {
246         if(auditManager.isAuditOn())
247         {
248             if (/*auditManager.isAuditOn() &&*/ isAuditable(call)){
249                 SecurityContext sc = SecurityContext.getCurrent();
250 //XXX remove audit API
251
/*
252                 auditManager.adminInvocation(
253                     sc.getCallerPrincipal().getName(), //caller
254                     sc.getSubject(), //subject
255                     auditManager.getRemoteHost(), // host
256                     getObjectNameForCall(call),//ObjectName
257                     getOperationName(call), //operation name
258                     "JMXLocal", //mode JMXLocal,JMXRemote-http,JMXRemote-rmi,JMXRemote-jmxmp
259                     getAuditedParamsString(call),
260                     call.getState().isSuccess());
261 */

262 /*
263 System.out.println(
264 "\nCaller: "+sc.getCallerPrincipal().getName() +
265 "\nSubject: "+ sc.getSubject() +
266 "\nHost: "+ auditManager.getRemoteHost() +
267 "\nObjectName: "+ getObjectNameForCall(call)+
268 "\nOperation: "+ getOperationName(call)+
269 "\nParams: "+ getAuditedParamsString(call)+
270 "\nSuccess: "+ call.getState().isSuccess() );
271 */

272             }
273         }
274     }
275     /**
276      * check call using method name/params/objectname
277      * - whether it auditable or not
278      */

279     private boolean isAuditable(Call call) {
280         if(call==null)
281             return false;
282         String JavaDoc methodName = call.getMethod().getName();
283         if( !methodName.equals("setAttribute") &&
284             !methodName.equals("setAttributes") &&
285             !methodName.equals("invoke"))
286                 return false;
287         if(methodName.equals("invoke"))
288         {
289             String JavaDoc opName = getOperationName(call);
290             if(opName==null ||
291                opName.startsWith("get") ||
292                opName.startsWith("list") ||
293                opName.startsWith("is") )
294                 return false;
295         }
296         String JavaDoc objectName = getObjectNameForCall(call);
297         if(objectName==null || objectName.indexOf("category=config")<0)
298             return false;
299         return true;
300     }
301     
302     
303     /**
304      * returns OperationName invoking in MBean
305      */

306     private String JavaDoc getOperationName(Call call) {
307         if(call==null)
308             return null;
309         String JavaDoc methodName = call.getMethod().getName();
310         if(methodName.equals("invoke"))
311         {
312             Object JavaDoc[] params = call.getArguments();
313             if(params!=null && params.length>1 && (params[1] instanceof String JavaDoc))
314                 methodName = (String JavaDoc)params[1];
315         }
316         return methodName;
317     }
318
319     /**
320      * represents parameters of call in printable form fro audit module
321      */

322     private String JavaDoc getAuditedParamsString(Call call) {
323         if(call==null)
324             return null;
325         Object JavaDoc[] params = call.getArguments();
326         if(params==null)
327             return null;
328         int i=0;
329         String JavaDoc methodName = call.getMethod().getName();
330         if(methodName.equals("invoke"))
331         {
332             if(params.length>2)
333                 return paramToString(params[2]);
334         }
335         else
336             if(methodName.equals("setAttribute") ||
337                 methodName.equals("setAttributes") )
338             {
339                 if(params.length>1)
340                     return paramToString(params[1]);
341             }
342         return null;
343     }
344     
345     /**
346      * represents parameter of call in printable form fro audit module
347      */

348     private String JavaDoc paramToString(Object JavaDoc obj) {
349         if(obj==null)
350             return null;
351         String JavaDoc res = null;
352         if(obj instanceof Object JavaDoc[])
353         {
354             res = "{";
355             for(int i=0; i<((Object JavaDoc[])obj).length; i++)
356                 res += paramToString(((Object JavaDoc[])obj)[i]) + ";";
357             res += "}";
358         }
359         else if(obj instanceof ArrayList JavaDoc)
360         {
361             res = "{";
362             for(int i=0; i<((ArrayList JavaDoc)obj).size(); i++)
363                 res += paramToString(((ArrayList JavaDoc)obj).get(i)) + ";";
364             res += "}";
365         }
366         else if(obj instanceof Properties JavaDoc)
367         {
368             res = "{";
369             Enumeration JavaDoc keys = ((Properties JavaDoc)obj).keys();
370             while (keys.hasMoreElements())
371             {
372                 final String JavaDoc key = (String JavaDoc)keys.nextElement();
373                 res += key + "=" + ((Properties JavaDoc)obj).get(key) + ";";
374             }
375             res += "}";
376         }
377         else if(obj instanceof Attribute JavaDoc)
378         {
379             res = ""+((Attribute JavaDoc)obj).getName()+"="+((Attribute JavaDoc)obj).getValue();
380         }
381         else if(obj instanceof String JavaDoc ||
382                 obj instanceof Number JavaDoc ||
383                 obj instanceof ObjectName JavaDoc )
384         {
385             res = obj.toString();
386         }
387         else
388             res = "<?>";
389         return res;
390     }
391
392     /**
393      * returns ObjectName of invoking MBean
394      */

395     private String JavaDoc getObjectNameForCall(Call call) {
396         if(call==null)
397             return null;
398         Object JavaDoc[] params = call.getArguments();
399         if( params==null ||
400             params.length<1 ||
401             !(params[0] instanceof ObjectName JavaDoc))
402             return null;
403         return params[0].toString();
404     }
405
406 }
407
Popular Tags