KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > mbeans > custom > BasicCustomMBeanOperations


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
25 package com.sun.enterprise.admin.mbeans.custom;
26 import com.sun.enterprise.admin.server.core.CustomMBeanRegistration;
27 import com.sun.enterprise.admin.common.MBeanServerFactory;
28 import com.sun.enterprise.admin.mbeans.custom.loading.CustomMBeanRegistrationImpl;
29 import com.sun.enterprise.admin.meta.MBeanRegistryFactory;
30 import com.sun.enterprise.config.ConfigContext;
31 import com.sun.enterprise.config.serverbeans.Mbean;
32 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
33 import com.sun.enterprise.admin.target.TargetBuilder;
34 import com.sun.enterprise.admin.target.Target;
35
36 import java.util.List JavaDoc;
37 import java.util.Map JavaDoc;
38 import java.util.Collections JavaDoc;
39 import java.util.HashMap JavaDoc;
40 import javax.management.MBeanInfo JavaDoc;
41 import javax.management.MalformedObjectNameException JavaDoc;
42 import javax.management.ObjectName JavaDoc;
43 import javax.management.MBeanInfo JavaDoc;
44 import javax.management.MBeanServerConnection JavaDoc;
45 import javax.management.MBeanServer JavaDoc;
46
47
48 public class BasicCustomMBeanOperations implements CustomMBeanOperationsMBean {
49
50     /** The instance of AdminContext that correpsponds to configuration on disk */
51     protected final ConfigContext acc;
52     
53     public BasicCustomMBeanOperations() {
54         this.acc = MBeanRegistryFactory.getAdminContext().getAdminConfigContext();
55     }
56
57     public String JavaDoc createMBean(final String JavaDoc target, final String JavaDoc className) throws CustomMBeanException {
58         final Map JavaDoc<String JavaDoc, String JavaDoc> params = CustomMBeanConstants.unmodifiableMap(CustomMBeanConstants.IMPL_CLASS_NAME_KEY, className);
59         final Map JavaDoc<String JavaDoc, String JavaDoc> attributes = Collections.emptyMap();
60         return ( this.createMBean(target, params, attributes) );
61     }
62
63     public String JavaDoc createMBean(String JavaDoc target, Map JavaDoc<String JavaDoc, String JavaDoc> params) throws CustomMBeanException {
64         final Map JavaDoc<String JavaDoc, String JavaDoc> attributes = Collections.emptyMap();
65         return ( this.createMBean(target, params, attributes) );
66     }
67
68     public String JavaDoc createMBean(final String JavaDoc target, final Map JavaDoc<String JavaDoc, String JavaDoc> params, final Map JavaDoc<String JavaDoc, String JavaDoc> attributes) throws CustomMBeanException {
69         if (params == null || attributes == null)
70             throw new IllegalArgumentException JavaDoc(CMBStrings.get("InternalError", "null argument"));
71         Target t = null;
72         try {
73             t = TargetBuilder.INSTANCE.createTarget(target, this.acc);
74         } catch (final Exception JavaDoc e) {
75             throw new RuntimeException JavaDoc(e);
76         }
77         return ( this.createMBeanDefinitionAddingReferenceToServer(t.getName(), params, attributes) );
78     }
79     
80     public void createMBeanRef(final String JavaDoc target, final String JavaDoc ref) throws CustomMBeanException {
81         throw new UnsupportedOperationException JavaDoc(CMBStrings.get("InternalError", "Not to be called on PE"));
82     }
83
84     public String JavaDoc deleteMBean(final String JavaDoc target, final String JavaDoc name) throws CustomMBeanException {
85         if (name == null)
86           throw new IllegalArgumentException JavaDoc(CMBStrings.get("InternalError", "null argument"));
87      
88         Target t = null;
89         try {
90             t = TargetBuilder.INSTANCE.createTarget(target, this.acc);
91         } catch (final Exception JavaDoc e) {
92             throw new RuntimeException JavaDoc(e);
93         }
94         
95         return ( this.deleteMBeanDefinitionRemovingReferenceFromDomain(t.getName(), name) );
96     }
97
98     public void deleteMBeanRef(final String JavaDoc target, final String JavaDoc ref) throws CustomMBeanException {
99         throw new UnsupportedOperationException JavaDoc(CMBStrings.get("InternalError", "Not to be called on PE"));
100     }
101     
102     /**
103      * Return the MBeanInfo of a given Custom MBean.
104      * The MBean must be loadable from the standard App Server location.
105      * The code does this:
106      * <ul>
107      * <li>Register the MBean in the MBeanServer
108      * <li>Fetch and save the MBeanInfo
109      * <li>Unregister the MBean
110      * </ul>
111      * Note that if the MBean can't be deployed successfully then this method won't work.
112      * @param classname
113      * @throws com.sun.enterprise.admin.mbeans.custom.CustomMBeanException
114      * @return The MBeanInfo object.
115      */

116     public MBeanInfo JavaDoc getMBeanInfo(String JavaDoc classname) throws CustomMBeanException
117     {
118         try
119         {
120             // create some unique names...
121
final String JavaDoc oname = "user:getMBeanInfo=" + System.nanoTime();
122             final String JavaDoc name = "getMBeanInfo" + System.nanoTime();
123
124             // create an MBean object because our helper code uses them...
125
Mbean mbean = new Mbean();
126             mbean.setImplClassName(classname);
127             mbean.setName(name);
128             mbean.setObjectName(oname);
129             mbean.setEnabled(true);
130
131             // fetch the MBeanServer
132
final MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
133
134             // Create a helper to do the reg/unreg...
135
CustomMBeanRegistrationImpl cmr = new CustomMBeanRegistrationImpl(mbs);
136
137             // register it
138
cmr.registerMBean(mbean);
139
140             // get the REAL ObjectName
141
ObjectName JavaDoc ron = cmr.getCascadingAwareObjectName(mbean);
142
143             // now fetch the MBeanInfo
144
MBeanInfo JavaDoc info = mbs.getMBeanInfo(ron);
145
146             // unregister it...
147
mbs.unregisterMBean(ron);
148
149             return info;
150         }
151         catch(Exception JavaDoc e)
152         {
153             throw new CustomMBeanException(e);
154         }
155     }
156     
157     /** Method that does bulk of the work to fulfill most of the functionality of this class. Other methods
158      * in this class and any subclasses should consider calling this method. It does the validation
159      * checks before creating the <i> mbean definition </i> in server's configuration. Most importantly, if
160      * all is well, a custom MBean definition will be created and an application-ref will be created for a
161      * server so that when the target server starts up, this mbean (which is referenced) is available for registration.
162      * @param s String representing the name of the server instance
163      * @param params a Map<String, String> specifying the other parameters optionally needed for mbean
164      * @param attributes a Map<String, String> specifying the custom MBean initialization attributes
165      */

166     protected String JavaDoc createMBeanDefinitionAddingReferenceToServer(final String JavaDoc s, final Map JavaDoc<String JavaDoc, String JavaDoc> params, final Map JavaDoc<String JavaDoc, String JavaDoc> attributes) throws CustomMBeanException {
167         try {
168             final Mbean mbean = this.createMBeanDefinitionInDomain(params, attributes);
169             final ObjectName JavaDoc onPostReg = new ObjectName JavaDoc(mbean.getObjectName());
170
171             // bug 6308668
172
// the mbean was created but never deleted IN THE CONTEXT
173
if (onExists(s, onPostReg)) //use references here, because object-name is NOT a primary key unlike name
174
{
175                 ServerBeansFactory.removeMbeanDefinition(acc, mbean.getName());
176     
177                 throw new CustomMBeanException(CMBStrings.get("AlreadyExists", onPostReg.toString()));
178             }
179             ServerBeansFactory.addMbeanReference(this.acc, mbean.getName(), s);
180             return ( mbean.getName() );
181         } catch (final Exception JavaDoc e) {
182             throw new CustomMBeanException(e);
183         }
184     }
185
186     protected Mbean createMBeanDefinitionInDomain(final Map JavaDoc<String JavaDoc, String JavaDoc> params, final Map JavaDoc<String JavaDoc, String JavaDoc> attributes) {
187         final Map JavaDoc<String JavaDoc, String JavaDoc> mm = checkAndModifyParamsForName(params);
188         final String JavaDoc name = mm.get(CustomMBeanConstants.NAME_KEY);
189         if (definitionExists(name))
190             throw new CustomMBeanException(CMBStrings.get("AlreadyExists", name));
191         final ObjectName JavaDoc onPostReg = selectObjectName(mm, attributes);
192         if (!CustomMBeanConstants.CUSTOM_MBEAN_DOMAIN.equals(onPostReg.getDomain())) {
193                 throw new IllegalArgumentException JavaDoc (CMBStrings.get("BadDomainName", onPostReg.getDomain(), CustomMBeanConstants.CUSTOM_MBEAN_DOMAIN));
194         }
195         // Now we mutate the params with "final" valid values
196
mm.put(CustomMBeanConstants.OBJECT_NAME_KEY, onPostReg.toString()); //put the correct object-name to map
197
final Mbean mbean = MBeanValidator.toMbean(mm, attributes, true);
198         try {
199             ServerBeansFactory.addMbeanDefinition(this.acc, mbean);
200         } catch (final Exception JavaDoc e) {
201             throw new CustomMBeanException(e);
202         }
203         return ( mbean );
204     }
205     protected Map JavaDoc<String JavaDoc, String JavaDoc> checkAndModifyParamsForName(final Map JavaDoc<String JavaDoc, String JavaDoc> params) throws CustomMBeanException {
206         checkParams(params);
207         final Map JavaDoc<String JavaDoc, String JavaDoc> paramsWithNameKey = putNameIfAbsent(params); // possibly changes the params
208
//at this point, it can be safely assumed that both name and class-name of the custom-mbean are available
209
final String JavaDoc name = paramsWithNameKey.get(CustomMBeanConstants.NAME_KEY);
210         return ( paramsWithNameKey );
211     }
212     
213     protected ObjectName JavaDoc selectObjectName(final Map JavaDoc<String JavaDoc, String JavaDoc> mm, final Map JavaDoc<String JavaDoc, String JavaDoc> attributes) throws CustomMBeanException {
214         final ObjectName JavaDoc onPreReg = ObjectNameSelectionAlgorithm.select(mm);
215         //by the time the algorithm is accessed, if the map contains object-name it is valid
216
final MBeanValidator mv = new MBeanValidator();
217         final ObjectName JavaDoc onPostReg = mv.registerTestMBean(createTestMap(Collections.unmodifiableMap(mm), onPreReg), attributes);
218         final String JavaDoc className = mm.get(CustomMBeanConstants.IMPL_CLASS_NAME_KEY);
219         final boolean selfReg = ObjectNameSelectionAlgorithm.implementsMBeanRegistrationInterface(className);
220         if (onPostReg != null) { // todo -- should throw an exception if it is null!!
221
// note that onPostReg is *always* going to contain the "server" property, so we must account for that
222
final ObjectName JavaDoc cascadedON = CustomMBeanRegistrationImpl.getCascadingAwareObjectName(onPreReg);
223
224             // It may be setting its own name if it implements MBeanRegistration...
225
if (!onPostReg.equals(cascadedON) && !selfReg) {
226                 throw new CustomMBeanException(CMBStrings.get("ObjectNameMismatch", onPreReg, CustomMBeanRegistrationImpl.getCascadingUnawareObjectName(onPostReg)));
227             }
228         }
229         try {
230             mv.unregisterTestMBean(onPostReg); //cleanup, if fails, could be ignored, as a new MBS is employed every time
231
} catch (final Exception JavaDoc e) {
232             e.printStackTrace();
233         }
234         //Note that we should always return the object-name without "server" property
235
final ObjectName JavaDoc onInConfig = CustomMBeanRegistrationImpl.getCascadingUnawareObjectName(onPostReg);
236         return ( onInConfig );
237     }
238     protected String JavaDoc deleteMBeanDefinitionRemovingReferenceFromDomain(final String JavaDoc s, final String JavaDoc name) throws RuntimeException JavaDoc {
239         boolean refd;
240         try {
241             refd = ServerBeansFactory.isReferencedMBean(acc, s, name);
242         } catch(final Exception JavaDoc e) {
243             throw new RuntimeException JavaDoc(e);
244         }
245         if (!refd) {
246             throw new RuntimeException JavaDoc(CMBStrings.get("RefsNotFound", s, name));
247         }
248         removeMBeanDefinitionAndReferenceFromConfigTree(s, name);
249         return ( name );
250     }
251
252     protected Map JavaDoc<String JavaDoc, String JavaDoc> putNameIfAbsent(final Map JavaDoc<String JavaDoc, String JavaDoc> m) {
253         final Map JavaDoc<String JavaDoc, String JavaDoc> nm = new HashMap JavaDoc<String JavaDoc, String JavaDoc>(m);
254         final String JavaDoc c = nm.get(CustomMBeanConstants.IMPL_CLASS_NAME_KEY); // must not be null
255
assert (c != null);
256         if (!nm.containsKey(CustomMBeanConstants.NAME_KEY))
257             nm.put(CustomMBeanConstants.NAME_KEY, c);
258         return ( nm );
259     }
260
261     protected void checkParams(final Map JavaDoc<String JavaDoc, String JavaDoc> params) throws IllegalArgumentException JavaDoc {
262         if (!params.containsKey(CustomMBeanConstants.IMPL_CLASS_NAME_KEY))
263             throw new IllegalArgumentException JavaDoc(CMBStrings.get("NoImplClass"));
264         checkValidIfPresent(params);
265         checkValidObjectNameIfPresent(params);
266     }
267
268     protected boolean definitionExists(final String JavaDoc name) throws CustomMBeanException {
269         boolean exists = false;
270         try {
271             final List JavaDoc<Mbean> mbeans = ServerBeansFactory.getAllMBeanDefinitions(acc);
272             for (Mbean m : mbeans) {
273                 if (m.getName().equals(name)) {
274                     exists = true;
275                     break;
276                 }
277                     
278             }
279             return (exists);
280         } catch (final Exception JavaDoc e) {
281             throw new CustomMBeanException(e);
282         }
283     }
284     
285     protected boolean onExists(final String JavaDoc server, final ObjectName JavaDoc on) throws RuntimeException JavaDoc {
286         try {
287             boolean exists = false;
288             final List JavaDoc<Mbean> mbeans = ServerBeansFactory.getReferencedMBeans(acc, server);
289             for (Mbean m : mbeans) {
290                 final String JavaDoc onsFromConfig = m.getObjectName();
291                 final ObjectName JavaDoc onFromConfig = new ObjectName JavaDoc(onsFromConfig);
292                 if (onFromConfig.equals(on)) {
293                     exists = true;
294                     break;
295                 }
296             }
297             return ( exists ) ;
298         } catch (final Exception JavaDoc e) {
299             throw new RuntimeException JavaDoc(e);
300         }
301     }
302     ///// Private Methods /////
303

304     private void checkValidIfPresent(final Map JavaDoc<String JavaDoc, String JavaDoc> params) throws IllegalArgumentException JavaDoc {
305         final String JavaDoc nameKey = CustomMBeanConstants.NAME_KEY;
306         final String JavaDoc name = params.get(nameKey);
307         final String JavaDoc cKey = CustomMBeanConstants.IMPL_CLASS_NAME_KEY;
308         final String JavaDoc cVal = params.get(cKey);
309         final String JavaDoc onKey = CustomMBeanConstants.OBJECT_NAME_KEY;
310         final String JavaDoc onVal = params.get(onKey);
311         if (params.containsKey(nameKey) && name == null)
312
313             throw new IllegalArgumentException JavaDoc(CMBStrings.get("MapHasNullParam", "Name"));
314         if (params.containsKey(cKey) && cVal == null)
315             throw new IllegalArgumentException JavaDoc(CMBStrings.get("MapHasNullParam", "ClassName"));
316         if (params.containsKey(onKey) && onVal == null)
317             throw new IllegalArgumentException JavaDoc(CMBStrings.get("MapHasNullParam", "ObjectName"));
318     }
319         
320     private void checkValidObjectNameIfPresent(final Map JavaDoc<String JavaDoc, String JavaDoc> params) throws IllegalArgumentException JavaDoc {
321         final String JavaDoc onKey = CustomMBeanConstants.OBJECT_NAME_KEY;
322         final String JavaDoc onVal = params.get(onKey);
323         boolean onSpecified = params.containsKey(onKey) && onVal != null;
324         ObjectName JavaDoc on = null;
325         if (onSpecified) {
326             try {
327                 on = new ObjectName JavaDoc(onVal); //see if JMX likes it
328
} catch(final MalformedObjectNameException JavaDoc me) {
329                 throw new IllegalArgumentException JavaDoc(me);
330             }
331             if (on.isPattern())
332                 throw new IllegalArgumentException JavaDoc(CMBStrings.get("ObjectNamePattern"));
333             final String JavaDoc d = on.getDomain();
334             if (!CustomMBeanConstants.CUSTOM_MBEAN_DOMAIN.equals(d)) {
335                 throw new IllegalArgumentException JavaDoc (CMBStrings.get("BadDomainName", d, CustomMBeanConstants.CUSTOM_MBEAN_DOMAIN));
336             }
337             if (on.getKeyProperty(CustomMBeanConstants.SERVER_KEY) != null) {
338                 throw new IllegalArgumentException JavaDoc(CMBStrings.get("ObjectNameReserved", on.toString(), CustomMBeanConstants.SERVER_KEY));
339             }
340         }
341     }
342         
343     private void removeMBeanDefinitionAndReferenceFromConfigTree(final String JavaDoc server, final String JavaDoc ref) throws RuntimeException JavaDoc {
344         try {
345             ServerBeansFactory.removeMbeanReference(acc, ref, server);
346             ServerBeansFactory.removeMbeanDefinition(acc, ref);
347         } catch (final Exception JavaDoc e) {
348             throw new RuntimeException JavaDoc(e);
349         }
350     }
351     private Map JavaDoc<String JavaDoc, String JavaDoc> createTestMap(final Map JavaDoc<String JavaDoc, String JavaDoc> params, final ObjectName JavaDoc on) {
352         final Map JavaDoc<String JavaDoc, String JavaDoc> nm = new HashMap JavaDoc<String JavaDoc, String JavaDoc> (params);
353         nm.put(CustomMBeanConstants.OBJECT_NAME_KEY, on.toString());
354         return ( nm );
355     }
356     ///// Private Methods /////
357
}
358
Popular Tags