KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jahia > services > webapps_deployer > JahiaTomcatWebAppsDeployerBaseService


1 //
2
// ____.
3
// __/\ ______| |__/\. _______
4
// __ .____| | \ | +----+ \
5
// _______| /--| | | - \ _ | : - \_________
6
// \\______: :---| : : | : | \________>
7
// |__\---\_____________:______: :____|____:_____\
8
// /_____|
9
//
10
// . . . i n j a h i a w e t r u s t . . .
11
//
12
//
13
//
14
// JahiaTomcatWebAppsDeployerBaseService
15
//
16
// NK 12.01.2001
17
//
18
//
19

20
21 package org.jahia.services.webapps_deployer;
22
23
24 import org.jahia.data.applications.ApplicationBean;
25 import org.jahia.data.constants.JahiaConstants;
26 import org.jahia.data.webapps.JahiaEarFileHandler;
27 import org.jahia.data.webapps.JahiaWebAppsPackage;
28 import org.jahia.data.webapps.JahiaWebAppsWarHandler;
29 import org.jahia.data.webapps.Web_Component;
30 import org.jahia.exceptions.JahiaException;
31 import org.jahia.exceptions.JahiaInitializationException;
32 import org.jahia.services.sites.JahiaSite;
33 import org.jahia.services.webapps_deployer.tomcat.TomcatWebAppsDeployer;
34 import org.jahia.services.webapps_deployer.tomcat.Tomcat_Users_Xml;
35 import org.jahia.settings.SettingsBean;
36 import org.jahia.utils.JahiaTools;
37 import org.jahia.utils.keygenerator.JahiaKeyGen;
38
39 import java.io.File JavaDoc;
40 import java.util.Vector JavaDoc;
41
42 /**
43  * This Service Register new Application Definition,
44  * deploy webApps packaged in a .war or .ear file.
45  *
46  * @author Khue ng
47  * @version 1.0
48  */

