KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > management > j2eemanagement > J2EEDomain


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2004 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: J2EEDomain.java,v 1.18 2005/07/25 21:03:55 pasmith Exp $
23  * --------------------------------------------------------------------------
24  */

25 package org.objectweb.jonas.management.j2eemanagement;
26
27 import java.io.ByteArrayOutputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Map JavaDoc;
36
37 import javax.management.InstanceNotFoundException JavaDoc;
38 import javax.management.JMException JavaDoc;
39 import javax.management.ListenerNotFoundException JavaDoc;
40 import javax.management.MBeanRegistration JavaDoc;
41 import javax.management.MBeanServer JavaDoc;
42 import javax.management.MBeanServerConnection JavaDoc;
43 import javax.management.MBeanServerNotification JavaDoc;
44 import javax.management.MalformedObjectNameException JavaDoc;
45 import javax.management.Notification JavaDoc;
46 import javax.management.NotificationListener JavaDoc;
47 import javax.management.ObjectName JavaDoc;
48 import javax.management.remote.JMXConnector JavaDoc;
49
50 import org.objectweb.jonas.common.JProp;
51 import org.objectweb.jonas.common.Log;
52 import org.objectweb.jonas.discovery.DiscEvent;
53 import org.objectweb.jonas.discovery.DiscoveryListener;
54 import org.objectweb.jonas.jmx.J2eeObjectName;
55 import org.objectweb.jonas.jmx.JmxService;
56 import org.objectweb.util.monolog.api.BasicLevel;
57 import org.objectweb.util.monolog.api.Logger;
58
59 import java.io.FileInputStream JavaDoc;
60
61 /**
62  * Implements a managed object which represents a management domain.
63  * Domain management information is present in two data structures:
64  * <code>myServers</code> and <code>managedServersToUrls</code>.
65  * The first one containes the OBJECT_NAMEs of the J2EEServers the domain is
66  * supposed to contain, and the second containes the JMX Connector URLs
67  * each server provides for management.
68  * Both are updated by addServer() and removeServer() methods.
69  * @author Adriana Danes
70  * @author Vivek Lakshmanan
71  */

