KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > deployment > spi > JMXTarget


1 /*
2  * JBoss, Home of Professional Open Source
3  * Copyright 2005, JBoss Inc., and individual contributors as indicated
4  * by the @authors tag. See the copyright.txt in the distribution for a
5  * full listing of individual contributors.
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this software; if not, write to the Free
19  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21  */

22 package org.jboss.deployment.spi;
23
24 import java.net.InetAddress JavaDoc;
25 import java.net.URI JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.net.URLDecoder JavaDoc;
28 import java.net.UnknownHostException JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Properties JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34
35 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
36 import javax.enterprise.deploy.spi.TargetModuleID JavaDoc;
37 import javax.enterprise.deploy.spi.exceptions.TargetException JavaDoc;
38 import javax.management.MBeanServerConnection JavaDoc;
39 import javax.management.ObjectName JavaDoc;
40 import javax.naming.Context JavaDoc;
41 import javax.naming.InitialContext JavaDoc;
42 import javax.naming.NamingException JavaDoc;
43
44 import org.jboss.logging.Logger;
45
46 /**
47  * A Target that deploys using the JMX adaptor to communicate with the
48  * MainDeployer using file URLs to the deployments.
49  * @author Thomas.Diesler@jboss.org
50  * @author Scott.Stark@jboss.com
51  * @version $Revision: 38480 $
52  */