49 public class JahiaTomcatWebAppsDeployerBaseService extends JahiaWebAppsDeployerService {
50
51     private static org.apache.log4j.Logger logger =
52             org.apache.log4j.Logger.getLogger (JahiaTomcatWebAppsDeployerBaseService.class);
53
54     private static final String JavaDoc CLASS_NAME = JahiaWebAppsDeployerService.class.getName ();
55
56     private static JahiaTomcatWebAppsDeployerBaseService m_Instance = null;
57
58
59     /** The tomcat tomcat-users.xml file * */
60     private String JavaDoc m_TomcatUsersXmlFilePath;
61
62     /** The Tomcat User needed to use Tomcat Management Application API **/
63
64     /** The Tomcat user name * */
65     private static String JavaDoc m_TomcatUserName = "Jahia";
66
67     /** The Tomcat user password * */
68     private static String JavaDoc m_TomcatUserPassword = "";
69
70     /** The Tomcat user roles * */
71     private static String JavaDoc m_TomcatUserRoles = "manager";
72
73     /** the HostHttpPath needed to call Tomcat Manager Servlet Application servlet * */
74     private static String JavaDoc m_JahiaWebAppsDeployerBaseURL = "";
75
76     /** Tomcat initialization error * */
77     private boolean m_TomcatInitErr = false;
78
79
80     /**
81      * Constructor
82      */

83     protected JahiaTomcatWebAppsDeployerBaseService () {
84
85         logger.debug ("Starting the Jahia Tomcat WebApps Deployer Base Service");
86
87     }
88
89
90     /**
91      * Use this method to get an instance of this class
92      */

93     public static synchronized JahiaTomcatWebAppsDeployerBaseService getInstance () {
94
95         if (m_Instance == null) {
96             m_Instance = new JahiaTomcatWebAppsDeployerBaseService ();
97         }
98         return m_Instance;
99     }
100
101
102     //-------------------------------------------------------------------------
103
/**
104      * Initialize with Tomcat configuration and disk paths
105      *
106      * @param JahiaPrivateSettings jSettings
107      */

108     public void init (SettingsBean jSettings)
109             throws JahiaInitializationException {
110
111         if (!isInitialized ()) {
112
113             super.init (jSettings);
114
115             m_JahiaWebAppsDeployerBaseURL = jSettings.getJahiaWebAppsDeployerBaseURL ();
116
117             // add a user with the manager role to tomcat-users.xml
118
//System.out.println(" m_ServerHomeDiskPath is " + m_ServerHomeDiskPath );
119
m_TomcatUsersXmlFilePath =
120                     m_ServerHomeDiskPath + "conf" + File.separator + "tomcat-users.xml";
121
122             File JavaDoc tomcatUsersXmlFile = new File JavaDoc (m_TomcatUsersXmlFilePath);
123             if (tomcatUsersXmlFile == null || !tomcatUsersXmlFile.isFile ()
124                     || !tomcatUsersXmlFile.canWrite ()) {
125                 logger.debug (
126                         "WARNING: " + tomcatUsersXmlFile.getAbsolutePath () + " file cannot be accessed or doesn't exist, application deployment might not work! ");
127                 //throw new JahiaInitializationException ( errMsg );
128
m_TomcatInitErr = true;
129             } else {
130
131                 if (!addManagerUser (m_TomcatUsersXmlFilePath)) {
132                     logger.debug (
133                             "WARNING: cannot create the tomcat manager user for web apps, application deployment might not work");
134                     m_TomcatInitErr = true;
135
136                 }
137             }
138
139             mIsServiceInitialized = true;
140         }
141
142     } // end init
143

144
145     //-------------------------------------------------------------------------
146
/**
147      * Hot Deploy a .ear or .war file.
148      * Hot Deploy a web component on the specifiy server, active them to
149      * be immediately accessible in Jahia
150      * If it's a .ear file, the context is the application context
151      * If it's a .war file, the context is the web application context
152      *
153      * @param (JahiaSite) the site
154      * @param (String) context , the context
155      * @param (String) filePath , the full path to the ear file
156      *
157      * @return (boolean) true if successfull
158      */

159     public boolean deploy (JahiaSite site, String JavaDoc context, String JavaDoc filePath)
160             throws JahiaException {
161
162         if (!canDeploy ()) {
163             return false;
164         }
165
166         boolean success = false;
167         if (filePath.endsWith (".ear")) {
168             success = handleEarFile (site, filePath);
169         } else if (filePath.endsWith (".war")) {
170             success = deployWarFile (site, context, filePath);
171         } else {
172             File JavaDoc tmpFile = new File JavaDoc (filePath);
173             if (tmpFile != null && tmpFile.isDirectory ()) {
174                 success = deployDirectory (site, context, filePath);
175             }
176         }
177
178         if (success) {
179             deletePackage (site, filePath);
180             return true;
181         } else {
182             return false;
183         }
184     }
185
186
187     //-------------------------------------------------------------------------
188
/**
189      * Undeploy a web application. Delete the web component from disk.
190      *
191      * @param (ApplicationBean) the application bean object
192      *
193      * @return (boolean) true if successfull
194      */

195
196     public boolean undeploy (ApplicationBean app) throws JahiaException {
197
198         if (!canDeploy ()) {
199             return false;
200         }
201
202         if (app != null) {
203
204             // call tomcat undeploy url
205
undeployWebApp (app.getContext ());
206
207             // try to delete physically the directory on disk
208
JahiaTools.deleteFile (new File JavaDoc (m_WebAppRootPath + app.getContext ()));
209
210
211             // delete the jsp cache folder
212
/*
213             StringBuffer path = new StringBuffer( System.getProperties().getProperty("user.dir") );
214             path.append(File.separator);
215             path.append("work");
216             path.append(File.separator);
217             path.append("localhost");
218             path.append(app.getContext());
219
220             JahiaTools.deleteFile( new File( path.toString()) );
221             */

222
223             return true;
224         }
225
226         return false;
227     }
228
229
230     //-------------------------------------------------------------------------
231
/**
232      * Deploy a single .war web component file
233      *
234      * @param (JahiaSite) the site
235      * @param (String) webContext , the web context
236      * @param (String) filePath , the full path to the war file
237      */

238     protected boolean deployWarFile (JahiaSite site, String JavaDoc webContext, String JavaDoc filePath)
239             throws JahiaException {
240
241         Vector JavaDoc webApps = new Vector JavaDoc ();
242         StringBuffer JavaDoc webContextDiskPath = new StringBuffer JavaDoc (m_WebAppRootPath);
243         webContextDiskPath.append (File.separator);
244         webContextDiskPath.append (webContext);
245         webContextDiskPath.append ("_");
246         webContextDiskPath.append (site.getSiteKey ());
247
248         //StringBuffer webContextBuff = new StringBuffer(site.getSiteKey());
249
StringBuffer JavaDoc webContextBuff = new StringBuffer JavaDoc (webContext);
250         webContextBuff.append ("_");
251         webContextBuff.append (site.getSiteKey ());
252
253         webApps = handleWarFile (webContextDiskPath.toString (), filePath);
254
255         // Activate the Web App in Tomcat
256
activateWebApp (webContextBuff.toString (), webContextDiskPath.toString ());
257
258         // register Web Apps in Jahia
259
File JavaDoc f = new File JavaDoc (filePath);
260         registerWebApps (site, webContextBuff.toString (), f.getName (), webApps);
261
262         // move the war to the context
263
File JavaDoc warFile = new File JavaDoc (filePath);
264         warFile.delete ();
265
266         /*
267         webContextDiskPath.append(File.separator);
268         webContextDiskPath.append(warFile.getName());
269
270         File newPos = new File(webContextDiskPath.toString()+File.separator+m_WEB_INF);
271         if ( !warFile.renameTo(newPos) ){
272             warFile.delete();
273         }
274         */

275
276         return true;
277
278     }
279
280
281     //-------------------------------------------------------------------------
282
/**
283      * Deploy an unziped directory
284      *
285      * @param (JahiaSite) the site
286      * @param (String) webContext , the web context
287      * @param (String) filePath , the full path to the war file
288      */

289     protected synchronized boolean deployDirectory (JahiaSite site, String JavaDoc webContext,
290                                                     String JavaDoc filePath) throws JahiaException {
291
292         String JavaDoc webContextDiskPath = m_WebAppRootPath + webContext;
293         File JavaDoc tmpFile = new File JavaDoc (webContextDiskPath);
294         File JavaDoc curFile = new File JavaDoc (filePath);
295         boolean sameDir = false;
296
297         sameDir = tmpFile.equals (curFile);
298
299         //System.out.println(" to deploy webContext =" + webContext + ", path=" + filePath);
300
//System.out.println(" deploy Directory webContextDiskPath =" + webContextDiskPath );
301

302
303
304         if (sameDir || !tmpFile.isDirectory ()) {
305
306             JahiaWebAppsPackage aPackage = loadWebAppInfoFromDirectory (filePath);
307             if (aPackage != null && (aPackage.getWebApps ().size () > 0)) {
308
309                 File JavaDoc dir = new File JavaDoc (filePath);
310
311                 if (!sameDir) {
312
313                     if (dir != null && dir.renameTo (tmpFile)) {
314                         return false;
315                     }
316                 }
317
318                 // Activate the Web App in Tomcat
319
activateWebApp (webContext, webContextDiskPath);
320
321                 // register Web Apps in Jahia
322
registerWebApps (site, webContext, "", aPackage.getWebApps ());
323
324                 return true;
325             }
326         }
327
328         return false;
329
330     }
331
332
333     //-------------------------------------------------------------------------
334
/**
335      * A simple way to pass a vector of .ear of war files
336      * to be deployed
337      *
338      * @param (JahiaSite) the site
339      * @param (Vector) files, a vector of .ear or .war files
340      *
341      * @return (boolean) true if done correctly
342      */

343     public boolean deploy (JahiaSite site, Vector JavaDoc files) {
344
345
346         synchronized (files) {
347
348             int size = files.size ();
349             File JavaDoc fileItem = null;
350
351             for (int i = 0; i < size; i++) {
352
353                 fileItem = (File JavaDoc) files.get (i);
354
355                 if (fileItem != null && fileItem.isFile ()) {
356                     logger.debug ("Found new application to deploy : " + fileItem.getName ());
357                     try {
358
359                         JahiaWebAppsPackage pack = null;
360                         if (site.getWebAppsAutoDeployMode () && canDeploy ()) {
361                             if (fileItem.getName ().endsWith (".ear") || fileItem.getName ()
362                                     .endsWith (".war")) {
363                                 pack = loadWebAppInfo (fileItem.getAbsolutePath ());
364                                 if (pack != null) {
365                                     if (!deploy (site, pack.getContextRoot (),
366                                             fileItem.getAbsolutePath ())) {
367                                         fileItem.delete ();
368                                         return false;
369                                     }
370                                 } else {
371                                     try {
372                                         File JavaDoc newFile = new File JavaDoc (
373                                                 fileItem.getAbsolutePath () + "_error");
374                                         //newFile.createNewFile();
375
fileItem.renameTo (newFile);
376                                     } catch (Throwable JavaDoc t) {
377                                         logger.error (
378                                                 "Error renaming error file " +
379                                                 fileItem.toString () + " to " +
380                                                 fileItem.getAbsolutePath () + "_error",
381                                                 t);
382                                     }
383                                 }
384                             }
385                         } else {
386                             if (!site.getWebAppsAutoDeployMode ()) {
387                                 logger.warn (
388                                         "Site automatic web application deployment is deactivated. Rescheduling for later in case setting changes.");
389                             }
390                             addNewFile (site, fileItem.getAbsolutePath ());
391                         }
392
393                     } catch (JahiaException e) {
394                         String JavaDoc errMsg = "Failed deploying Application file " + fileItem.getName ();
395                         logger.error (errMsg, e);
396                         fileItem.delete ();
397                     }
398                 }
399             }
400         }
401         return true;
402     }
403
404
405     //-------------------------------------------------------------------------
406
/**
407      * Handle Ear application File Deployment
408      *
409      * @param (JahiaSite) the site
410      * @param (String) filePath , the full path to the ear file
411      *
412      * @return (boolean) true if success full
413      */

414     protected boolean handleEarFile (JahiaSite site, String JavaDoc filePath) throws JahiaException {
415
416         //logger.info("started");
417

418         // Create a Ear Handler
419
JahiaEarFileHandler earh = null;
420
421         try {
422
423             earh = new JahiaEarFileHandler (filePath);
424
425             // Get WebComponents ( list of war files )
426
Vector JavaDoc webComponents = earh.getWebComponents ();
427             int size = webComponents.size ();
428
429             if (size <= 0) {
430                 return false;
431             }
432
433             // Deploy web components ( war files )
434
Web_Component webComp = null;
435             String JavaDoc webURI = null; // name of the war file
436

437             for (int i = 0; i < size; i++) {
438
439                 webComp = (Web_Component) webComponents.get (i);
440
441                 webURI = webComp.getWebURI ();
442
443
444                 if (webURI != null && (webURI.length () > 0)) {
445
446                     //logger.debug("start extracting entry " + webURI);
447

448                     // extract the war file
449
earh.extractEntry (webURI, m_TempFolderDiskPath);
450
451                     // get the extracted war file
452
File JavaDoc warFile = new File JavaDoc (m_TempFolderDiskPath + File.separator + webURI);
453
454                     String JavaDoc deployContext = webComp.getContextRoot();
455                     if (deployContext == null) {
456                         deployContext = JahiaTools.removeFileExtension (warFile.getName (), ".war");
457                     } else {
458                         if (deployContext.startsWith("/")) {
459                             deployContext = deployContext.substring(1);
460                         }
461                     }
462
463                     if (!deployWarFile (site,
464                             deployContext,
465                             warFile.getAbsolutePath ())) {
466                         return false;
467                     }
468
469                 }
470
471             }
472
473
474         } catch (JahiaException e) {
475
476             String JavaDoc errMsg = "Failed handling webApps file ";
477             logger.error (errMsg + "\n" + e.toString (), e);
478             throw new JahiaException ("JahiaTomcatWebAppsDeployerBaseService::deployEarFile()",
479                     "JahiaTomcatWebAppsDeployerBaseService" + errMsg,
480                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
481
482         } finally {
483
484             // Important to close the JarFile object !!!!
485
// cannot delete it otherwise
486
if (earh != null) {
487                 earh.closeArchiveFile ();
488             }
489         }
490
491         return true;
492     }
493
494
495
496     //-------------------------------------------------------------------------
497
/**
498      * extract Web Component file in the web app context and
499      * return the list of Web App Definition objects
500      *
501      * @param (String) webAppContext , the full path to the Web App Context Root
502      * @param (String) filePath , the full path to the war file
503      *
504      * @return (Vector) the list of Web App Definitions
505      */

506     protected Vector JavaDoc handleWarFile (String JavaDoc webAppContext, String JavaDoc filePath)
507             throws JahiaException {
508
509         // Create a WebApp War Handler
510
JahiaWebAppsWarHandler wah = null;
511
512         Vector JavaDoc webApps = new Vector JavaDoc ();
513
514         try {
515
516             wah = new JahiaWebAppsWarHandler (filePath);
517
518             webApps = wah.getWebAppsPackage ().getWebApps ();
519             int size = webApps.size ();
520
521             if (size > 0) {
522
523                 // create the dir
524
File JavaDoc f = new File JavaDoc (webAppContext);
525                 if (!f.isDirectory () && !f.mkdirs ()) {
526
527                     String JavaDoc errMsg = "Failed creating the war context root dir " + f.getAbsolutePath ();
528                     logger.error (errMsg + "\n");
529                     throw new JahiaException (
530                             "JahiaTomcatWebAppsDeployerBaseService::deployWarFile()",
531                             "JahiaTomcatWebAppsDeployerBaseService" + errMsg,
532                             JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY);
533                 }
534
535                 // Remove the Meta-Inf folder
536
removeMetaInfFolder (f.getAbsolutePath ());
537
538                 // extract the war file in the Web App Context Root
539
wah.unzip (webAppContext);
540
541
542             }
543
544         } catch (JahiaException e) {
545
546             String JavaDoc errMsg = "Failed handling webApps file ";
547             logger.error (errMsg + "\n" + e.toString (), e);
548             throw new JahiaException ("JahiaTomcatWebAppsDeployerBaseService::deployWarFile()",
549                     "JahiaTomcatWebAppsDeployerBaseService" + errMsg,
550                     JahiaException.SERVICE_ERROR, JahiaException.ERROR_SEVERITY, e);
551
552         } finally {
553
554             // Important to close the JarFile object !!!!
555
// cannot delete it otherwise
556
if (wah != null) {
557                 wah.closeArchiveFile ();
558             }
559         }
560
561         return webApps;
562     }
563
564
565
566     //-------------------------------------------------------------------------
567
/**
568      * Active Web Application in Tomcat
569      *
570      * @param (String) webContext , The Context for the webApps
571      * @param (String) webAppDiskPath , The absolute disk path to the unpacked web app
572      * @param (boolean) return true if success full
573      */

574     protected boolean activateWebApp (
575             String JavaDoc context,
576             String JavaDoc webAppDiskPath
577             ) throws JahiaException {
578
579         TomcatWebAppsDeployer deployer = new TomcatWebAppsDeployer (
580                 m_ServerType,
581                 m_JahiaWebAppsDeployerBaseURL,
582                 m_TomcatUserName,
583                 m_TomcatUserPassword
584         );
585         File JavaDoc tmpFile = new File JavaDoc (webAppDiskPath);
586         String JavaDoc fileUrl = null;
587         try {
588             fileUrl = tmpFile.toURL ().toString ();
589         } catch (java.net.MalformedURLException JavaDoc ue) {
590             logger.debug (
591                     "Error while activating app with context=" + context + " and webAppDiskPath=" + webAppDiskPath,
592                     ue);
593             return false;
594         }
595
596         return deployer.deploy ("/" + context, fileUrl);
597
598     }
599
600
601     //-------------------------------------------------------------------------
602
/**
603      * Undeploy a Web Application in Tomcat
604      *
605      * @param (String) webContext , The Context for the webApps
606      * @param (boolean) return true if success full
607      */

608     protected boolean undeployWebApp (String JavaDoc context
609                                       ) throws JahiaException {
610
611         TomcatWebAppsDeployer deployer = new TomcatWebAppsDeployer (
612                 m_ServerType,
613                 m_JahiaWebAppsDeployerBaseURL,
614                 m_TomcatUserName,
615                 m_TomcatUserPassword
616         );
617         /*
618         boolean doStop = ( m_ServerType.endsWith(JahiaConstants.SERVER_TOMCAT4_BETA2)
619                                 || m_ServerType.endsWith(JahiaConstants.SERVER_TOMCAT4_BETA3)
620                                 || m_ServerType.endsWith(JahiaConstants.SERVER_TOMCAT4_BETA6) );
621         */

622         boolean doStop = (!m_ServerType.endsWith (JahiaConstants.SERVER_TOMCAT4_BETA1));
623
624         if (context.startsWith ("/")) {
625             if (doStop) {
626                 deployer.stop (context);
627             }
628             return deployer.undeploy (context);
629         } else {
630             if (doStop) {
631                 deployer.stop ("/" + context);
632             }
633             return deployer.undeploy ("/" + context);
634         }
635
636     }
637
638
639     //-------------------------------------------------------------------------
640
/**
641      * Create the web context
642      *
643      * @param (String) webContext , the web context
644      *
645      * @return (String) webContextPath, the full web context path
646      */

647     protected String JavaDoc createWebContext (String JavaDoc webContext) {
648
649         StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc (1024);
650         strBuf.append (m_WebAppRootPath);
651         strBuf.append (webContext);
652
653         // full path to the application context root folder
654
String JavaDoc webContextPath = strBuf.toString ();
655
656         File JavaDoc f = new File JavaDoc (webContextPath);
657
658         if (!f.isDirectory () && !f.mkdirs ()) {
659
660             return null;
661         }
662
663         return webContextPath;
664     }
665
666
667     //-------------------------------------------------------------------------
668
/**
669      * Add a User with the manager role to tomcat-users.xml
670      *
671      * @param (String) the full path to the tomcat-usesr.xml file
672      *
673      * @return (boolean) true if successfull
674      */

675     protected boolean addManagerUser (String JavaDoc docPath) {
676
677
678         try {
679
680             String JavaDoc password = null;
681             m_TomcatUserPassword = JahiaKeyGen.getKey (15);
682             Tomcat_Users_Xml doc = new Tomcat_Users_Xml (docPath);
683
684             password = doc.getUserPassword (m_TomcatUserName, m_TomcatUserRoles);
685             if (password == null) {
686                 doc.addUser (m_TomcatUserName, m_TomcatUserPassword, m_TomcatUserRoles);
687                 doc.write ();
688             } else if (password.equals ("")) {
689                 doc.updateUser (m_TomcatUserName, m_TomcatUserPassword, m_TomcatUserRoles);
690                 doc.write ();
691             } else {
692                 m_TomcatUserPassword = password;
693             }
694         } catch (JahiaException e) {
695             logger.debug ("Exception while modifying Tomcat user file", e);
696             return false;
697         }
698         return true;
699     }
700
701
702
703     //-------------------------------------------------------------------------
704
/**
705      * Return true if the tomcat-users.xml has been correctly loaded.
706      * If not, deployment functionality are not available and always return false
707      *
708      * @return (boolean) true if successfull
709      */

710     public boolean canDeploy () {
711         if (m_TomcatInitErr) {
712             logger.debug (
713                     "Cannot deploy application because of failure of the initialization of the deployment service. Check your logs for warnings or errors.");
714         }
715
716         return (!m_TomcatInitErr);
717
718     }
719
720
721 } // end JahiaTomcatWebAppsDeployerService
722
Popular Tags