KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > server > J2EEServerMBean


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2005 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  * $Id: J2EEServerMBean.java,v 1.39 2005/06/08 09:38:15 benoitf Exp $
22  * --------------------------------------------------------------------------
23  */

24 package org.objectweb.jonas.server;
25
26 // Java imports
27
import java.io.File JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.net.URLClassLoader JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Arrays JavaDoc;
35
36 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
37 import javax.management.MBeanException JavaDoc;
38 import javax.management.Notification JavaDoc;
39 import javax.management.NotificationFilter JavaDoc;
40 import javax.management.NotificationListener JavaDoc;
41
42 import org.apache.commons.modeler.BaseModelMBean;
43
44 import org.objectweb.common.Cmd;
45
46 import org.objectweb.jonas_ear.deployment.api.EarDeploymentDesc;
47 import org.objectweb.jonas_ear.deployment.api.EarDeploymentDescException;
48 import org.objectweb.jonas_ear.deployment.lib.wrapper.EarManagerWrapper;
49
50 import org.objectweb.jonas_ejb.genic.wrapper.GenicServiceWrapper;
51
52 import org.objectweb.jonas_lib.files.FileUtils;
53 import org.objectweb.jonas_lib.genclientstub.wrapper.ClientGenStubWrapper;
54
55 import org.objectweb.jonas_web.deployment.api.WebContainerDeploymentDescException;
56 import org.objectweb.jonas_web.deployment.lib.wrapper.WebManagerWrapper;
57
58 import org.objectweb.jonas_ws.wsgen.wrapper.WsGenWrapper;
59
60 import org.objectweb.jonas.common.JProp;
61 import org.objectweb.jonas.common.Log;
62 import org.objectweb.jonas.container.EJBService;
63 import org.objectweb.jonas.ear.EarService;
64 import org.objectweb.jonas.ear.EarServiceException;
65 import org.objectweb.jonas.resource.ResourceService;
66 import org.objectweb.jonas.service.ServiceException;
67 import org.objectweb.jonas.service.ServiceManager;
68 import org.objectweb.jonas.web.JWebContainerService;
69
70 import org.objectweb.util.monolog.api.BasicLevel;
71 import org.objectweb.util.monolog.api.Logger;
72
73 /**
74  * MBean class for Server management. Two classes are used to provide all
75  * management services : J2EEServer and J2EEServerMBean. This class provide the
76  * notification's process when add or remove resources.
77  * @author Adriana Danes
78  * @author Michel-Ange Anton
79  */

