KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > jbi > container > EnvironmentContext


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.jbi.container;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Iterator JavaDoc;
22 import java.util.Map JavaDoc;
23 import java.util.Timer JavaDoc;
24 import java.util.TimerTask JavaDoc;
25
26 import javax.jbi.JBIException;
27 import javax.management.JMException JavaDoc;
28 import javax.management.MBeanAttributeInfo JavaDoc;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.servicemix.jbi.framework.ComponentMBeanImpl;
33 import org.apache.servicemix.jbi.management.AttributeInfoHelper;
34 import org.apache.servicemix.jbi.management.BaseSystemService;
35 import org.apache.servicemix.jbi.util.FileUtil;
36 import org.apache.servicemix.jbi.util.FileVersionUtil;
37
38 import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
39 import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicBoolean;
40
41 /**
42  * Holder for environment information
43  *
44  * <component-name> (component root dir)
45  * |-> version_X (versionned dir)
46  * \-> workspace (workspace dir)
47  *
48  * ServiceAssembly root
49  * \-> version_X (versionned dir)
50  * |-> install (unzip dir)
51  * \-> sus (service units dir)
52  * |-> <component-name>
53  * |-> <service-unit-name>
54  *
55  * @version $Revision: 426415 $
56  */

57 public class EnvironmentContext extends BaseSystemService implements EnvironmentContextMBean {
58     private static final Log log = LogFactory.getLog(EnvironmentContext.class);
59
60     private File JavaDoc jbiRootDir;
61     private File JavaDoc componentsDir;
62     private File JavaDoc installationDir;
63     private File JavaDoc deploymentDir;
64     private File JavaDoc sharedLibDir;
65     private File JavaDoc serviceAssembliesDir;
66     private File JavaDoc tmpDir;
67     private int statsInterval = 5;
68     private Map JavaDoc envMap = new ConcurrentHashMap();
69     private AtomicBoolean started = new AtomicBoolean(false);
70     private boolean dumpStats = false;
71     private Timer JavaDoc statsTimer;
72     private TimerTask JavaDoc timerTask;
73
74
75     /**
76      * @return the current version of servicemix
77      */

78     public static String JavaDoc getVersion() {
79         String JavaDoc answer = null;
80         Package JavaDoc p = Package.getPackage("org.apache.servicemix");
81         if (p != null) {
82             answer = p.getImplementationVersion();
83         }
84         return answer;
85     }
86
87     /**
88      * Get Description
89      * @return description
90      */

91     public String JavaDoc getDescription(){
92         return "Manages Environment for the Container";
93     }
94     /**
95      * @return Returns the componentsDir.
96      */

97     public File JavaDoc getComponentsDir() {
98         return componentsDir;
99     }
100
101     /**
102      * @return Returns the installationDir.
103      */

104     public File JavaDoc getInstallationDir() {
105         return installationDir;
106     }
107     
108     /**
109      * Set the installationDir - rge default location
110      * is root/<container name>/installation
111      * @param installationDir
112      */

113     public void setInstallationDir(File JavaDoc installationDir){
114         this.installationDir = installationDir;
115     }
116     
117
118     /**
119      * @return Returns the deploymentDir.
120      */

121     public File JavaDoc getDeploymentDir() {
122         return deploymentDir;
123     }
124
125     /**
126      * @param deploymentDir The deploymentDir to set.
127      */

128     public void setDeploymentDir(File JavaDoc deploymentDir) {
129         this.deploymentDir = deploymentDir;
130     }
131     
132     /**
133      *
134      * @return Returns the shared library directory
135      */

136     public File JavaDoc getSharedLibDir(){
137         return sharedLibDir;
138     }
139
140     /**
141      * @return Returns the tmpDir
142      */

143     public File JavaDoc getTmpDir() {
144         if (tmpDir != null) {
145             FileUtil.buildDirectory(tmpDir);
146         }
147         return tmpDir;
148     }
149
150         
151     /**
152      * @return Returns service asseblies directory
153      */

154     public File JavaDoc getServiceAssembliesDir(){
155         return serviceAssembliesDir;
156     }
157    
158
159     /**
160      * Initialize the Environment
161      *
162      * @param container
163      * @param rootDirPath
164      * @exception javax.jbi.JBIException if the root directory informed could not be created or it is not a directory
165      */

166     public void init(JBIContainer container, String JavaDoc rootDirPath) throws JBIException {
167         super.init(container);
168         jbiRootDir = new File JavaDoc(rootDirPath);
169         buildDirectoryStructure();
170     }
171
172     protected Class JavaDoc getServiceMBean() {
173         return EnvironmentContextMBean.class;
174     }
175
176     /**
177      * Start the item.
178      *
179      * @exception javax.jbi.JBIException if the item fails to start.
180      */

181     public void start() throws javax.jbi.JBIException {
182         super.start();
183         if (started.compareAndSet(false, true)) {
184             scheduleStatsTimer();
185         }
186     }
187
188     /**
189      * Stop the item. This suspends current messaging activities.
190      *
191      * @exception javax.jbi.JBIException if the item fails to stop.
192      */

193     public void stop() throws javax.jbi.JBIException {
194         if (started.compareAndSet(true, false)) {
195             super.stop();
196             if (timerTask != null) {
197                 timerTask.cancel();
198             }
199         }
200     }
201
202     /**
203      * Shut down the item. The releases resources, preparatory to uninstallation.
204      *
205      * @exception javax.jbi.JBIException if the item fails to shut down.
206      */

207     public void shutDown() throws javax.jbi.JBIException {
208         super.shutDown();
209         for (Iterator JavaDoc i = envMap.values().iterator();i.hasNext();) {
210             ComponentEnvironment ce = (ComponentEnvironment) i.next();
211             ce.close();
212         }
213         if (timerTask != null) {
214             timerTask.cancel();
215         }
216         if (statsTimer != null) {
217             statsTimer.cancel();
218         }
219         envMap.clear();
220         container.getManagementContext().unregisterMBean(this);
221     }
222
223     /**
224      * @return Returns the statsInterval (in secs).
225      */

226     public int getStatsInterval() {
227         return statsInterval;
228     }
229
230     /**
231      * @param statsInterval The statsInterval to set (in secs).
232      */

233     public void setStatsInterval(int statsInterval) {
234         this.statsInterval = statsInterval;
235         scheduleStatsTimer();
236     }
237
238     /**
239      * @return Returns the dumpStats.
240      */

241     public boolean isDumpStats() {
242         return dumpStats;
243     }
244
245     /**
246      * @param value The dumpStats to set.
247      */

248     public void setDumpStats(boolean value) {
249         if (dumpStats && !value) {
250             if (timerTask != null) {
251                 timerTask.cancel();
252             }
253         }
254         else if (!dumpStats && value) {
255             dumpStats = value;//scheduleStatsTimer relies on dumpStats value
256
scheduleStatsTimer();
257         }
258         dumpStats = value;
259     }
260
261     protected void doDumpStats() {
262         if (isDumpStats()) {
263             for (Iterator JavaDoc i = envMap.values().iterator();i.hasNext();) {
264                 ComponentEnvironment ce = (ComponentEnvironment) i.next();
265                 ce.dumpStats();
266             }
267         }
268     }
269
270     /**
271      * register the ComponentConnector
272      *
273      * @param connector
274      * @return the CompponentEnvironment
275      * @throws JBIException
276      */

277     public ComponentEnvironment registerComponent(ComponentMBeanImpl connector) throws JBIException {
278         return registerComponent(null, connector);
279     }
280     
281     /**
282      * register the ComponentConnector
283      *
284      * @param connector
285      * @return the CompponentEnvironment
286      * @throws JBIException
287      */

288     public ComponentEnvironment registerComponent(ComponentEnvironment result,
289             ComponentMBeanImpl connector) throws JBIException {
290         if (result == null) {
291             result = new ComponentEnvironment();
292         }
293         if (!connector.isPojo()) {
294             if (container.isEmbedded()) {
295                 throw new JBIException("JBI component can not be installed in embedded mode");
296             }
297             // add workspace root and stats root ..
298
try {
299                 String JavaDoc name = connector.getComponentNameSpace().getName();
300                 if (result.getComponentRoot() == null) {
301                     File JavaDoc componentRoot = getComponentRootDir(name);
302                     FileUtil.buildDirectory(componentRoot);
303                     result.setComponentRoot(componentRoot);
304                 }
305                 if (result.getWorkspaceRoot() == null) {
306                     File JavaDoc privateWorkspace = createWorkspaceDirectory(name);
307                     result.setWorkspaceRoot(privateWorkspace);
308                 }
309                 if (result.getStateFile() == null) {
310                     File JavaDoc stateFile = FileUtil.getDirectoryPath(result.getComponentRoot(), "state.xml");
311                     result.setStateFile(stateFile);
312                 }
313             } catch (IOException JavaDoc e) {
314                 throw new JBIException(e);
315             }
316         }
317         if (result.getStatsFile() == null) {
318             File JavaDoc statsFile = FileUtil.getDirectoryPath(result.getComponentRoot(), "stats.cvs");
319             result.setStatsFile(statsFile);
320         }
321         result.setLocalConnector(connector);
322         envMap.put(connector, result);
323         return result;
324     }
325     
326     /**
327      * Get root directory for a Component
328      *
329      * @param componentName
330      * @return directory for deployment/workspace etc
331      * @throws IOException
332      */

333     public File JavaDoc getComponentRootDir(String JavaDoc componentName) {
334         if (getComponentsDir() == null) {
335             return null;
336         }
337         File JavaDoc result = FileUtil.getDirectoryPath(getComponentsDir(), componentName);
338         return result;
339     }
340
341     /**
342      * Create root directory for a Component
343      *
344      * @param componentName
345      * @return directory for deployment/workspace etc
346      * @throws IOException
347      */

348     public File JavaDoc createComponentRootDir(String JavaDoc componentName) throws IOException JavaDoc {
349         if (getComponentsDir() == null) {
350             return null;
351         }
352         File JavaDoc result = FileUtil.getDirectoryPath(getComponentsDir(), componentName);
353         return result;
354     }
355     
356     /**
357      * Get a new versionned directory for installation
358      *
359      * @param componentName
360      * @return
361      * @throws IOException
362      */

363     public File JavaDoc getNewComponentInstallationDir(String JavaDoc componentName) throws IOException JavaDoc {
364         File JavaDoc result = getComponentRootDir(componentName);
365         // get new version dir
366
result = FileVersionUtil.getNewVersionDirectory(result);
367         return result;
368     }
369     
370     /**
371      * Create installation directory for a Component
372      *
373      * @param componentName
374      * @return directory to deploy in
375      * @throws IOException
376      */

377     public File JavaDoc getComponentInstallationDir(String JavaDoc componentName) throws IOException JavaDoc {
378         File JavaDoc result = getComponentRootDir(componentName);
379         // get the version directory
380
result = FileVersionUtil.getLatestVersionDirectory(result);
381         return result;
382     }
383     
384     public ComponentEnvironment getNewComponentEnvironment(String JavaDoc compName) throws IOException JavaDoc {
385         File JavaDoc rootDir = FileUtil.getDirectoryPath(getComponentsDir(), compName);
386         File JavaDoc instDir = FileVersionUtil.getNewVersionDirectory(rootDir);
387         File JavaDoc workDir = FileUtil.getDirectoryPath(rootDir, "workspace");
388         File JavaDoc stateFile = FileUtil.getDirectoryPath(rootDir, "state.xml");
389         File JavaDoc statsFile = FileUtil.getDirectoryPath(rootDir, "stats.cvs");
390         ComponentEnvironment env = new ComponentEnvironment();
391         env.setComponentRoot(rootDir);
392         env.setInstallRoot(instDir);
393         env.setWorkspaceRoot(workDir);
394         env.setStateFile(stateFile);
395         env.setStatsFile(statsFile);
396         return env;
397     }
398     
399     public ComponentEnvironment getComponentEnvironment(String JavaDoc compName) throws IOException JavaDoc {
400         File JavaDoc rootDir = FileUtil.getDirectoryPath(getComponentsDir(), compName);
401         File JavaDoc instDir = FileVersionUtil.getLatestVersionDirectory(rootDir);
402         File JavaDoc workDir = FileUtil.getDirectoryPath(rootDir, "workspace");
403         File JavaDoc stateFile = FileUtil.getDirectoryPath(rootDir, "state.xml");
404         File JavaDoc statsFile = FileUtil.getDirectoryPath(rootDir, "stats.cvs");
405         ComponentEnvironment env = new ComponentEnvironment();
406         env.setComponentRoot(rootDir);
407         env.setInstallRoot(instDir);
408         env.setWorkspaceRoot(workDir);
409         env.setStateFile(stateFile);
410         env.setStatsFile(statsFile);
411         return env;
412     }
413     
414     public ServiceAssemblyEnvironment getNewServiceAssemblyEnvironment(String JavaDoc saName) throws IOException JavaDoc {
415         File JavaDoc rootDir = FileUtil.getDirectoryPath(getServiceAssembliesDir(), saName);
416         File JavaDoc versDir = FileVersionUtil.getNewVersionDirectory(rootDir);
417         File JavaDoc instDir = FileUtil.getDirectoryPath(versDir, "install");
418         File JavaDoc susDir = FileUtil.getDirectoryPath(versDir, "sus");
419         File JavaDoc stateFile = FileUtil.getDirectoryPath(rootDir, "state.xml");
420         ServiceAssemblyEnvironment env = new ServiceAssemblyEnvironment();
421         env.setRootDir(rootDir);
422         env.setInstallDir(instDir);
423         env.setSusDir(susDir);
424         env.setStateFile(stateFile);
425         return env;
426     }
427     
428     public ServiceAssemblyEnvironment getServiceAssemblyEnvironment(String JavaDoc saName) {
429         File JavaDoc rootDir = FileUtil.getDirectoryPath(getServiceAssembliesDir(), saName);
430         File JavaDoc versDir = FileVersionUtil.getLatestVersionDirectory(rootDir);
431         File JavaDoc instDir = FileUtil.getDirectoryPath(versDir, "install");
432         File JavaDoc susDir = FileUtil.getDirectoryPath(versDir, "sus");
433         File JavaDoc stateFile = FileUtil.getDirectoryPath(rootDir, "state.xml");
434         ServiceAssemblyEnvironment env = new ServiceAssemblyEnvironment();
435         env.setRootDir(rootDir);
436         env.setInstallDir(instDir);
437         env.setSusDir(susDir);
438         env.setStateFile(stateFile);
439         return env;
440     }
441     
442     /**
443      * Create workspace directory for a Component
444      *
445      * @param componentName
446      * @return directory workspace
447      * @throws IOException
448      */

449     public File JavaDoc createWorkspaceDirectory(String JavaDoc componentName) throws IOException JavaDoc {
450         File JavaDoc result = FileUtil.getDirectoryPath(getComponentsDir(), componentName);
451         result = FileUtil.getDirectoryPath(result, "workspace");
452         FileUtil.buildDirectory(result);
453         return result;
454     }
455     
456     /**
457      * deregister the ComponentConnector
458      *
459      * @param connector
460      * @param doDelete true if component is to be deleted
461      */

462     public void unreregister(ComponentMBeanImpl connector) {
463         ComponentEnvironment ce = (ComponentEnvironment) envMap.remove(connector);
464         if (ce != null) {
465             ce.close();
466         }
467     }
468
469     /**
470      * Remove the Component root directory from the local file system
471      *
472      * @param componentName
473      */

474     public void removeComponentRootDirectory(String JavaDoc componentName) {
475         File JavaDoc file = getComponentRootDir(componentName);
476         if (file != null) {
477             if (!FileUtil.deleteFile(file)) {
478                 log.warn("Failed to remove directory structure for component [version]: " + componentName + " [" + file.getName() + ']');
479             }
480             else {
481                 log.info("Removed directory structure for component [version]: " + componentName + " [" + file.getName() + ']');
482             }
483         }
484     }
485     
486     /**
487      * create a shared library directory
488      *
489      * @param name
490      * @return directory
491      * @throws IOException
492      */

493     public File JavaDoc createSharedLibraryDirectory(String JavaDoc name) {
494         File JavaDoc result = FileUtil.getDirectoryPath(getSharedLibDir(), name);
495         FileUtil.buildDirectory(result);
496         return result;
497     }
498     
499     /**
500      * remove shared library directory
501      * @param name
502      * @throws IOException
503      */

504     public void removeSharedLibraryDirectory(String JavaDoc name) {
505         File JavaDoc result = FileUtil.getDirectoryPath(getSharedLibDir(), name);
506         FileUtil.deleteFile(result);
507     }
508
509
510     private void buildDirectoryStructure() throws JBIException {
511         // We want ServiceMix to be able to run embedded
512
// so do not create the directory structure if the root does not exist
513
if (container.isEmbedded()) {
514             return;
515         }
516         try {
517             jbiRootDir = jbiRootDir.getCanonicalFile();
518             if (!jbiRootDir.exists()) {
519                 if (!jbiRootDir.mkdirs()) {
520                     throw new JBIException("Directory could not be created: "+jbiRootDir.getCanonicalFile());
521                 }
522             } else if (!jbiRootDir.isDirectory()) {
523                 throw new JBIException("Not a directory: " + jbiRootDir.getCanonicalFile());
524             }
525             if (installationDir == null){
526                 installationDir = FileUtil.getDirectoryPath(jbiRootDir, "install");
527             }
528             installationDir = installationDir.getCanonicalFile();
529             if (deploymentDir == null){
530                 deploymentDir = FileUtil.getDirectoryPath(jbiRootDir, "deploy");
531             }
532             deploymentDir = deploymentDir.getCanonicalFile();
533             componentsDir = FileUtil.getDirectoryPath(jbiRootDir, "components").getCanonicalFile();
534             tmpDir = FileUtil.getDirectoryPath(jbiRootDir, "tmp").getCanonicalFile();
535             sharedLibDir = FileUtil.getDirectoryPath(jbiRootDir, "sharedlibs").getCanonicalFile();
536             serviceAssembliesDir = FileUtil.getDirectoryPath(jbiRootDir,"service-assemblies").getCanonicalFile();
537             //actually create the sub directories
538
FileUtil.buildDirectory(installationDir);
539             FileUtil.buildDirectory(deploymentDir);
540             FileUtil.buildDirectory(componentsDir);
541             FileUtil.buildDirectory(tmpDir);
542             FileUtil.buildDirectory(sharedLibDir);
543             FileUtil.buildDirectory(serviceAssembliesDir);
544         } catch (IOException JavaDoc e) {
545             throw new JBIException(e);
546         }
547     }
548
549     private void scheduleStatsTimer() {
550         if (isDumpStats()) {
551             if (statsTimer == null) {
552                 statsTimer = new Timer JavaDoc(true);
553             }
554             if (timerTask != null) {
555                 timerTask.cancel();
556             }
557             timerTask = new TimerTask JavaDoc() {
558                 public void run() {
559                     doDumpStats();
560                 }
561             };
562             long interval = statsInterval * 1000;
563             statsTimer.scheduleAtFixedRate(timerTask, interval, interval);
564         }
565     }
566     
567     
568     
569    
570
571     /**
572      * Get an array of MBeanAttributeInfo
573      *
574      * @return array of AttributeInfos
575      * @throws JMException
576      */

577     public MBeanAttributeInfo JavaDoc[] getAttributeInfos() throws JMException JavaDoc {
578         AttributeInfoHelper helper = new AttributeInfoHelper();
579         helper.addAttribute(getObjectToManage(), "dumpStats", "Periodically dump Component statistics");
580         helper.addAttribute(getObjectToManage(), "statsInterval", "Interval (secs) before dumping statistics");
581         return AttributeInfoHelper.join(super.getAttributeInfos(), helper.getAttributeInfos());
582     }
583
584     public File JavaDoc getJbiRootDir() {
585         return jbiRootDir;
586     }
587
588
589 }
590
Popular Tags