53 public class JMXTarget implements JBossTarget
54 {
55    private static final Logger log = Logger.getLogger(JMXTarget.class);
56    /**
57     * The default RMIAdaptor JNDI location
58     */

59    private static final String JavaDoc DEFAULT_ADAPTOR_PATH = "/jmx/invoker/RMIAdaptor";
60    /** The JSR88 deployment manager default and uri option name */
61    private static final String JavaDoc JSR88_MBEAN = "jboss.management.local:type=JSR88DeploymentManager,name=DefaultManager";
62    private static final String JavaDoc JSR88_MBEAN_OPT = "jsr88MBean";
63
64    /** The deployment target uri */
65    private URI JavaDoc deployURI;
66    /** The JNDI properties used to locate the MBeanServer */
67    private Properties JavaDoc jndiEnv;
68    private ObjectName JavaDoc jsr88MBean;
69
70    /**
71     * @todo merge the query parameter parsing for jndi and mbean names and
72     * test proper escaping of unsafe url chars.
73     *
74     * @param deployURI
75     */

76    public JMXTarget(URI JavaDoc deployURI)
77    {
78       log.debug("new JMXTarget: " + deployURI);
79       try
80       {
81          String JavaDoc localHostName = InetAddress.getLocalHost().getHostName();
82
83          String JavaDoc scheme = deployURI.getScheme();
84          String JavaDoc host = deployURI.getHost();
85          int port = deployURI.getPort();
86          String JavaDoc path = deployURI.getPath();
87          String JavaDoc query = deployURI.getRawQuery();
88
89          if (new URI JavaDoc(DeploymentManagerImpl.DEPLOYER_URI).equals(deployURI))
90          {
91             // Using JNDI defaults
92
scheme = "jnp";
93             host = localHostName;
94             port = 1099;
95             path = DEFAULT_ADAPTOR_PATH;
96
97             try
98             {
99                InitialContext JavaDoc iniCtx = new InitialContext JavaDoc();
100                Hashtable JavaDoc env = iniCtx.getEnvironment();
101                String JavaDoc providerURL = (String JavaDoc)env.get(InitialContext.PROVIDER_URL);
102                if (providerURL != null)
103                {
104                   // In case there is no schema returned
105
if (providerURL.indexOf("://") < 0)
106                      providerURL = "jnp://" + providerURL;
107
108                   URI JavaDoc providerURI = new URI JavaDoc(providerURL);
109                   scheme = providerURI.getScheme();
110                   host = providerURI.getHost();
111                   port = providerURI.getPort();
112                }
113             }
114             catch (NamingException JavaDoc e)
115             {
116                log.error(e);
117             }
118          }
119
120          StringBuffer JavaDoc uri = new StringBuffer JavaDoc(scheme + "://");
121          uri.append(host != null ? host : localHostName);
122          uri.append(port > 0 ? ":" + port : "");
123          uri.append(path != null && path.length() > 0 ? path : DEFAULT_ADAPTOR_PATH);
124          uri.append(query != null ? "?" + query : "");
125          deployURI = new URI JavaDoc(uri.toString());
126
127          log.debug("URI changed to: " + deployURI);
128          this.deployURI = deployURI;
129
130          // Parse the query for options
131
parseQuery();
132       }
133       catch (Exception JavaDoc e)
134       {
135          log.error(e);
136       }
137
138    }
139
140    /**
141     * Get the target's description
142     * @return the description
143     */

144    public String JavaDoc getDescription()
145    {
146       return "JBoss JMX deployment target";
147    }
148
149    /**
150     * Get the target's name
151     * @return the name
152     */

153    public String JavaDoc getName()
154    {
155       return deployURI.toString();
156    }
157
158    /**
159     * Get the target's host name
160     */

161    public String JavaDoc getHostName()
162    {
163       return deployURI.getHost();
164    }
165
166    /**
167     * Deploy a given module
168     */

169    public void deploy(TargetModuleID JavaDoc targetModuleID) throws Exception JavaDoc
170    {
171       TargetModuleIDImpl moduleID = (TargetModuleIDImpl)targetModuleID;
172       SerializableTargetModuleID smoduleID = new SerializableTargetModuleID(moduleID);
173       MBeanServerConnection JavaDoc server = getMBeanServerConnection();
174       String JavaDoc url = targetModuleID.getModuleID();
175       Object JavaDoc[] args = { smoduleID };
176       String JavaDoc[] sig = { smoduleID.getClass().getName() };
177       log.info("Begin deploy: " + url);
178       server.invoke(jsr88MBean, "deploy", args, sig);
179       log.info("End deploy");
180    }
181
182    /**
183     * Start a given module
184     */

185    public void start(TargetModuleID JavaDoc targetModuleID) throws Exception JavaDoc
186    {
187       MBeanServerConnection JavaDoc server = getMBeanServerConnection();
188       URL JavaDoc url = new URL JavaDoc(targetModuleID.getModuleID());
189       Object JavaDoc[] args = { url };
190       String JavaDoc[] sig = { URL JavaDoc.class.getName() };
191       log.debug("Start: " + url);
192       args = new Object JavaDoc[] { url.toExternalForm() };
193       sig = new String JavaDoc[] { String JavaDoc.class.getName() };
194       log.info("Begin start: " + url);
195       server.invoke(jsr88MBean, "start", args, sig);
196       log.info("End start");
197    }
198
199    /**
200     * Stop a given module
201     */

202    public void stop(TargetModuleID JavaDoc targetModuleID) throws Exception JavaDoc
203    {
204       MBeanServerConnection JavaDoc server = getMBeanServerConnection();
205       URL JavaDoc url = new URL JavaDoc(targetModuleID.getModuleID());
206       Object JavaDoc[] args = { url };
207       String JavaDoc[] sig = { URL JavaDoc.class.getName() };
208       log.debug("Stop: " + url);
209       args = new Object JavaDoc[] { url.toExternalForm() };
210       sig = new String JavaDoc[] { String JavaDoc.class.getName() };
211       log.info("Begin stop: " + url);
212       server.invoke(jsr88MBean, "stop", args, sig);
213       log.info("End stop");
214    }
215
216    /**
217     * Undeploy a given module
218     */

219    public void undeploy(TargetModuleID JavaDoc targetModuleID) throws Exception JavaDoc
220    {
221       MBeanServerConnection JavaDoc server = getMBeanServerConnection();
222       String JavaDoc url = targetModuleID.getModuleID();
223       Object JavaDoc[] args = { url };
224       String JavaDoc[] sig = { String JavaDoc.class.getName() };
225       log.info("Begin undeploy: " + url);
226       server.invoke(jsr88MBean, "undeploy", args, sig);
227       log.info("End undeploy");
228    }
229
230    /**
231     * Retrieve the list of all J2EE application modules running or not running
232     * on the identified targets.
233     */

234    public TargetModuleID JavaDoc[] getAvailableModules(ModuleType JavaDoc moduleType) throws TargetException JavaDoc
235    {
236       try
237       {
238          List JavaDoc list = new ArrayList JavaDoc();
239          MBeanServerConnection JavaDoc server = getMBeanServerConnection();
240          Object JavaDoc[] args = { new Integer JavaDoc(moduleType.getValue()) };
241          String JavaDoc[] sig = { int.class.getName() };
242          SerializableTargetModuleID[] modules = (SerializableTargetModuleID[])server.invoke(jsr88MBean, "getAvailableModules", args, sig);
243          for (int n = 0; n < modules.length; n++)
244          {
245             SerializableTargetModuleID id = modules[n];
246             String JavaDoc moduleID = id.getModuleID();
247             boolean isRunning = id.isRunning();
248             ModuleType JavaDoc type = ModuleType.getModuleType(id.getModuleType());
249             TargetModuleIDImpl tmid = new TargetModuleIDImpl(this, moduleID, null, isRunning, type);
250             convertChildren(tmid, id);
251             list.add(tmid);
252          }
253
254          TargetModuleID JavaDoc[] targetModuleIDs = new TargetModuleID JavaDoc[list.size()];
255          list.toArray(targetModuleIDs);
256          return targetModuleIDs;
257       }
258       catch (Exception JavaDoc e)
259       {
260          log.error("Cannot get available modules", e);
261          TargetException JavaDoc tex = new TargetException JavaDoc("");
262          tex.initCause(e);
263          throw tex;
264       }
265    }
266
267    private void convertChildren(TargetModuleIDImpl parent, SerializableTargetModuleID parentID)
268    {
269       SerializableTargetModuleID[] children = parentID.getChildModuleIDs();
270       int length = children != null ? children.length : 0;
271       for (int n = 0; n < length; n++)
272       {
273          SerializableTargetModuleID id = children[n];
274          String JavaDoc moduleID = id.getModuleID();
275          boolean isRunning = id.isRunning();
276          ModuleType JavaDoc type = ModuleType.getModuleType(id.getModuleType());
277          TargetModuleIDImpl child = new TargetModuleIDImpl(this, moduleID, parent, isRunning, type);
278          parent.addChildTargetModuleID(child);
279          convertChildren(child, id);
280       }
281    }
282
283    // Get MBeanServerConnection
284
private MBeanServerConnection JavaDoc getMBeanServerConnection() throws NamingException JavaDoc
285    {
286       Properties JavaDoc env = buildJNDIEnv();
287       String JavaDoc lookupPath = deployURI.getPath();
288       log.debug("JNDI lookup: " + lookupPath);
289       log.trace("Creating InitialContext with env: " + env);
290       InitialContext JavaDoc ctx = new InitialContext JavaDoc(env);
291       MBeanServerConnection JavaDoc server = (MBeanServerConnection JavaDoc)ctx.lookup(lookupPath);
292       return server;
293    }
294
295    /**
296     * Parse the query portion of the deployment URI to look for options:
297     * jsr88MBean : specifies the JSR88 mbean service that provides the
298     * deployment manager deploy/start/stop/undeploy operations.
299     */

300    private void parseQuery() throws Exception JavaDoc
301    {
302       String JavaDoc query = deployURI.getRawQuery();
303       log.debug("DeployURI.rawQuery: " + query);
304       Properties JavaDoc params = new Properties JavaDoc();
305       if (query != null)
306       {
307          /* Break the raw query into the name=value pairs. This processing is
308           too fragile to how the URI was built as it expects that only
309           the name/value portions of the query were encoded.
310           */

311          String JavaDoc[] options = query.split("[&=]");
312          for (int n = 0; n < options.length; n += 2)
313          {
314             String JavaDoc name = URLDecoder.decode(options[n], "UTF-8");
315             String JavaDoc value = URLDecoder.decode(options[n + 1], "UTF-8");
316             params.setProperty(name, value);
317          }
318       }
319
320       String JavaDoc name = params.getProperty(JSR88_MBEAN_OPT, JSR88_MBEAN);
321       jsr88MBean = new ObjectName JavaDoc(name);
322    }
323
324    private Properties JavaDoc buildJNDIEnv()
325    {
326       if (jndiEnv == null)
327       {
328          jndiEnv = new Properties JavaDoc();
329
330          // Parse the query string for name=value pairs to put into the env
331
String JavaDoc query = deployURI.getQuery();
332          if (query != null)
333          {
334             log.debug("Parsing query string: " + query);
335             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(query, "=&");
336             while (tokenizer.hasMoreTokens())
337             {
338                String JavaDoc name = tokenizer.nextToken();
339                String JavaDoc value = tokenizer.nextToken();
340                jndiEnv.setProperty(name, value);
341             }
342          }
343
344          // Set defaults for missing properties
345
if (jndiEnv.getProperty(Context.INITIAL_CONTEXT_FACTORY) == null)
346          {
347             jndiEnv.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
348          }
349          if (jndiEnv.getProperty(Context.PROVIDER_URL) == null)
350          {
351             String JavaDoc host = deployURI.getHost();
352             if (host == null)
353             {
354                try
355                {
356                   host = InetAddress.getLocalHost().getHostName();
357                }
358                catch (UnknownHostException JavaDoc e)
359                {
360                   host = "localhost";
361                }
362             }
363
364             int port = deployURI.getPort();
365             if (port <= 0)
366             {
367                port = 1099;
368             }
369
370             String JavaDoc jnpURL = "jnp://" + host + ':' + port;
371             jndiEnv.setProperty(Context.PROVIDER_URL, jnpURL);
372          }
373          if (jndiEnv.getProperty(Context.OBJECT_FACTORIES) == null)
374          {
375             jndiEnv.setProperty(Context.OBJECT_FACTORIES, "org.jboss.naming");
376          }
377       }
378
379       return jndiEnv;
380    }
381 }
382
Popular Tags