KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > petals > jbi > management > autoload > AutoLoaderImpl


1 /**
2  * PETALS: PETALS Services Platform
3  * Copyright (C) 2005 EBM WebSourcing
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
18  * USA.
19  *
20  * Initial developer(s): EBM WebSourcing
21  * --------------------------------------------------------------------------
22  * $Id: AutoLoaderImpl.java,v 1.2 2006/04/07 10:24:27 alouis Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 package org.objectweb.petals.jbi.management.autoload;
27
28 import java.io.File JavaDoc;
29 import java.io.FileNotFoundException JavaDoc;
30 import java.io.IOException JavaDoc;
31 import java.io.PrintWriter JavaDoc;
32 import java.net.URI JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Timer JavaDoc;
36
37 import javax.management.MBeanServer JavaDoc;
38 import javax.management.ObjectName JavaDoc;
39
40 import org.apache.commons.io.FileUtils;
41 import org.objectweb.fractal.fraclet.annotation.FractalComponent;
42 import org.objectweb.fractal.fraclet.annotation.Interface;
43 import org.objectweb.fractal.fraclet.annotation.LifeCycle;
44 import org.objectweb.fractal.fraclet.annotation.LifeCycleType;
45 import org.objectweb.fractal.fraclet.annotation.Monolog;
46 import org.objectweb.fractal.fraclet.annotation.Provides;
47 import org.objectweb.fractal.fraclet.annotation.Requires;
48 import org.objectweb.petals.jbi.management.deployment.DeploymentService;
49 import org.objectweb.petals.jbi.management.service.InstallationService;
50 import org.objectweb.petals.jbi.management.service.LifeCycleManagerService;
51 import org.objectweb.petals.jbi.management.service.PackageHandler;
52 import org.objectweb.petals.jbi.management.service.util.XMLResult;
53 import org.objectweb.petals.jbi.management.systemstate.ComponentState;
54 import org.objectweb.petals.jbi.management.systemstate.ServiceAssemblyState;
55 import org.objectweb.petals.jbi.management.systemstate.SharedLibraryState;
56 import org.objectweb.petals.jbi.management.systemstate.SystemState;
57 import org.objectweb.petals.repository.RepositoryService;
58 import org.objectweb.petals.tools.jbicommon.descriptor.JBIDescriptor;
59 import org.objectweb.petals.util.LoggingUtil;
60 import org.objectweb.petals.util.SystemUtil;
61 import org.objectweb.util.monolog.api.Logger;
62
63 /**
64  * This class is used for automaticly loading components which are placed in the
65  * "autoLoad" directory. It periodicly scan the directory and check if new
66  * components are presents. The InstallationService is called for each of those
67  * components. The whole process of installation is done (install + start) After
68  * being threat, the archives of the components are removed. A file
69  * "fileName.success" will be created if success A file "fileName.failed" will
70  * be created otherwise, containing the related exception
71  *
72  * @author alouis
73  *
74  */