80
81 public class J2EEServerMBean extends BaseModelMBean {
82
83     /**
84      * Logger
85      */

86     private static Logger mgtLogger = Log.getLogger(Log.JONAS_MANAGEMENT_PREFIX);
87
88     /**
89      * Default constructor
90      * @throws MBeanException if super constructor fails
91      */

92     public J2EEServerMBean() throws MBeanException JavaDoc {
93         super();
94     }
95
96     // ------------------------------------------------------------- Public
97
// methods
98

99     /**
100      * All The MBean names corresponding to the deployed J2EEModules (ear, jar,
101      * war, rar).
102      * @return The String's array of deployed modules objects names
103      */

104     public String JavaDoc[] getDeployedObjects() {
105         ArrayList JavaDoc al = (ArrayList JavaDoc) ((J2EEServer) (this.resource)).getDeployedObjects();
106         return (String JavaDoc[]) al.toArray(new String JavaDoc[al.size()]);
107     }
108
109     /**
110      * All The MBean names corresponding to the deployed J2EEResources.
111      * @return The String's array of deployed resources objects names
112      */

113     public String JavaDoc[] getResources() {
114         ArrayList JavaDoc al = (ArrayList JavaDoc) ((J2EEServer) (this.resource)).getResources();
115         return (String JavaDoc[]) al.toArray(new String JavaDoc[al.size()]);
116     }
117
118     /**
119      * All The MBean names corresponding to the used JVMs.
120      * @return The String's array of used JVMs objects names
121      */

122     public String JavaDoc[] getJavaVMs() {
123         ArrayList JavaDoc al = (ArrayList JavaDoc) ((J2EEServer) (this.resource)).getJavaVMs();
124         return (String JavaDoc[]) al.toArray(new String JavaDoc[al.size()]);
125     }
126
127     /**
128      * Send a notification to the listener.
129      * @param pNotification The notification to send
130      */

131     public void sendNotification(Notification JavaDoc pNotification) {
132         ((J2EEServer) (this.resource)).sendNotification(pNotification);
133     }
134
135     /**
136      * Add a new listener.
137      * @param pListner Listener to notify
138      * @param pFilter Notification filter
139      * @param pHandback ??
140      * @throws java.lang.IllegalArgumentException if notification is not done
141      */

142     public void addNotificationListener(NotificationListener JavaDoc pListner, NotificationFilter JavaDoc pFilter,
143             java.lang.Object JavaDoc pHandback) throws java.lang.IllegalArgumentException JavaDoc {
144         ((J2EEServer) (this.resource)).addNotificationListener(pListner, pFilter, pHandback);
145     }
146
147     /**
148      * Deploy a stand-alone J2EE module packaged in a JAR file
149      * @param fileName file name
150      * @return The ObjectName of the MBean associated to the deployed module
151      * @throws Exception Management operation failed
152      */

153     public String JavaDoc deployJar(String JavaDoc fileName) throws Exception JavaDoc {
154         return ((J2EEServer) (this.resource)).deployJar(fileName);
155     }
156
157     /**
158      * Deploy a stand-alone J2EE module packaged in a War file
159      * @param fileName file name
160      * @throws Exception Management operation failed
161      */

162     public void deployWar(String JavaDoc fileName) throws Exception JavaDoc {
163         ((J2EEServer) (this.resource)).deployWar(fileName);
164     }
165
166     /**
167      * Deploy a J2EE application packaged in a EAR file
168      * @param fileName file name
169      * @return The ObjectName of the MBean associated to the deployed J2EE
170      * Application
171      * @throws Exception Management operation failed
172      */

173     public String JavaDoc deployEar(String JavaDoc fileName) throws Exception JavaDoc {
174         return ((J2EEServer) (this.resource)).deployEar(fileName);
175     }
176
177     /**
178      * Deploy a J2EE application packaged in a RAR file
179      * @param fileName file name
180      * @return The ObjectName of the MBean associated to the deployed J2EE
181      * Application
182      * @throws Exception Management operation failed
183      */

184     public String JavaDoc deployRar(String JavaDoc fileName) throws Exception JavaDoc {
185         return ((J2EEServer) (this.resource)).deployRar(fileName);
186     }
187
188     /**
189      * Test if the specified filename is already deployed or not.
190      * @param fileName the name of the ear file.
191      * @return true if the ear is deployed, otherwise false.
192      * @throws Exception Management operation failed
193      */

194     public Boolean JavaDoc isEarDeployed(String JavaDoc fileName) throws Exception JavaDoc {
195         return ((J2EEServer) (this.resource)).isEarDeployed(fileName);
196     }
197
198     /**
199      * Test if the specified filename is already deployed or not.
200      * @param fileName the name of the rar file.
201      * @return true if the rar is deployed, otherwise false.
202      * @throws Exception Management operation failed
203      */

204     public Boolean JavaDoc isRarDeployed(String JavaDoc fileName) throws Exception JavaDoc {
205         return ((J2EEServer) (this.resource)).isRarDeployed(fileName);
206     }
207
208     /**
209      * Test if the specified filename is already deployed or not.
210      * @param fileName the name of the jar file.
211      * @return true if the jar is deployed, otherwise false.
212      * @throws Exception Management operation failed
213      */

214     public Boolean JavaDoc isJarDeployed(String JavaDoc fileName) throws Exception JavaDoc {
215         return ((J2EEServer) (this.resource)).isJarDeployed(fileName);
216     }
217
218     /**
219      * Test if the specified filename is already deployed or not.
220      * @param fileName the name of the War file.
221      * @return true if the jar is deployed, otherwise false.
222      * @throws Exception Management operation failed
223      */

224     public Boolean JavaDoc isWarDeployed(String JavaDoc fileName) throws Exception JavaDoc {
225         return ((J2EEServer) (this.resource)).isWarDeployed(fileName);
226     }
227
228     /**
229      * Deploy local file and generate classes with Genic tool
230      * @param pathname : local path name to the application
231      * @param genicArgs : list of genic's parameters
232      */

233     public void deployLocalFile(String JavaDoc pathname, String JavaDoc[] genicArgs) {
234         try {
235                callGenic(genicArgs, pathname);
236         } catch (Exception JavaDoc e) {
237             mgtLogger.log(BasicLevel.WARN, "Cannot generate classes for this application : '" + pathname + ". " + e.getMessage() + "'.");
238         }
239     }
240
241     /**
242      * Deploy file (GenIC), needed for Ishmael to work. The file is in the
243      * directory specified by the property "jonas.service.deployment.directory"
244      * @param typeparam type of the file (EJB, WAR, EAR, RAR, CAR)
245      * @param bfile bytes array of the file
246      * @param filename basename of the file to be deployed (if moveIntoDeployableDirectory full path name because local file)
247      * @param genicArgs arguments for GenIC
248      * @param moveIntoDeployableDirectory true to copy the file into the deployable JOnAS_BASE directory
249      * @throws RemoteException
250      * @throws EarServiceException
251      * @throws ResourceServiceException
252      * @throws JWebContainerServiceException
253      * @return absolute path of the file
254      * @author Dean Jennings. <da_jennings@junta.com.au>
255      */

256     public String JavaDoc deployFile(Integer JavaDoc typeparam, java.lang.Byte JavaDoc[] bfile, String JavaDoc filename, String JavaDoc[] genicArgs, Boolean JavaDoc moveIntoDeployableDirectory) {
257         String JavaDoc directory = "";
258         int type = typeparam.intValue();
259
260         ServiceManager serviceManager = null;
261         try {
262             serviceManager = ServiceManager.getInstance();
263         } catch (Exception JavaDoc e) {
264             // TODO
265
mgtLogger.log(BasicLevel.ERROR, "Cannot get the instance of the Service Manager : '" + e.getMessage()
266                     + "'.");
267         }
268
269         boolean isJar = false;
270         if (type == ModuleType.EJB.getValue()) {
271                 directory = ((EJBService) serviceManager.getEjbService()).getEjbjarsDirectory();
272                 isJar = true;
273         } else if (type == ModuleType.EAR.getValue()) {
274                 directory = ((EarService) serviceManager.getEarService()).getAppsDirectory();
275         } else if (type == ModuleType.WAR.getValue()) {
276                 directory = ((JWebContainerService) serviceManager.getWebContainerService()).getWebappsDirectory();
277         } else if (type == ModuleType.RAR.getValue()) {
278                 directory = ((ResourceService) serviceManager.getResourceService()).getRarsDirectory();
279         } else if (type == ModuleType.CAR.getValue()) {
280             // do nothing
281
}
282         File JavaDoc file;
283         if (moveIntoDeployableDirectory.booleanValue()) {
284            file = new File JavaDoc(directory + filename);
285         } else {
286            file = new File JavaDoc(filename);
287         }
288         try {
289             FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(file);
290             byte[] bfileused = new byte[bfile.length];
291             for (int i = 0; i < bfile.length; i++) {
292                 bfileused[i] = bfile[i].byteValue();
293             }
294             out.write(bfileused);
295             out.close();
296             if (type == ModuleType.EJB.getValue()) {
297                     try {
298                         callGenic(genicArgs, file.getAbsolutePath());
299                     } catch (ServiceException e) {
300                         mgtLogger.log(BasicLevel.WARN, "deploy File error " + filename + e.getClass().getName() + " "
301                                 + e.getMessage());
302                     }
303             } else if (type == ModuleType.EAR.getValue()) {
304                 unpackAndCompileEar(file, genicArgs);
305             } else if (type == ModuleType.WAR.getValue()) {
306                  checkWebAppDeploymentDesc(file);
307             } else {
308                 if (mgtLogger.isLoggable(BasicLevel.DEBUG)) {
309                     mgtLogger.log(BasicLevel.DEBUG, "Deployment not yet implemented for type '" + type + ".");
310                 }
311             }
312         } catch (IOException JavaDoc ioe) {
313             mgtLogger.log(BasicLevel.ERROR, "Cannot dump to outputstream the file '" + file + "' : '"
314                     + ioe.getMessage() + "'.", ioe);
315             // TODO
316
}
317
318         // Ugly but don't work without it ...
319
try {
320             Thread.sleep(1000);
321         } catch (InterruptedException JavaDoc e1) {
322             e1.printStackTrace();
323         }
324
325         if (!filename.endsWith(".rar")) {
326             String JavaDoc modifiedArchive = null;
327             ClientGenStubWrapper clientWrapper = new ClientGenStubWrapper();
328             try {
329                 modifiedArchive = clientWrapper.callClientGenStubExecute(file.getPath());
330             } catch (Exception JavaDoc e) {
331                 mgtLogger.log(BasicLevel.ERROR, "Cannot launch ClientGenStub on the file '" + file + "' : '"
332                         + e.getCause().getMessage() + "'.", e);
333             }
334
335             boolean modified = false;
336             try {
337                 modified = clientWrapper.callClientGenStubIsInputModifed();
338             } catch (Exception JavaDoc e) {
339                 mgtLogger.log(BasicLevel.ERROR, "Cannot launch ClientGenStub.isInputModified '" + file + "' : '"
340                         + e.getCause().getMessage() + "'.", e);
341                 // assume file has been modified
342
modified = true;
343             }
344
345             if (modified) {
346                 // assume also that we can call WsGen after
347
File JavaDoc newFile = new File JavaDoc(modifiedArchive);
348                 try {
349                     FileUtils.copyFile(newFile, file);
350                 } catch (Exception JavaDoc e) {
351                     mgtLogger.log(BasicLevel.ERROR, "Error when copying file '" + newFile + "'. : " + e.getMessage());
352                 }
353
354                 // Ugly but don't work without it ...
355
try {
356                     Thread.sleep(1000);
357                 } catch (InterruptedException JavaDoc e1) {
358                     e1.printStackTrace();
359                 }
360
361                 WsGenWrapper ww = new WsGenWrapper();
362                 try {
363                     modifiedArchive = ww.callWsGenExecute(file.getPath());
364                 } catch (Exception JavaDoc e) {
365                     mgtLogger.log(BasicLevel.ERROR, "Cannot launch WsGen on the file '" + file + "' : '"
366                             + e.getCause().getMessage() + "'.", e);
367                 }
368
369                 try {
370                     modified = ww.callWsGenIsInputModifed();
371                 } catch (Exception JavaDoc e) {
372                     mgtLogger.log(BasicLevel.ERROR, "Cannot launch WsGen on the file '" + file + "' : '"
373                             + e.getCause().getMessage() + "'.", e);
374                 }
375
376                 if (modified) {
377                     // assume also that we can call WsGen after
378
File JavaDoc newFile2 = new File JavaDoc(modifiedArchive);
379                     // Check for modifiedArchive suffix
380
if (modifiedArchive.endsWith(".ear")) {
381                         // check if input file is a jar
382
if (isJar) {
383                             // this case is special: we got a JAR in input and generate a EAR in output
384
// the output goes to apps directory
385
String JavaDoc modifiedDirectory = ((EarService) serviceManager.getEarService()).getAppsDirectory();
386                             file = new File JavaDoc(modifiedDirectory + newFile2.getName());
387                         }
388                     }
389                     try {
390                         FileUtils.copyFile(newFile2, file);
391                     } catch (Exception JavaDoc e) {
392                         mgtLogger.log(BasicLevel.ERROR, "Error when copying file '" + newFile2 + "'. : " + e.getMessage());
393                     }
394                     return file.getPath();
395                 }
396
397                 return modifiedArchive;
398             } else {
399                 // don't call wsgen as it will fail with DTD too
400
return file.getPath();
401             }
402         } else {
403             return file.getPath();
404         }
405     }
406
407
408     /**
409      * Call GenIC by using a wrapper
410      * @param genicArgs arguments for GenIC
411      * @param jarPath path of the jar file
412      */

413     private void callGenic(String JavaDoc[] genicArgs, String JavaDoc jarPath) {
414         String JavaDoc[] args;
415         if (genicArgs != null) {
416             args = new String JavaDoc[genicArgs.length + 1];
417             for (int i = 0; i < genicArgs.length; i++) {
418                 args[i] = genicArgs[i];
419             }
420             args[genicArgs.length] = jarPath;
421         } else {
422             args = new String JavaDoc[1];
423             args[0] = jarPath;
424         }
425         if (mgtLogger.isLoggable(BasicLevel.DEBUG)) {
426             mgtLogger.log(BasicLevel.DEBUG, "Calling GenIC with arguments :" + Arrays.asList(args));
427         }
428         GenicServiceWrapper.callGenic(args);
429     }
430
431     /**
432      * Unpack and then launch GenIC on each ejb jar files
433      * @param file ear file
434      * @param genicArgs arguments for GenIC
435      * @throws ServiceException if this step fails
436      */

437     private void unpackAndCompileEar(File JavaDoc file, String JavaDoc[] genicArgs) throws ServiceException {
438         URL JavaDoc[] earUrl = new URL JavaDoc[1];
439
440         try {
441             earUrl[0] = file.toURL();
442         } catch (MalformedURLException JavaDoc e) {
443             // TODO
444
mgtLogger.log(BasicLevel.ERROR, "The url for the file '" + file + "' cannot be built : '" + e.getMessage()
445                     + "'.");
446         }
447
448         //Create classLoader
449
//parent classloader is the current classloader
450
ClassLoader JavaDoc currentLoader = Thread.currentThread().getContextClassLoader();
451         URLClassLoader JavaDoc loaderCls = new URLClassLoader JavaDoc(earUrl, currentLoader);
452
453         EarDeploymentDesc desc = null;
454         try {
455             desc = EarManagerWrapper.getDeploymentDesc(earUrl[0].getFile(), loaderCls);
456         } catch (EarDeploymentDescException e) {
457             // TODO
458
mgtLogger.log(BasicLevel.ERROR, "Cannot get deployment descriptor for the Ear file '" + file + "' : '"
459                     + e.getMessage() + "'.");
460         }
461
462         String JavaDoc[] ejbTags = desc.getEjbTags();
463         if (ejbTags.length != 0) {
464             // need to call GENIC
465
/*
466              * Example of a jar command: jar -uf ../output/ejbjars/sb.jar -C
467              * /tmp/genic1547.tmp a/b/C1.class -C /tmp/genic1547.tmp
468              * a/b/C2.class .....
469              */

470             String JavaDoc javaHomeBin = System.getProperty("java.home", "");
471             if (!("".equals(javaHomeBin))) {
472                 javaHomeBin = javaHomeBin + File.separator + ".." + File.separator + "bin" + File.separator;
473             }
474
475             Cmd cmd = null;
476             cmd = new Cmd(javaHomeBin + "jar");
477             cmd.addArgument("-xf");
478             cmd.addArgument(file.getAbsolutePath());
479
480             for (int i = 0; i < ejbTags.length; i++) {
481                 cmd.addArgument(ejbTags[i]);
482             }
483
484             boolean exitCmd = cmd.run();
485             // Analyse the result of the jar command
486
if (!exitCmd) {
487                 throw new EarServiceException("Failed when extracting the the ejb jar " + "in the given jar file '"
488                         + file + "'.");
489             }
490
491             for (int i = 0; i < ejbTags.length; i++) {
492                 try {
493                     callGenic(genicArgs, ejbTags[i]);
494                 } catch (ServiceException e) {
495                     throw (e);
496                 }
497             }
498             // add modified jar into ear
499
cmd = new Cmd(javaHomeBin + "jar");
500             cmd.addArgument("-uf");
501             cmd.addArgument(file.getAbsolutePath());
502
503             for (int i = 0; i < ejbTags.length; i++) {
504                 cmd.addArgument(ejbTags[i]);
505             }
506             exitCmd = cmd.run();
507             // Analyse the result of the jar command
508
if (!exitCmd) {
509                 throw new EarServiceException("Failed when extracting the the ejb jar " + "in the given jar file '"
510                         + file + "'.");
511             }
512
513             for (int i = 0; i < ejbTags.length; i++) {
514                 File JavaDoc del = new File JavaDoc(ejbTags[i]);
515                 del.delete();
516             }
517         }
518         desc = null;
519     }
520
521     /**
522      * Validate deployment descriptor of the War file
523      * @param file given file
524      */

525     private void checkWebAppDeploymentDesc(File JavaDoc file) {
526         URL JavaDoc warUrl = null;
527
528         try {
529             warUrl = file.toURL();
530         } catch (MalformedURLException JavaDoc mue) {
531             mgtLogger.log(BasicLevel.ERROR, "The url for the file '" + file + "' cannot be built : '"
532                     + mue.getMessage() + "'.");
533             throw new RuntimeException JavaDoc(mue);
534         }
535
536         URLClassLoader JavaDoc warCl = new URLClassLoader JavaDoc(new URL JavaDoc[] {warUrl});
537
538         try {
539             WebManagerWrapper.getDeploymentDesc(warUrl, warCl, null);
540         } catch (WebContainerDeploymentDescException e) {
541             String JavaDoc err = "Cannot read the deployment descriptors '" + warUrl.getFile() + "'";
542             mgtLogger.log(BasicLevel.ERROR, err + ": " + e);
543             e.printStackTrace(System.err);
544             throw new RuntimeException JavaDoc(err, e);
545         }
546
547     }
548
549     /**
550      * Add an object name to the <code>resources</code> list.
551      * @param pObjectName Object name correspondig to a J2EEResource MBean
552      */

553     //
554
// public static void addResource(String pObjectName) {
555
// try {
556
// Server oServer = Server.getInstance();
557
// J2EEServer oJ2EEServer = oServer.getJ2EEServer();
558
// oJ2EEServer.addResource(pObjectName);
559
// } catch (Exception e) {
560
// mgtLogger.log(BasicLevel.WARN
561
// , "Add resource error (object=" + pObjectName + ") : "
562
// + e.getClass().getName() + " " + e.getMessage());
563
// }
564
// }
565
/**
566      * Remove an object name from the <code>resources</code> list.
567      * @param pObjectName Object name correspondig to a J2EEResource MBean
568      * @return Object name to the removed J2EEResource MBean
569      */

570
571     // public static String removeResource(String pObjectName) {
572
// String sRet = null;
573
// try {
574
// Server oServer = Server.getInstance();
575
// J2EEServer oJ2EEServer = oServer.getJ2EEServer();
576
// sRet = oJ2EEServer.removeResource(pObjectName);
577
// } catch (Exception e) {
578
// mgtLogger.log(BasicLevel.WARN
579
// , "Remove resource object error (object=" + pObjectName + ") : "
580
// + e.getClass().getName() + " " + e.getMessage());
581
// }
582
// return sRet;
583
// }
584

585
586     /**
587      * Send a file to JOnAS Base with the given input stream and write it
588      * in the corresponding directory, ie JONAS_BASE/apps, JONAS_BASE/ejbjars, etc.
589      * It is based on the filename extension
590      * @param fileContent the content (bytes) of the file
591      * @param fileName name of the file
592      * @param replaceExisting replace existing file if any
593      * @return the path of the file
594      * @throws Exception if file is already present and if the user don't want to replace existing file.
595      */

596     public String JavaDoc sendFile(byte[] fileContent, String JavaDoc fileName, boolean replaceExisting) throws Exception JavaDoc {
597
598         File JavaDoc directoryUploadedFile = null;
599         FileOutputStream JavaDoc fos = null;
600         try {
601             // Get directory where to upload file, based on extension
602
String JavaDoc dir = getFolderDir(fileName);
603
604             // set the dest file
605
directoryUploadedFile = new File JavaDoc(dir, fileName);
606             // check, by default we can't overwrite an existing file.
607
if (directoryUploadedFile.exists() && !replaceExisting) {
608                 throw new Exception JavaDoc("File '" + directoryUploadedFile + "' already exists on the server.");
609             }
610
611             // write the bytes to the given file
612
fos = new FileOutputStream JavaDoc(directoryUploadedFile);
613             fos.write(fileContent);
614         } finally {
615             if (fos != null) {
616                 try {
617                     // close the output stream
618
fos.close();
619                 } catch (IOException JavaDoc ioe) {
620                     mgtLogger.log(BasicLevel.DEBUG, "Cannot close the output stream", ioe);
621                 }
622             }
623
624         }
625         if (directoryUploadedFile != null) {
626             return directoryUploadedFile.getPath();
627         } else {
628             return "error, no uploaded file";
629         }
630     }
631
632     /**
633      * Remove a specified J2EE module
634      * @param fileName Name of file to remove
635      * @return true if file has been removed
636      * @throws Exception if remove fails
637      */

638     public Boolean JavaDoc removeModuleFile(String JavaDoc fileName) throws Exception JavaDoc {
639         // Get directory where to search given file
640
String JavaDoc dir = getFolderDir(fileName);
641
642         File JavaDoc searchedFile = new File JavaDoc(dir, fileName);
643         if (searchedFile.exists()) {
644             return Boolean.valueOf(searchedFile.delete());
645         } else {
646             throw new Exception JavaDoc("File '" + searchedFile + "' was not found on the JOnAS server. Cannot remove it");
647         }
648
649     }
650
651
652     /**
653      * Get directory based on a filename
654      * @param fileName name of the file
655      * @return folder of type JONAS_BASE/XXXX/
656      * @throws Exception if file is not a J2EE archive
657      */

658     private String JavaDoc getFolderDir(String JavaDoc fileName) throws Exception JavaDoc {
659         String JavaDoc jBase = JProp.getJonasBase();
660         // based on extension
661
String JavaDoc dir = null;
662         // EJB
663
if (fileName.toLowerCase().endsWith(".jar")) {
664             dir = jBase + File.separator + "ejbjars";
665         } else if (fileName.toLowerCase().endsWith(".war")) {
666             // War file
667
dir = jBase + File.separator + "webapps";
668         } else if (fileName.toLowerCase().endsWith(".ear")) {
669             // ear file
670
dir = jBase + File.separator + "apps";
671         } else if (fileName.toLowerCase().endsWith(".rar")) {
672             // rar file
673
dir = jBase + File.separator + "rars";
674         } else {
675             // invalid type
676
throw new Exception JavaDoc("Invalid extension for the file '" + fileName
677                     + "'. Valid are .jar, .war, .ear, .rar");
678         }
679         return dir;
680     }
681
682 }
Popular Tags