72 public class J2EEDomain extends J2EEManagedObject implements MBeanRegistration JavaDoc, NotificationListener JavaDoc {
73
74     private static final int BUFFER_SIZE = 1024;
75     
76     /**
77      * Management domain name
78      */

79     private String JavaDoc name = null;
80
81     /**
82      * List of OBJECT_NAMEs corresponding to the servers associated with this domain
83      */

84     private List JavaDoc myServers = null;
85
86     /**
87      * J2EE Management logger
88      */

89     private static Logger logger = null;
90
91     /**
92      * Current MBeanServer (in which this J2EEDomain MBean is registered)
93      */

94     private MBeanServer JavaDoc mbeanServer = null;
95
96     /**
97      * JmxService reference allows for getting a connection for a server in the domain
98      */

99     private JmxService jmxService = null;
100
101     /**
102      * Mapping serverName -> JMX Service URLs published by the server named serverName
103      */

104     private Map JavaDoc managedServersToUrls = null;
105
106     /**
107      * MBean constructor
108      * @param objectName object name of the managed object
109      * @param stateManageable if true, this managed object implements J2EE State Management Model
110      * @param statisticsProvider if true, this managed object implements the J2EE StatisticProvide Model
111      * @param eventProvider if true, this managed object implements the J2EE EventProvider Model
112      * @throws JMException ..
113      */

114     public J2EEDomain(String JavaDoc objectName, boolean stateManageable, boolean statisticsProvider, boolean eventProvider) throws JMException JavaDoc {
115         super(objectName, stateManageable, statisticsProvider, eventProvider);
116         ObjectName JavaDoc myObjectName = ObjectName.getInstance(objectName);
117         name = myObjectName.getKeyProperty("name");
118         myServers = Collections.synchronizedList(new ArrayList JavaDoc());
119         managedServersToUrls = new HashMap JavaDoc();
120         logger = Log.getLogger("org.objectweb.jonas.management.j2eemanagement");
121         if (logger.isLoggable(BasicLevel.DEBUG)) {
122             logger.log(BasicLevel.DEBUG, "J2EEDomain managed object created. OBJECT_NAME = " + objectName);
123         }
124     }
125
126     /**
127      * Return the MBeans OBJECT_NAMEs of the servers running in this domain.
128      * Convert myServers ArrayList of OBJECT_NAMEs to an array of Strings of OBJECT_NAMEs
129      * @return The list of object names corresponding to the servers associated with this domain
130      */

131     public String JavaDoc[] getServers() {
132         //return (String[]) myServers.toArray();
133
String JavaDoc[] sb = new String JavaDoc[myServers.size()];
134         int i = 0;
135         for (Iterator JavaDoc it = myServers.iterator(); it.hasNext();) {
136             sb[i++] = (String JavaDoc) it.next();
137         }
138         return sb;
139     }
140
141     /**
142      * Returns the names of the servers currently managed.
143      *
144      * @return Names of servers currently managed.
145      */

146     public String JavaDoc[] getServerNames() {
147         return (String JavaDoc[]) managedServersToUrls.keySet().toArray(new String JavaDoc[managedServersToUrls.keySet().size()]);
148     }
149
150     /**
151      * Return the connector server urls for a given server.
152      * @param serverName the server we are inquiring for
153      * @return The list of connector server urls corresponding to the given server
154      */

155     public String JavaDoc[] getConnectorServerURLs(String JavaDoc serverName) {
156         return (String JavaDoc[]) managedServersToUrls.get(serverName);
157     }
158
159     /**
160      * Add an OBJECT_NAME to the <code>servers</code> list.
161      * @param serverOn ObjectName (String form) of a J2EEServer to be add in this domain
162      * @param connectorServerURLs connector server urls for this server
163      */

164     public void addServer(String JavaDoc serverOn, String JavaDoc[] connectorServerURLs) {
165         if (myServers.contains(serverOn)) {
166             if (logger.isLoggable(BasicLevel.DEBUG)) {
167                 logger.log(BasicLevel.DEBUG, "The object name: " + serverOn + " is already in the servers list");
168             }
169         } else {
170             myServers.add(serverOn);
171
172             try {
173                 ObjectName JavaDoc on = ObjectName.getInstance(serverOn);
174                 String JavaDoc name = on.getKeyProperty("name");
175                 managedServersToUrls.put(name, connectorServerURLs);
176             } catch (MalformedObjectNameException JavaDoc me) {
177                 // No mapping for this server name, the getConnectorServerURLs()
178
// will return null
179
managedServersToUrls.put(name, null);
180             }
181         }
182     }
183
184     /**
185      * Remove an object name from the <code>servers</code> list.
186      *
187      * @param serverOn
188      * ObjectName (String form) of a J2EEServer to be removed from
189      * this domain
190      * @return Object name of the removed J2EEServer
191      */

192     public String JavaDoc removeServer(String JavaDoc serverOn) {
193         int index = myServers.indexOf(serverOn);
194         if (index == -1) {
195             // name not found
196
return null;
197         } else {
198             try {
199                 ObjectName JavaDoc on = ObjectName.getInstance(serverOn);
200                 String JavaDoc name = on.getKeyProperty("name");
201                 managedServersToUrls.remove(name);
202             } catch (MalformedObjectNameException JavaDoc me) {
203                 // No mapping for this server name, this shouldnt happen but if
204
//it does, return null and dont remove anything.
205
return null;
206
207             }
208             return (String JavaDoc) myServers.remove(index);
209         }
210     }
211
212     /**
213      * @param server The MBean server in which the MBean will be registered.
214      * @param name The object name of the MBean
215      * @return The object name of the MBean
216      */

217     public ObjectName JavaDoc preRegister(MBeanServer JavaDoc server, ObjectName JavaDoc name) throws Exception JavaDoc {
218         if (name == null) {
219             return J2eeObjectName.J2EEDomain(this.name);
220         }
221         String JavaDoc myName = getObjectName().toString();
222         String JavaDoc argName = name.toString();
223         if (myName.equals(argName)) {
224             // OK
225
mbeanServer = server;
226             return name;
227         } else {
228             if (logger.isLoggable(BasicLevel.WARN)) {
229                 logger.log(BasicLevel.WARN, "Trying to register J2EEDomain MBean with the following name: "
230                         + argName + " when the expected name is: " + myName);
231             }
232             return ObjectName.getInstance(this.name);
233         }
234     }
235
236     /**
237      * Add J2EEDomain MBean (myself) as listener to registration/unregistration notifications of
238      * JOnAS management MBeans.
239      * @param registrationDone Indicates whether or not the MBean has been successfully registered
240      */

241     public void postRegister(Boolean JavaDoc registrationDone) {
242         if (registrationDone.booleanValue()) {
243             try {
244                 // MBeanServerDelegate is the MBean which sends registration/unregistration notifications
245
ObjectName JavaDoc delegate = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
246                 mbeanServer.addNotificationListener(delegate, this, null, null);
247             } catch (JMException JavaDoc me) {
248                 if (logger.isLoggable(BasicLevel.DEBUG)) {
249                     logger.log(BasicLevel.DEBUG, "J2EEDomain MBean could not be added as notification listener for MBeanServerNotifications "
250                             + "related to the REGISTRATION or UNREGISTRETION of JOnAS management MBeans");
251                 }
252             }
253         }
254     }
255
256     /**
257      * @see javax.management.MBeanRegistration#preDeregister()
258      */

259     public void preDeregister() throws Exception JavaDoc {
260         // TODO Auto-generated method stub
261

262     }
263
264     /**
265      * @see javax.management.MBeanRegistration#postDeregister()
266      */

267     public void postDeregister() {
268         // TODO Auto-generated method stub
269

270     }
271
272     /**
273      * @param notification received notification
274      * @param handback received handback
275      */

276     public void handleNotification(Notification JavaDoc notification, Object JavaDoc handback) {
277         if (notification instanceof MBeanServerNotification JavaDoc) {
278             handleMBeanServerNotification((MBeanServerNotification JavaDoc) notification);
279         } else {
280             // Handle notification emmited by the Enroller or the DiscoveryClient MBean
281
handleDiscoveryNotification(notification);
282         }
283     }
284
285     /**
286      * Treat REGISTRATION/UNREGISTRATION MBeanServerNotification generated for "management" MBeans
287      * @param notification MBeanServerNotification to treat
288      */

289     private void handleMBeanServerNotification(MBeanServerNotification JavaDoc notification) {
290         String JavaDoc type = notification.getType();
291         // ObjectName of the MBean that caused the notification
292
ObjectName JavaDoc registeredOn = ((MBeanServerNotification JavaDoc) notification).getMBeanName();
293         String JavaDoc name = registeredOn.getKeyProperty("name");
294         // The names below are defined in JonasObjectName class
295
if ((name != null) && (name.equals("discoveryEnroller") || name.equals("discoveryClient"))) {
296             if (type.equals(MBeanServerNotification.REGISTRATION_NOTIFICATION)) {
297                 try {
298                     // register myself as listener of notifications emitted by the Enroller or DiscoveryClient MBean
299
mbeanServer.addNotificationListener(registeredOn, this, null, null);
300                     if (logger.isLoggable(BasicLevel.DEBUG)) {
301                         logger.log(BasicLevel.DEBUG, "J2EEDomain (this) registered as listener to notifs emitted by " + registeredOn);
302                     }
303                 } catch (InstanceNotFoundException JavaDoc e) {
304                     // TODO Auto-generated catch block
305
e.printStackTrace();
306                 }
307             }
308             if (type.equals(MBeanServerNotification.UNREGISTRATION_NOTIFICATION)) {
309                 try {
310                     // unregister myself as listener of notifications emitted by the Enroller or DiscoveryClient MBean
311
mbeanServer.removeNotificationListener(registeredOn, this);
312                     if (logger.isLoggable(BasicLevel.DEBUG)) {
313                         logger.log(BasicLevel.DEBUG, "J2EEDomain (this) removed listener for notifs emitted by " + registeredOn);
314                     }
315                 } catch (InstanceNotFoundException JavaDoc e) {
316                     // TODO Auto-generated catch block
317
e.printStackTrace();
318                 } catch (ListenerNotFoundException JavaDoc e) {
319                     // TODO Auto-generated catch block
320
e.printStackTrace();
321                 }
322             }
323         }
324     }
325
326     /**
327      * Treat notification if it is a discovery notification
328      * @param notification received notification to treat
329      */

330     private void handleDiscoveryNotification(Notification JavaDoc notification) {
331         // Treat discovery notification
332
String JavaDoc type = notification.getType();
333         if (type.equals(DiscoveryListener.DISCOVERY_TYPE)) {
334             DiscEvent userData = (DiscEvent) notification.getUserData();
335             String JavaDoc domainName = userData.getDomainName();
336             if (domainName.equals(name)) {
337                 String JavaDoc serverName = userData.getServerName();
338                 ObjectName JavaDoc on = J2eeObjectName.J2EEServer(domainName, serverName);
339                 String JavaDoc state = userData.getState();
340                 if (state.equals(DiscEvent.RUNNING)) {
341                     addServer(on.toString(), userData.getConnectorURL());
342                 } else if (state.equals(DiscEvent.STOPPING)) {
343                     removeServer(on.toString());
344                 }
345             }
346         }
347     }
348
349     // -------------------------------------
350
/**
351      * Support of management operations at domain level.
352      * --> J2EE Application and modules deployment
353      * -------------------------------------------------
354      * In this implementation only one deployment operation can be launched
355      * at a time. During the duration of this operation, the value of the
356      * <code>progress</code> object is not null. A new operation request
357      * will be rejected if the the value of the <code>progress</code> object is
358      * RUNNING.
359      */

360     static final private String JavaDoc RUNNING = "running";
361     static final private String JavaDoc COMPLETED = "completed";
362     static final private String JavaDoc FAILED = "failed";
363     static final private String JavaDoc DEPLOYED = "deployed";
364     static final private String JavaDoc UNDEPLOYED = "undeployed";
365     
366     static final private String JavaDoc DEPLOY = "deploy";
367     static final private String JavaDoc UNDEPLOY = "undeploy";
368     static final private String JavaDoc UPLOAD_DEPLOY = "uploadDeploy";
369     static final private String JavaDoc UPLOAD = "upload";
370     
371     static final private boolean SUCCESS = true;
372     static final private boolean FAILURE = false;
373
374     private String JavaDoc progress = null;
375     private HashMap JavaDoc progressReport = null;
376     private String JavaDoc globalErrorReport = null;
377
378     /**
379      * @return Returns the progress value.
380      */

381     public String JavaDoc getProgress() {
382         return progress;
383     }
384
385     /**
386      * @param progress The progress to set.
387      */

388     private void setProgress(String JavaDoc progress) {
389         this.progress = progress;
390     }
391
392     /**
393      * Set progress to null
394      */

395     public void resetProgress() {
396         progress = null;
397     }
398
399     /**
400      * Deploy a JAR module on a target if no other deployment operation is executing.
401      *
402      * @param target The OBJECT_NAMES of the J2EEServers composing the target
403      * @param fileName file containing the module (installed on each target)
404      * @return true if the operation was executed, false if the operation was rejected
405      */

406     public boolean deployJar(String JavaDoc[] target, String JavaDoc fileName) {
407         if (isAnotherOperationRunning()) {
408             return false;
409         }
410         
411         String JavaDoc opName = "deployJar";
412         String JavaDoc[] params = {fileName };
413         String JavaDoc[] signature = {"java.lang.String" };
414         return doDeploymentOperation(opName, params, signature, target, fileName, DEPLOY, false);
415     }
416
417     /**
418      * Un-deploy a JAR module on a target if no other deployment operation is executing.
419      *
420      * @param target The OBJECT_NAMES of the J2EEServers composing the target
421      * @param fileName file containing the module
422      * @return true if the operation was executed, false if the operation was rejected
423      */

424     public boolean unDeployJar(String JavaDoc[] target, String JavaDoc fileName) {
425         if (isAnotherOperationRunning()) {
426             return false;
427         }
428         
429         String JavaDoc opName = "unDeployJar";
430         String JavaDoc[] params = {fileName };
431         String JavaDoc[] signature = {"java.lang.String" };
432         return doDeploymentOperation(opName, params, signature, target, fileName, UNDEPLOY, false);
433     }
434
435     /**
436      * Deploy a WAR module on a target if no other deployment operation is executing.
437      *
438      * @param target The OBJECT_NAMES of the J2EEServers composing the target
439      * @param fileName file containing the module (installed on each target)
440      * @return true if the operation was executed, false if the operation was rejected
441      */

442     public boolean deployWar(String JavaDoc[] target, String JavaDoc fileName) {
443         if (isAnotherOperationRunning()) {
444             return false;
445         }
446         
447         String JavaDoc opName = "deployWar";
448         String JavaDoc[] params = {fileName };
449         String JavaDoc[] signature = {"java.lang.String" };
450         return doDeploymentOperation(opName, params, signature, target, fileName, DEPLOY, false);
451     }
452
453     /**
454      * Un-deploy a WAR module on a target if no other deployment operation is executing.
455      *
456      * @param target The OBJECT_NAMES of the J2EEServers composing the target
457      * @param fileName file containing the module
458      * @return true if the operation was executed, false if the operation was rejected
459      */

460     public boolean unDeployWar(String JavaDoc[] target, String JavaDoc fileName) {
461         if (isAnotherOperationRunning()) {
462             return false;
463         }
464         
465         String JavaDoc opName = "unDeployWar";
466         String JavaDoc[] params = {fileName };
467         String JavaDoc[] signature = {"java.lang.String" };
468         return doDeploymentOperation(opName, params, signature, target, fileName, UNDEPLOY, false);
469     }
470
471     /**
472      * Deploy a RAR module on a target if no other deployment operation is executing.
473      *
474      * @param target The OBJECT_NAMES of the J2EEServers composing the target
475      * @param fileName file containing the module (installed on each target)
476      * @return true if the operation was executed, false if the operation was rejected
477      */

478     public boolean deployRar(String JavaDoc[] target, String JavaDoc fileName) {
479         if (isAnotherOperationRunning()) {
480             return false;
481         }
482         
483         String JavaDoc opName = "deployRar";
484         String JavaDoc[] params = {fileName };
485         String JavaDoc[] signature = {"java.lang.String" };
486         return doDeploymentOperation(opName, params, signature, target, fileName, DEPLOY, false);
487     }
488
489     /**
490      * Un-deploy a RAR module on a target if no other deployment operation is executing.
491      *
492      * @param target The OBJECT_NAMES of the J2EEServers composing the target
493      * @param fileName file containing the module
494      * @return true if the operation was executed, false if the operation was rejected
495      */

496     public boolean unDeployRar(String JavaDoc[] target, String JavaDoc fileName) {
497         if (isAnotherOperationRunning()) {
498             return false;
499         }
500         
501         String JavaDoc opName = "unDeployRar";
502         String JavaDoc[] params = {fileName };
503         String JavaDoc[] signature = {"java.lang.String" };
504         return doDeploymentOperation(opName, params, signature, target, fileName, UNDEPLOY, false);
505     }
506
507     /**
508      * Deploy a EAR module on a target if no other deployment operation is executing.
509      *
510      * @param target The OBJECT_NAMES of the J2EEServers composing the target
511      * @param fileName file containing the module (installed on each target)
512      * @return true if the operation was executed, false if the operation was rejected
513      */

514     public boolean deployEar(String JavaDoc[] target, String JavaDoc fileName) {
515         if (isAnotherOperationRunning()) {
516             return false;
517         }
518         
519         String JavaDoc opName = "deployEar";
520         String JavaDoc[] params = {fileName };
521         String JavaDoc[] signature = {"java.lang.String" };
522         return doDeploymentOperation(opName, params, signature, target, fileName, DEPLOY, false);
523     }
524
525     /**
526      * Un-deploy a EAR module on a target if no other deployment operation is executing.
527      *
528      * @param target The OBJECT_NAMES of the J2EEServers composing the target
529      * @param fileName file containing the module
530      * @return true if the operation was executed, false if the operation was rejected
531      */

532     public boolean unDeployEar(String JavaDoc[] target, String JavaDoc fileName) {
533         if (isAnotherOperationRunning()) {
534             return false;
535         }
536         
537         String JavaDoc opName = "unDeployEar";
538         String JavaDoc[] params = {fileName };
539         String JavaDoc[] signature = {"java.lang.String" };
540         return doDeploymentOperation(opName, params, signature, target, fileName, UNDEPLOY, false);
541     }
542     
543     /**
544      * Upload an EAR modlue to all targets and deploy the new module.
545      *
546      * @param target a list target servers
547      * @param fileName file containing the module
548      * @param replaceExisting should a file with the same name on the target server be overwritten
549      * @return true if the operation was executed, false if the operation was rejected
550      */

551     public boolean uploadDeployEar(String JavaDoc[] target, String JavaDoc fileName, boolean replaceExisting) {
552         if (isAnotherOperationRunning()) {
553             return false;
554         }
555         
556         String JavaDoc opName = "reDeployEar";
557         String JavaDoc[] params = {fileName };
558         String JavaDoc[] signature = {"java.lang.String" };
559         return doDeploymentOperation(opName, params, signature, target, fileName, UPLOAD_DEPLOY, replaceExisting);
560     }
561     
562     /**
563      * Upload an WAR modlue to all targets and deploy the new module.
564      *
565      * @param target a list target servers
566      * @param fileName file containing the module
567      * @param replaceExisting should a file with the same name on the target server be overwritten
568      * @return true if the operation was executed, false if the operation was rejected
569      */

570     public boolean uploadDeployWar(String JavaDoc[] target, String JavaDoc fileName, boolean replaceExisting) {
571         if (isAnotherOperationRunning()) {
572             return false;
573         }
574         
575         String JavaDoc opName = "reDeployWar";
576         String JavaDoc[] params = {fileName };
577         String JavaDoc[] signature = {"java.lang.String" };
578         return doDeploymentOperation(opName, params, signature, target, fileName, UPLOAD_DEPLOY, replaceExisting);
579     }
580     
581     /**
582      * Upload an JAR modlue to all targets and deploy the new module.
583      *
584      * @param target a list target servers
585      * @param fileName file containing the module
586      * @param replaceExisting should a file with the same name on the target server be overwritten
587      * @return true if the operation was executed, false if the operation was rejected
588      */

589     public boolean uploadDeployJar(String JavaDoc[] target, String JavaDoc fileName, boolean replaceExisting) {
590         if (isAnotherOperationRunning()) {
591             return false;
592         }
593         
594         String JavaDoc opName = "reDeployJar";
595         String JavaDoc[] params = {fileName };
596         String JavaDoc[] signature = {"java.lang.String" };
597         return doDeploymentOperation(opName, params, signature, target, fileName, UPLOAD_DEPLOY, replaceExisting);
598     }
599     
600     /**
601      * Upload an RAR modlue to all targets and deploy the new module.
602      *
603      * @param target a list target servers
604      * @param fileName file containing the module
605      * @param replaceExisting should a file with the same name on the target server be overwritten
606      * @return true if the operation was executed, false if the operation was rejected
607      */

608     public boolean uploadDeployRar(String JavaDoc[] target, String JavaDoc fileName, boolean replaceExisting) {
609         if (isAnotherOperationRunning()) {
610             return false;
611         }
612         
613         String JavaDoc opName = "reDeployRar";
614         String JavaDoc[] params = {fileName };
615         String JavaDoc[] signature = {"java.lang.String" };
616         return doDeploymentOperation(opName, params, signature, target, fileName, UPLOAD_DEPLOY, replaceExisting);
617     }
618     
619     /**
620      * Upload a module to each of the target servers.
621      *
622      * @param target a list of the target servers
623      * @param fileName file containing the module
624      * @param replaceExisting should a file with the same name on the target server be overwritten
625      * @return true if the operation was executed, false if the operation was rejected
626      */

627     public boolean uploadFile(String JavaDoc[] target, String JavaDoc fileName, boolean replaceExisting) {
628         if (isAnotherOperationRunning()) {
629             return false;
630         };
631         
632         String JavaDoc opName = "uploadFile";
633         String JavaDoc[] params = {fileName};
634         String JavaDoc[] signature = {"java.lang.String" };
635         return doDeploymentOperation(opName, params, signature, target, fileName, UPLOAD, replaceExisting);
636     }
637
638     /**
639      * A deployment operation can be: deploy/unDeploy/upload/uploadDeploy for
640      * jar, war, rar or ear.
641      *
642      * The progress object reflects the operation evolution.
643      *
644      * If the operation succeded on every server in the target, the progress passes
645      * to COMPLETED. If the op. failed on some servers in the target, the error
646      * is reported in the corresponding entry of progressReport HashMap.
647      *
648      * If the target is not correct (does not correspond to the domain management
649      * information), the globalErrorReport contains corresponding error description.
650      *
651      * @param opName the name of the operation to be invoked
652      * @param opParams the parameters to be given to the invoke() method
653      * @param opSignature the signature of the method being invoked
654      * @param target The OBJECT_NAMES of the J2EEServers composing the target
655      * @param fileName file containing the module
656      * @param opType one of DEPLOY, UNDEPLOY, UPLOAD, UPLOAD_DEPLOY
657      * @param replaceExisting whether an existing module should be overwritten on upload
658      *
659      * @return true if the operation was executed, false if the operation was
660      * rejected
661      */

662     private boolean doDeploymentOperation(String JavaDoc opName, Object JavaDoc[] opParams, String JavaDoc[] opSignature, String JavaDoc[] target, String JavaDoc fileName, String JavaDoc opType, boolean replaceExisting) {
663         progressReport = new HashMap JavaDoc();
664         // test target coherence
665
if (isTargetCorrect(target)) {
666             MBeanServerConnection JavaDoc connection = null;
667             JMXConnector JavaDoc connector = null;
668             for (int i = 0; i < target.length; i++) {
669                 ObjectName JavaDoc targetOn = null;
670                 try {
671                     targetOn = ObjectName.getInstance(target[i]);
672                 } catch (MalformedObjectNameException JavaDoc me) {
673                     // Should not occur here
674
setProgress(FAILED);
675                     continue;
676                 }
677                 String JavaDoc serverName = targetOn.getKeyProperty("name");
678                 connection = jmxService.getServerConnection(serverName);
679                 try {
680                     testConnection(connection, serverName);
681                     try {
682                         if (opType.equals(DEPLOY)) {
683                             doDeploy(connection,
684                                      targetOn,
685                                      opName,
686                                      opParams,
687                                      opSignature,
688                                      fileName);
689                         } else if (opType.equals(UNDEPLOY)) {
690                             doUnDeploy(connection,
691                                        targetOn,
692                                        opName,
693                                        opParams,
694                                        opSignature,
695                                        fileName);
696                         } else if (opType.equals(UPLOAD_DEPLOY)) {
697                             doUploadReDeploy(connection,
698                                              targetOn,
699                                              opName,
700                                              opParams,
701                                              opSignature,
702                                              fileName,
703                                              replaceExisting);
704                         } else if (opType.equals(UPLOAD)) {
705                             doUpload(connection,
706                                      targetOn,
707                                      fileName,
708                                      replaceExisting);
709                         }
710                     } catch (Exception JavaDoc e) {
711                         setProgress(FAILED);
712                         HashMap JavaDoc status = new HashMap JavaDoc();
713                         status.put(e.toString(), Boolean.valueOf(FAILURE));
714                         progressReport.put(serverName, status);
715                         continue;
716                     }
717                 } catch (Exception JavaDoc e) {
718                     setProgress(FAILED);
719                     HashMap JavaDoc status = new HashMap JavaDoc();
720                     status.put("Could not connect to: " +
721                             serverName + ". Error: " + e.toString(), Boolean.valueOf(FAILURE));
722                     progressReport.put(serverName, status);
723                     continue;
724                 }
725             }
726             if (!getProgress().equals(FAILED)) {
727                 setProgress(COMPLETED);
728             }
729         } else {
730             setProgress(FAILED);
731         }
732         return true;
733
734     }
735     
736     /**
737      * Deploy a module on a given server.
738      *
739      * @param connection MBeanServerConnection to use to invoke an MBean operation
740      * @param targetOn ObjectName of the target server
741      * @param opName the name of the deploy operation
742      * @param opParams the parameters to this deploy operation
743      * @param opSignature the method signature of the deploy operation
744      * @param fileName the name of the module to deploy
745      * @throws Exception if an exception is thrown during the undeployment
746      */

747     private void doDeploy(MBeanServerConnection JavaDoc connection, ObjectName JavaDoc targetOn,
748                           String JavaDoc opName, Object JavaDoc[] opParams, String JavaDoc[] opSignature,
749                           String JavaDoc fileName)
750     throws Exception JavaDoc {
751         
752         String JavaDoc serverName = targetOn.getKeyProperty("name");
753         
754         if (!isDeployed(connection, targetOn, opName, opParams, opSignature)) {
755             
756             connection.invoke(targetOn, opName, opParams, opSignature);
757             
758             if (logger.isLoggable(BasicLevel.DEBUG)) {
759                 logger.log(BasicLevel.DEBUG, "Opearation "
760                                 + opName + "'" + fileName
761                                 + ") on target " + serverName
762                                 + " done");
763             }
764             //progressReport.put(serverName, DEPLOYED);
765
HashMap JavaDoc status = new HashMap JavaDoc();
766             status.put(DEPLOYED, new Boolean JavaDoc(SUCCESS));
767             progressReport.put(serverName, status);
768         } else {
769             //progressReport.put(serverName, "File is already deployed.");
770
HashMap JavaDoc status = new HashMap JavaDoc();
771             status.put("File is already deployed.", new Boolean JavaDoc(FAILURE));
772             progressReport.put(serverName, status);
773         }
774     }
775     
776     /**
777      * Undeploy a module on a given server.
778      *
779      * @param connection MBeanServerConnection to use to invoke an MBean operation
780      * @param targetOn ObjectName of the target server
781      * @param opName the name of the unDeploy operation
782      * @param opParams the parameters to this undeploy operation
783      * @param opSignature the method signature of the undeploy operation
784      * @param fileName the name of the module to undeploy
785      * @throws Exception if an exception is thrown during the deployment
786      */

787     private void doUnDeploy(MBeanServerConnection JavaDoc connection, ObjectName JavaDoc targetOn,
788             String JavaDoc opName, Object JavaDoc[] opParams, String JavaDoc[] opSignature, String JavaDoc fileName)
789     throws Exception JavaDoc {
790         
791         String JavaDoc serverName = targetOn.getKeyProperty("name");
792         
793         if (isDeployed(connection, targetOn, opName, opParams, opSignature)) {
794             
795             connection.invoke(targetOn, opName, opParams, opSignature);
796             
797             if (logger.isLoggable(BasicLevel.DEBUG)) {
798                 logger.log(BasicLevel.DEBUG, "Opearation "
799                                 + opName + "'" + fileName
800                                 + ") on target " + serverName
801                                 + " done");
802             }
803             HashMap JavaDoc status = new HashMap JavaDoc();
804             status.put(UNDEPLOYED, Boolean.valueOf(SUCCESS));
805             progressReport.put(serverName, status);
806         } else {
807             HashMap JavaDoc status = new HashMap JavaDoc();
808             status.put("File is not deployed.", Boolean.valueOf(FAILURE));
809             progressReport.put(serverName, status);
810         }
811     }
812     
813     /**
814      * Upload and (re)deploy a file on a target server.
815      *
816      * @param connection MBeanServerConnection to use to invoke an MBean operation
817      * @param targetOn ObjectName of the target server
818      * @param opName the name of the operation
819      * @param opParams the parameters to this undeploy operation
820      * @param opSignature the method signature of the undeploy operation
821      * @param fileName the name of the module to upload and redeploy
822      * @param replaceExisting If an existing file of the same name should be replaced.
823      * @throws Exception if an exception is thrown during the deployment
824      */

825     private void doUploadReDeploy(MBeanServerConnection JavaDoc connection, ObjectName JavaDoc targetOn,
826             String JavaDoc opName, Object JavaDoc[] opParams, String JavaDoc[] opSignature, String JavaDoc fileName, boolean replaceExisting)
827     throws Exception JavaDoc {
828         
829         String JavaDoc serverName = targetOn.getKeyProperty("name");
830         String JavaDoc uploadedName = fileName;
831         
832         try {
833             uploadedName = doUpload(connection, targetOn, fileName, replaceExisting);
834         } catch (Exception JavaDoc e) {
835             HashMap JavaDoc status = new HashMap JavaDoc();
836             status.put("File failed to upload: " + e.toString(), Boolean.valueOf(FAILURE));
837             progressReport.put(serverName, status);
838             return;
839         }
840         
841         // the parameter needs to change to reflect the name of the module after
842
// it was uploaded. So when we are uploading '/usr/share/java/some.jar'
843
// it will need to be given to the deployJar command as 'deploy.jar'
844
opParams[0] = uploadedName;
845         
846         boolean isDeployed = isDeployed(connection, targetOn, opName, opParams, opSignature);
847         // redeploy an application because the module was replaced by a new one
848
if (isDeployed && replaceExisting) {
849             doUnDeploy(connection, targetOn, getUnDeployType(opName), opParams, opSignature, fileName);
850             doDeploy(connection, targetOn, getDeployType(opName), opParams, opSignature, fileName);
851         }
852         // the uploaded module was not deployed, need to deploy it
853
else if (!isDeployed) {
854             doDeploy(connection,targetOn, getDeployType(opName), opParams, opSignature, fileName);
855         } else {
856             // Do nothing.
857
}
858     }
859     
860     /**
861      * Uploads a file to a target server.
862      *
863      * @param connection MBeanServerConnection to use to invoke an MBean operation
864      * @param targetOn ObjectName of the target server
865      * @param fileName The file to upload
866      * @param replaceExisting If an existing file of the same name should be replaced.
867      * @return The path of the uploaded file.
868      * @throws Exception if an exception is thrown during the deployment
869      */

870     private String JavaDoc doUpload(MBeanServerConnection JavaDoc connection, ObjectName JavaDoc targetOn, String JavaDoc fileName, boolean replaceExisting) throws Exception JavaDoc {
871
872         String JavaDoc opName = "sendFile";
873         
874         File JavaDoc file = null;
875         // first try the file name as it is
876
file = new File JavaDoc(fileName).getCanonicalFile();
877         String JavaDoc deployName = file.getName();
878         if (!file.exists()) {
879             // if the file was not found try looking for it under JONAS_BASE
880
String JavaDoc dir = getFolderDir(fileName);
881             file = new File JavaDoc(dir, fileName);
882             deployName = fileName;
883         }
884
885         FileInputStream JavaDoc inputStream = new FileInputStream JavaDoc(file);
886         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
887         byte[] buf = new byte[BUFFER_SIZE];
888         // Read bytes
889
int len;
890         while ((len = inputStream.read(buf)) > 0) {
891             baos.write(buf, 0, len);
892         }
893         byte[] bytesOfFile = baos.toByteArray();
894
895         Object JavaDoc[] opParams = new Object JavaDoc[]{bytesOfFile, deployName, Boolean.valueOf(replaceExisting)};
896         String JavaDoc[] opSignature = new String JavaDoc[]{"[B", "java.lang.String", "boolean"};
897         String JavaDoc filePath = (String JavaDoc) connection.invoke(targetOn, opName, opParams, opSignature);
898         
899         String JavaDoc serverName = targetOn.getKeyProperty("name");
900         HashMap JavaDoc status = new HashMap JavaDoc();
901         status.put("File uploaded to: '" + filePath + "'" , Boolean.valueOf(SUCCESS));
902         progressReport.put(serverName, status);
903         
904         return deployName;
905     }
906     
907     /**
908      * Returns the directory that a file would be found in.
909      *
910      * @param fileName the file to find the directory for.
911      * @return The directory of the given file.
912      * @throws Exception if an exception is thrown during the deployment
913      */

914     private String JavaDoc getFolderDir(String JavaDoc fileName) throws Exception JavaDoc {
915         String JavaDoc jBase = JProp.getJonasBase();
916         // based on extension
917
String JavaDoc dir = null;
918         // EJB
919
if (fileName.toLowerCase().endsWith(".jar")) {
920             dir = jBase + File.separator + "ejbjars";
921         } else if (fileName.toLowerCase().endsWith(".war")) {
922             // War file
923
dir = jBase + File.separator + "webapps";
924         } else if (fileName.toLowerCase().endsWith(".ear")) {
925             // ear file
926
dir = jBase + File.separator + "apps";
927         } else if (fileName.toLowerCase().endsWith(".rar")) {
928             // rar file
929
dir = jBase + File.separator + "rars";
930         } else {
931             // invalid type
932
throw new Exception JavaDoc("Invalid extension for the file '" + fileName
933                     + "'. Valid are .jar, .war, .ear, .rar");
934         }
935         return dir;
936     }
937     
938     /**
939      * If a file is already deployed on a target server
940      *
941      * @param connection the MBeanServerConnection to use to invoke the MBean operation
942      * @param targetOn The target server name.
943      * @param opName the name of the operation that was used to call this.
944      * @param opParams the parameters to the MBean's invoke call.
945      * @param opSignature the signature for the parameters.
946      * @return if the given file is already deployed on the target server.
947      * @throws Exception if an exception is thrown during the deployment
948      */

949     private boolean isDeployed(MBeanServerConnection JavaDoc connection,
950             ObjectName JavaDoc targetOn, String JavaDoc opName, Object JavaDoc[] opParams,
951             String JavaDoc[] opSignature) throws Exception JavaDoc {
952
953         Boolean JavaDoc deployed = (Boolean JavaDoc) connection.invoke(targetOn,
954                 getIsDeployedType(opName), opParams, opSignature);
955
956         return deployed.booleanValue();
957     }
958
959     /**
960      * Returns which 'is deployed' method to use.
961      * @param opName The operation being invoked.
962      * @return Which 'is deployed' method to use.
963      */

964     private String JavaDoc getIsDeployedType(String JavaDoc opName) {
965         String JavaDoc result = "";
966         if (opName.indexOf("Ear") != -1) {
967             result = "isEarDeployed";
968         } else if (opName.indexOf("War") != -1) {
969             result = "isWarDeployed";
970         } else if (opName.indexOf("Rar") != -1) {
971             result = "isRarDeployed";
972         } else if (opName.indexOf("Jar") != -1) {
973             result = "isJarDeployed";
974         }
975         return result;
976     }
977
978     /**
979      * Depending on the name of the operation, which unDeploy method to use.
980      * @param opName the operation name that was used to call this.
981      * @return the right unDeploy method name to use.
982      */

983     private String JavaDoc getUnDeployType(String JavaDoc opName) {
984         String JavaDoc result = "";
985         if (opName.indexOf("Ear") != -1) {
986             result = "unDeployEar";
987         } else if (opName.indexOf("War") != -1) {
988             result = "unDeployWar";
989         } else if (opName.indexOf("Rar") != -1) {
990             result = "unDeployRar";
991         } else if (opName.indexOf("Jar") != -1) {
992             result = "unDeployJar";
993         }
994         return result;
995     }
996
997     /**
998      * Depending on the name of the operation, which deploy method to use.
999      * @param opName the operation name that was used to call this.
1000     * @return the right deploy method name to use.
1001     */

1002    private String JavaDoc getDeployType(String JavaDoc opName) {
1003        String JavaDoc result = "";
1004        if (opName.indexOf("Ear") != -1) {
1005            result = "deployEar";
1006        } else if (opName.indexOf("War") != -1) {
1007            result = "deployWar";
1008        } else if (opName.indexOf("Rar") != -1) {
1009            result = "deployRar";
1010        } else if (opName.indexOf("Jar") != -1) {
1011            result = "deployJar";
1012        }
1013        return result;
1014    }
1015
1016    /**
1017     * Check the current progress and determine whether a new deployment operation
1018     * is to be rejected or accepted.
1019     *
1020     * @return true if the operation should be rejected because another operation
1021     * is still running, false is the operation should be accepted and the
1022     * progress is set to RUNNING
1023     */

1024    private boolean isAnotherOperationRunning() {
1025        if (progress == null) {
1026            setProgress(RUNNING);
1027        } else {
1028            if (!getProgress().equals(RUNNING)) {
1029                setProgress(RUNNING);
1030            } else {
1031                return true;
1032            }
1033        }
1034        return false;
1035    }
1036
1037    /**
1038     * Return true if all the elements in target are present in myServers list
1039     * @param target array of server OBJECT_NAMEs
1040     * @return true if all the elements in target are present in myServers list
1041     */

1042    private boolean isTargetCorrect(String JavaDoc[] target) {
1043        for (int i = 0; i < target.length; i++) {
1044            if (!myServers.contains(target[i])) {
1045                setGlobalErrorReport("Target element " + target[i] + " is not registered in J2EEDomain MBean " + getObjectName());
1046                return false;
1047            }
1048        }
1049        return true;
1050    }
1051
1052    /**
1053     * Test a connection for server serverName
1054     * @param connection MBeanServerConnection to test
1055     * @param serverName the server's name
1056     * @throws IOException if thrown, the connection is faulty
1057     */

1058    private void testConnection(MBeanServerConnection JavaDoc connection, String JavaDoc serverName) throws IOException JavaDoc {
1059        Integer JavaDoc nb = connection.getMBeanCount();
1060        //System.out.println("OK Connection for server " + serverName);
1061
}
1062
1063    /**
1064     * @return Returns the jmxService.
1065     */

1066    public JmxService getJmxService() {
1067        return jmxService;
1068    }
1069
1070    /**
1071     * @param jmxService The jmxService to set.
1072     */

1073    public void setJmxService(JmxService jmxService) {
1074        this.jmxService = jmxService;
1075    }
1076
1077    /**
1078     * @return Returns the report.
1079     */

1080    public HashMap JavaDoc getProgressReport() {
1081        return progressReport;
1082    }
1083
1084    /**
1085     * @param report The report to set.
1086     */

1087    public void setProgressReport(HashMap JavaDoc report) {
1088        this.progressReport = report;
1089    }
1090
1091    /**
1092     * @return Returns the globalErrorReport.
1093     */

1094    public String JavaDoc getGlobalErrorReport() {
1095        return globalErrorReport;
1096    }
1097
1098    /**
1099     * @param globalErrorReport The globalErrorReport to set.
1100     */

1101    public void setGlobalErrorReport(String JavaDoc globalErrorReport) {
1102        this.globalErrorReport = globalErrorReport;
1103    }
1104}
1105
Popular Tags