75 @FractalComponent
76 @Provides(interfaces=@Interface(name="service",signature=org.objectweb.petals.jbi.management.autoload.AutoLoader.class))
77 public class AutoLoaderImpl implements AutoLoader {
78
79     private static String JavaDoc install = "install";
80
81     protected static File JavaDoc installDirectory;
82
83     private static String JavaDoc installed = "installed";
84
85     protected static File JavaDoc installedDirectory;
86
87     private static String JavaDoc uninstalled = "uninstalled";
88
89     protected static File JavaDoc uninstalledDirectory;
90
91     private static String JavaDoc work = "work";
92
93     protected static File JavaDoc workDirectory;
94
95     @Requires(name="deployment",signature=org.objectweb.petals.jbi.management.deployment.DeploymentService.class)
96     protected DeploymentService deploymentService;
97
98     @Requires(name="installation",signature=org.objectweb.petals.jbi.management.service.InstallationService.class)
99     protected InstallationService installationService;
100
101     protected Timer JavaDoc installDirectoryScanTimer;
102
103     protected Timer JavaDoc installedDirectoryScanTimer;
104
105     protected LoggingUtil log;
106
107     @Monolog(name="logger")
108     protected Logger logger;
109
110     @Requires(name="lifecyclemanager",signature=org.objectweb.petals.jbi.management.service.LifeCycleManagerService.class)
111     protected LifeCycleManagerService managerService;
112
113     /**
114      * Package Handler
115      */

116     protected PackageHandler packageHandler;
117
118     /**
119      * JBI Container :: Recovery Service
120      */

121     @Requires(name="systemstate",signature=org.objectweb.petals.jbi.management.systemstate.SystemState.class)
122     protected SystemState recoverySrv;
123
124     /**
125      * Platform Component :: Repository Service
126      */

127     protected RepositoryService repositorySrv;
128
129     private long scanPeriod = 4000L;
130
131     public static File JavaDoc getInstallDirectory() {
132         return installDirectory;
133     }
134
135     public static File JavaDoc getInstalledDirectory() {
136         return installedDirectory;
137     }
138
139     public static File JavaDoc getUninstalledDirectory() {
140         return uninstalledDirectory;
141     }
142
143     public static File JavaDoc getWorkDirectory() {
144         return workDirectory;
145     }
146
147     /**
148      * init the autoloader : init the directories
149      */

150     @LifeCycle(on=LifeCycleType.START)
151     public void start() throws IOException JavaDoc {
152         log = new LoggingUtil(logger);
153         log.call();
154         installDirectory = new File JavaDoc(SystemUtil.getPetalsInstallDirectory()
155                 .getAbsolutePath()
156                 + File.separator + install);
157         installedDirectory = new File JavaDoc(SystemUtil.getPetalsInstallDirectory()
158                 .getAbsolutePath()
159                 + File.separator + installed);
160         uninstalledDirectory = new File JavaDoc(SystemUtil.getPetalsInstallDirectory()
161                 .getAbsolutePath()
162                 + File.separator + uninstalled);
163         workDirectory = new File JavaDoc(SystemUtil.getPetalsInstallDirectory()
164                 .getAbsolutePath()
165                 + File.separator + work);
166
167         checkValidiyOfdirectory(installDirectory, false);
168         checkValidiyOfdirectory(installedDirectory, false);
169         checkValidiyOfdirectory(uninstalledDirectory, false);
170         checkValidiyOfdirectory(workDirectory, true);
171         
172         //old start method
173
installDirectoryScanTimer = new Timer JavaDoc();
174         installedDirectoryScanTimer = new Timer JavaDoc();
175         InstallDirectoryScanner installScan = new InstallDirectoryScanner(this,
176                 installDirectory);
177         InstalledDirectoryScanner installedScan = new InstalledDirectoryScanner(
178                 this, installedDirectory);
179         /*
180          * Initialize package handler
181          */

182         packageHandler = new PackageHandler(logger, repositorySrv);
183
184         installDirectoryScanTimer.schedule(installScan, scanPeriod, scanPeriod);
185         installedDirectoryScanTimer.schedule(installedScan, scanPeriod,
186                 scanPeriod);
187     }
188
189     /**
190      * Stop the autoload of the components. TODO : synchronization, does the
191      * autoload must wait before the end of an installation before closing?
192      */

193     @LifeCycle(on=LifeCycleType.STOP)
194     public void stop() {
195         log.call();
196
197         if (installDirectoryScanTimer != null) {
198             installDirectoryScanTimer.cancel();
199         }
200         if (installedDirectoryScanTimer != null) {
201             installedDirectoryScanTimer.cancel();
202         }
203     }
204
205     /**
206      * friendly method for the directoryscanner
207      *
208      * @param newInstallers
209      */

210     protected void install(File JavaDoc[] newInstallers) {
211         log.call();
212
213         if (newInstallers != null) {
214             for (int i = 0; i < newInstallers.length; i++) {
215                 File JavaDoc file = newInstallers[i];
216                 try {
217                     /*
218                      * Copy archive file to work dir
219                      */

220                     File JavaDoc workArchive = new File JavaDoc(getWorkDirectory(), file
221                             .getName());
222                     FileUtils.copyFile(file, workArchive);
223                     FileUtils.forceDelete(file);
224
225                     /*
226                      * Load JBI descriptor here
227                      */

228
229                     JBIDescriptor descriptor = packageHandler
230                             .loadDescriptor(workArchive.toURI());
231
232                     /*
233                      * Perform the right task : install, share or deploy
234                      */

235                     if (descriptor.getComponent() != null) {
236                         performInstall(workArchive);
237                     } else if (descriptor.getSharedLibrary() != null) {
238                         performShare(workArchive);
239                     } else if (descriptor.getServiceAssembly() != null) {
240                         performDeploy(workArchive);
241                     } else {
242                         throw new Exception JavaDoc("auto recover of entity failed : "
243                                 + workArchive.getCanonicalPath());
244                     }
245                     FileUtils.forceDelete(workArchive);
246
247                 } catch (Throwable JavaDoc e) {
248                     log.error("Error during install", e);
249                 }
250             }
251         }
252     }
253
254     /**
255      * friendly method for the directoryscanner
256      *
257      * @param newInstallers
258      */

259     protected void uninstall(List JavaDoc<File JavaDoc> filesToUninstall) {
260         log.call();
261         /*
262          * Retrieve all installed entities
263          */

264         List JavaDoc<ComponentState> compStates = recoverySrv
265                 .retrieveAllComponentStates();
266         List JavaDoc<SharedLibraryState> slStates = recoverySrv
267                 .retrieveAllSharedLibraryStates();
268         List JavaDoc<ServiceAssemblyState> saStates = recoverySrv
269                 .retrieveAllServiceAssemblyStates();
270
271         /*
272          * Check if one of the files to uninstall match one of the archiveUrl of
273          * the installed entities. If yes, this entity must be uninstalled.
274          */

275         List JavaDoc<String JavaDoc> compToUninstall = new ArrayList JavaDoc<String JavaDoc>();
276         List JavaDoc<String JavaDoc> slToUninstall = new ArrayList JavaDoc<String JavaDoc>();
277         List JavaDoc<String JavaDoc> saToUninstall = new ArrayList JavaDoc<String JavaDoc>();
278         for (ComponentState state : compStates) {
279             URI JavaDoc archiveURI = packageHandler.processAndGetPackageURI(state
280                     .getArchiveURL(), false);
281             File JavaDoc archiveFile = new File JavaDoc(archiveURI);
282             for (File JavaDoc file : filesToUninstall) {
283                 if (file.equals(archiveFile)) {
284                     compToUninstall.add(state.getName());
285                 }
286             }
287         }
288         for (SharedLibraryState state : slStates) {
289             URI JavaDoc archiveURI = packageHandler.processAndGetPackageURI(state
290                     .getArchiveURL(), false);
291             File JavaDoc archiveFile = new File JavaDoc(archiveURI);
292             for (File JavaDoc file : filesToUninstall) {
293                 if (file.equals(archiveFile)) {
294                     slToUninstall.add(state.getName());
295                 }
296             }
297         }
298         for (ServiceAssemblyState state : saStates) {
299             URI JavaDoc archiveURI = packageHandler.processAndGetPackageURI(state
300                     .getArchiveURL(), false);
301             File JavaDoc archiveFile = new File JavaDoc(archiveURI);
302             for (File JavaDoc file : filesToUninstall) {
303                 if (file.equals(archiveFile)) {
304                     saToUninstall.add(state.getName());
305                 }
306             }
307         }
308
309         /*
310          * Perform entity uninstallation
311          */

312         for (String JavaDoc name : saToUninstall) {
313             performSAUninstall(name);
314         }
315         for (String JavaDoc name : compToUninstall) {
316             performCompUninstall(name);
317         }
318         for (String JavaDoc name : slToUninstall) {
319             performSLUninstall(name);
320         }
321
322     }
323
324     // ----------------------------------------------------------------------
325
// Fractal BindingController implementation
326
// ----------------------------------------------------------------------
327

328     /**
329      * Check if the specified File is a directory and is created. If it does not
330      * exist, create it.
331      *
332      * @param dir
333      * @param clean
334      * delete directory content or not
335      */

336     private void checkValidiyOfdirectory(File JavaDoc dir, boolean clean)
337         throws IOException JavaDoc {
338         if (dir != null) {
339             // parameter is not null
340
if (!dir.exists()) {
341                 // directory does not exist, create it
342
if (!dir.mkdirs()) {
343                     // creation failed
344
throw new IOException JavaDoc(
345                             "can not create the following directory : "
346                                     + dir.getCanonicalPath());
347                 }
348             } else {
349                 // file already exist, check it is a directory
350
if (!dir.isDirectory()) {
351                     // file is not a directory
352
throw new IOException JavaDoc(dir.getCanonicalPath()
353                             + " already exists and is not a directory.");
354                 } else {
355                     // clean the directory
356
if (clean) {
357                         FileUtils.deleteDirectory(dir);
358                         dir.mkdirs();
359                     }
360                 }
361             }
362         } else {
363             throw new FileNotFoundException JavaDoc("the specified directory is null");
364         }
365     }
366
367     /**
368      * Uninstall the specified component.
369      *
370      * @param name
371      */

372     protected void performCompUninstall(String JavaDoc name) {
373         installationService.unloadInstaller(name, true);
374     }
375
376     /**
377      * Deploy the specified Archive in the JBI container and start it . Any
378      * exception will cause the abortion of the process. A file
379      * "fileName.success" will be created if success A file "fileName.failed"
380      * will be created otherwise, containing the related exception
381      *
382      * @param f
383      */

384     private void performDeploy(File JavaDoc f) {
385         log.call();
386
387         if (f != null && f.exists()) {
388
389             try {
390
391                 // TODO Find a better way of managing URI
392
// String absPath = f.getAbsolutePath().replaceAll(" ", "%20");
393
// String archiveURI;
394
// if (absPath.startsWith("/")) {
395
// archiveURI = "file://" + absPath;
396
// } else {
397
// archiveURI = "file:///" + absPath;
398
// }
399

400                 String JavaDoc xml = deploymentService.deploy(f.toURI().toString());
401
402                 if (xml.indexOf(XMLResult.TaskResult.FAILED.toString()) > -1) {
403                     log.warning("Problem while deploying a service assembly\n"
404                             + xml);
405                 } else {
406                     String JavaDoc saName = "";
407                     saName = xml.substring(xml.indexOf("<loc-param>") + 11, xml
408                             .indexOf("</loc-param>"));
409                     deploymentService.start(saName);
410
411                 }
412             } catch (Throwable JavaDoc e) {
413                 try {
414                     File JavaDoc failed = new File JavaDoc(workDirectory, f.getName()
415                             + ".failed");
416
417                     failed.createNewFile();
418                     PrintWriter JavaDoc w = null;
419                     w = new PrintWriter JavaDoc(failed);
420                     e.printStackTrace(w);
421                     w.flush();
422                     w.close();
423                     log.error("Error occured during auto deployment", e);
424                 } catch (IOException JavaDoc e1) {
425                     log
426                             .error(
427                                     "Error occured during failure report file creation.",
428                                     e1);
429                 }
430             }
431         }
432     }
433
434     /**
435      * Install the specified Archive in the JBI container and start it . Any
436      * exception will cause the abortion of the process. A file
437      * "fileName.success" will be created if success A file "fileName.failed"
438      * will be created otherwise, containing the related exception
439      *
440      * @param f
441      */

442     private void performInstall(File JavaDoc f) {
443         log.call();
444
445         if (f != null && f.exists()) {
446
447             try {
448
449                 MBeanServer JavaDoc jmxServer = managerService.getMBeanServer();
450
451                 // TODO Find a better way of managing URI
452
// String absPath = f.getAbsolutePath().replaceAll(" ", "%20");
453
// String archiveURI;
454
// if (absPath.startsWith("/")) {
455
// archiveURI = "file://" + absPath;
456
// } else {
457
// archiveURI = "file:///" + absPath;
458
// }
459

460                 ObjectName JavaDoc newInstallerName = installationService
461                         .loadNewInstaller(f.toURI().toString());
462                 if (!newInstallerName.getDomain().equals("error")) {
463                     Object JavaDoc[] nullObjects = new Object JavaDoc[0];
464                     String JavaDoc[] nullStrings = new String JavaDoc[0];
465
466                     Object JavaDoc result = jmxServer.invoke(newInstallerName,
467                             "install", nullObjects, nullStrings);
468
469                     if (result instanceof ObjectName JavaDoc) {
470                         ObjectName JavaDoc componentName = (ObjectName JavaDoc) result;
471
472                         jmxServer.invoke(componentName, "start", nullObjects,
473                                 nullStrings);
474
475                     } else {
476                         throw new Exception JavaDoc("error during installation");
477                     }
478                 } else {
479                     throw new Exception JavaDoc("Component can't be autoinstalled");
480                 }
481             } catch (Throwable JavaDoc e) {
482                 try {
483
484                     File JavaDoc failed = new File JavaDoc(workDirectory, f.getName()
485                             + ".failed");
486
487                     failed.createNewFile();
488                     PrintWriter JavaDoc w = null;
489                     w = new PrintWriter JavaDoc(failed);
490                     e.printStackTrace(w);
491                     w.flush();
492                     w.close();
493                     log.error("Error occured during auto installation.", e);
494                 } catch (IOException JavaDoc e1) {
495                     log
496                             .error(
497                                     "Error occured during failure report file creation.",
498                                     e1);
499                 }
500             }
501         }
502     }
503
504     // ----------------------------------------------------------------------
505
// Fractal LifecycleController implementation
506
// ----------------------------------------------------------------------
507

508     /**
509      * Undeploy the specified service assembly. isToBeDeleted is setted to true !
510      *
511      * @param name
512      */

513     protected void performSAUninstall(String JavaDoc name) {
514         try {
515             deploymentService.undeploy(name);
516         } catch (Exception JavaDoc e) {
517             log.error("Error occured during auto sa uninstallation.", e);
518         }
519     }
520
521     /**
522      * Install the specified shared library in the JBI container Any exception
523      * will cause the abortion of the process. A file "fileName.success" will be
524      * created if success A file "fileName.failed" will be created otherwise,
525      * containing the related exception
526      *
527      * @param f
528      */

529     private void performShare(File JavaDoc f) {
530         log.call();
531
532         if (f != null && f.exists()) {
533
534             try {
535
536                 // TODO Find a better way of managing URI
537
// String absPath = f.getAbsolutePath().replaceAll(" ", "%20");
538
// String archiveURI;
539
// if (absPath.startsWith("/")) {
540
// archiveURI = "file://" + absPath;
541
// } else {
542
// archiveURI = "file:///" + absPath;
543
// }
544

545                 installationService.installSharedLibrary(f.toURI().toString());
546
547             } catch (Throwable JavaDoc e) {
548                 try {
549
550                     File JavaDoc failed = new File JavaDoc(workDirectory, f.getName()
551                             + ".failed");
552
553                     failed.createNewFile();
554                     PrintWriter JavaDoc w = null;
555                     w = new PrintWriter JavaDoc(failed);
556                     e.printStackTrace(w);
557                     w.flush();
558                     w.close();
559                     log
560                             .error(
561                                     "Error occured during auto share lib installation.",
562                                     e);
563                 } catch (IOException JavaDoc e1) {
564                     log
565                             .error(
566                                     "Error occured during failure report file creation.",
567                                     e1);
568                 }
569             }
570         }
571     }
572
573     /**
574      * Uninstall the specified shared lib.
575      *
576      * @param name
577      */

578     protected void performSLUninstall(String JavaDoc name) {
579         installationService.uninstallSharedLibrary(name);
580     }
581
582 }
583
Popular Tags