KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > sape > carbon > services > carbonmanagement > DefaultCarbonManagementServiceImpl


1 package org.sape.carbon.services.carbonmanagement;
2
3 import java.io.IOException JavaDoc;
4 import java.io.StringWriter JavaDoc;
5 import java.lang.reflect.InvocationTargetException JavaDoc;
6 import java.lang.reflect.Method JavaDoc;
7 import java.util.Arrays JavaDoc;
8 import java.util.Collection JavaDoc;
9 import java.util.HashMap JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.Map JavaDoc;
12
13 import org.sape.carbon.core.bootstrap.BootStrapper;
14 import org.sape.carbon.core.component.ComponentConfiguration;
15 import org.sape.carbon.core.component.Lookup;
16 import org.sape.carbon.core.component.lifecycle.Configurable;
17 import org.sape.carbon.core.component.lifecycle.InvalidStateException;
18 import org.sape.carbon.core.component.lifecycle.LifecycleException;
19 import org.sape.carbon.core.config.Config;
20 import org.sape.carbon.core.config.Configuration;
21 import org.sape.carbon.core.config.InvalidConfigurationException;
22 import org.sape.carbon.core.config.interceptor.ConfigurationInterceptor;
23 import org.sape.carbon.core.config.node.Node;
24 import org.sape.carbon.core.config.node.NodeNotFoundException;
25 import org.sape.carbon.core.exception.ExceptionUtility;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.jdom.output.XMLOutputter;
30
31 /**
32  * Default implementation of CarbonManagementService
33  *
34  * Copyright 2002 Sapient
35  * @since carbon 1.2
36  * @author Douglas Voet, Dec 19, 2002
37  * @version $Revision: 1.10 $($Author: atayal $ / $Date: 2003/04/29 13:40:30 $)
38  */

39 public class DefaultCarbonManagementServiceImpl
40     implements CarbonManagementService, Configurable {
41
42     /** Provides a handle to Apache-commons logger */
43     private Log log = LogFactory.getLog(this.getClass());
44
45     /** Holds the components configuration. */
46     private CarbonManagementServiceConfiguration config;
47
48     /**
49      * Configures the component.
50      *
51      * @param configuration configuration for this component
52      * @throws InvalidConfigurationException indicates an invalid
53      * configuration
54      */

55     public void configure(ComponentConfiguration configuration)
56         throws InvalidConfigurationException {
57
58         try {
59             this.config = (CarbonManagementServiceConfiguration) configuration;
60         } catch (ClassCastException JavaDoc cce) {
61             throw new InvalidConfigurationException(
62                 this.getClass(),
63                 configuration.getConfigurationName(),
64                 null,
65                 "Configuration does not implement "
66                     + CarbonManagementServiceConfiguration.class.getName(),
67                 cce);
68         }
69     }
70
71     /**
72      * Genereates an Xml representation of the configuration tree.
73      *
74      * @param configuationPath path to configuration to view
75      * @return an Xml representation of the configuration tree
76      * @throws ConfigurationNotFoundException indicates no configuration
77      * could be found at the given path
78      */

79     public String JavaDoc viewConfigurationXML(String JavaDoc configuationPath)
80         throws ConfigurationNotFoundException {
81
82         try {
83             Configuration config =
84                 Config.getInstance().fetchConfiguration(configuationPath);
85
86             StringWriter JavaDoc writer = new StringWriter JavaDoc();
87             XMLOutputter outputter = new XMLOutputter(" ", true);
88             outputter.output(config.getDataStructure(), writer);
89             return writer.toString();
90
91         } catch (org.sape.carbon.core.config.ConfigurationNotFoundException
92                     cnfe) {
93
94             throw new ConfigurationNotFoundException(
95                 this.getClass(),
96                 "[" + configuationPath + "] was not found",
97                 cnfe);
98         } catch (IOException JavaDoc ioe) {
99             throw new InvalidStateException(
100                 this.getClass(),
101                 "[" + configuationPath + "] could not be converted to XML",
102                 ioe);
103         }
104     }
105
106     /**
107      * Generates an HTML representation of the configuration tree.
108      *
109      * @return Html representation of the configuration tree
110      */

111     public String JavaDoc viewConfigurationTree() {
112         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
113
114         buffer.append("<html><body><h2>Configuration Tree</h2>\n");
115         buffer.append("<pre><font face='Courier New'>");
116
117         try {
118             appendSubtreeToBuffer(
119                 buffer,
120                 Config.getInstance().fetchNode(Config.ROOT_NODE_NAME),
121                 0);
122
123         } catch (NodeNotFoundException nnfe) {
124             // never gonna happen
125
}
126
127         buffer.append("</font></pre></body></html>");
128
129         return buffer.toString();
130     }
131
132     /**
133      * @inherit
134      */

135     public void refreshAllConfigurations() {
136         try {
137             Config.getInstance().fetchNode(Config.ROOT_NODE_NAME).refresh();
138         } catch (NodeNotFoundException nnfe) {
139             // never gonna happen
140
}
141     }
142
143     /**
144      * Forces a configuration to refresh from the store.
145      *
146      * @param configuationPath path to configuration to refresh.
147      * @throws ConfigurationNotFoundException indicates no configuration was
148      * found at the given path
149      */

150     public void refreshConfiguration(String JavaDoc configuationPath)
151         throws ConfigurationNotFoundException {
152
153         try {
154             Config.getInstance().fetchNode(configuationPath).refresh();
155         } catch (org.sape.carbon.core.config.node.NodeNotFoundException nnfe) {
156             throw new ConfigurationNotFoundException(
157                 this.getClass(),
158                 "[" + configuationPath + "] was not found",
159                 nnfe);
160         }
161     }
162
163     /**
164      * @inherit
165      *
166      * This implementation will not refresh components that are configured
167      * not to be refreshed.
168      */

169     public void refreshAllComponentConfigurations() {
170         Collection JavaDoc componentNames =
171             Lookup.getInstance().getComponentKeeper().getComponentNames();
172
173         Collection JavaDoc dontReconfigure =
174             Arrays.asList(this.config.getDontReconfigure());
175
176         Iterator JavaDoc componentIterator = componentNames.iterator();
177         while (componentIterator.hasNext()) {
178             String JavaDoc componentName = (String JavaDoc) componentIterator.next();
179
180             if (!dontReconfigure.contains(componentName)) {
181                 try {
182                     ConfigurationInterceptor assistantView =
183                         (ConfigurationInterceptor) Lookup
184                             .getInstance()
185                             .fetchComponent(
186                             componentName);
187
188                     assistantView.refreshConfiguration();
189                 } catch (LifecycleException le) {
190                     if (log.isDebugEnabled()) {
191                         log.debug("Could not reconfigure component ["
192                             + componentName
193                             + "] due to exception: "
194                             + ExceptionUtility.printStackTracesToString(le));
195                     }
196                 }
197             }
198         }
199     }
200
201     /**
202      * @see Lookup#fetchComponent
203      */

204     public void loadComponent(String JavaDoc componentName)
205         throws ComponentNotFoundException {
206
207         try {
208             Lookup.getInstance().fetchComponent(componentName);
209         } catch (org.sape.carbon.core.component.ComponentNotFoundException
210                     cnfe) {
211
212             throw new ComponentNotFoundException(
213                 this.getClass(),
214                 "[" + componentName + "] was not found",
215                 cnfe);
216         }
217     }
218
219     /**
220      * This implementation uses configuration to specify which deployment
221      * properties to return.
222      *
223      * @return an HTML string representation of the deployment properties.
224      */

225     public String JavaDoc getDeploymentProperties() {
226         String JavaDoc[] propertyNames = this.config.getDeploymentPropertyNames();
227
228         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(256);
229         buf.append("<html><body><h2>Deployment Properties</h2>\n");
230
231         buf.append("<table border='2'><tr> <td><b>Name</b></td> ");
232         buf.append("<td><b>Value</b></td> </tr>\n");
233
234         for (int index = 0; index < propertyNames.length; index++) {
235             buf.append("<tr> <td>");
236             buf.append(propertyNames[index]);
237             buf.append("</td> <td>");
238             buf.append(
239                 BootStrapper.getInstance().getDeploymentProperty(
240                     propertyNames[index]));
241             buf.append("</td> </tr>\n");
242         }
243         buf.append("</table></body></html>");
244
245         return buf.toString();
246     }
247
248
249     /**
250      * This implementation uses configuration to specify which deployment
251      * properties to return.
252      *
253      * @return the deployment property map for all properties listed in
254      * configuration
255      */

256     public Map JavaDoc getDeploymentPropertyMap() {
257         String JavaDoc[] propertyNames = this.config.getDeploymentPropertyNames();
258         Map JavaDoc map = new HashMap JavaDoc();
259
260         for (int index = 0; index < propertyNames.length; index++) {
261             map.put(
262                 propertyNames[index],
263                 BootStrapper.getInstance().getDeploymentProperty(
264                     propertyNames[index]));
265         }
266
267         return map;
268     }
269
270     /**
271      * @see BootStrapper#getDeploymentProperty
272      */

273     public String JavaDoc getDeploymentProperty(String JavaDoc propertyName) {
274         return BootStrapper.getInstance().getDeploymentProperty(propertyName);
275     }
276
277     /** String constant for a tab without child. */
278     private static final String JavaDoc TAB = "| ";
279
280     /** String constant for a tab with child. */
281     private static final String JavaDoc TAB_WITH_CHILD = "+--";
282
283     /** String constant for generating a new line. */
284     private static final String JavaDoc NEW_LINE = "\n";
285
286     /** String constant for drawing a text arrow. */
287     private static final String JavaDoc ARROW = " --> ";
288
289     /**
290      * Recursive method that does a depth first traversal of the configuration
291      * node hierachy, appending the text representation of the subtree to
292      * the buffer.
293      *
294      * @param buffer the buffer to extend the subtree to
295      * @param subtree the subtree to append
296      * @param depth used to determine number of tabs to output before each node
297      */

298     private void appendSubtreeToBuffer(
299         StringBuffer JavaDoc buffer,
300         Node subtree,
301         int depth) {
302
303
304         Node[] children = subtree.fetchChildren();
305         String JavaDoc nodeName = subtree.getName();
306
307         if ("".equals(nodeName)) {
308             nodeName = Config.ROOT_NODE_NAME;
309         }
310
311         for (int count = 0; count < depth; count++) {
312             buffer.append(TAB);
313         }
314
315         if (children.length == 0) {
316             buffer.append(TAB);
317             buffer.append(nodeName);
318             buffer.append(NEW_LINE);
319
320         } else {
321             buffer.append(TAB_WITH_CHILD);
322             buffer.append(nodeName);
323             buffer.append(NEW_LINE);
324
325             for (int index = 0; index < children.length; index++) {
326                 if (!children[index]
327                     .getAbsoluteName()
328                     .startsWith(subtree.getAbsoluteName())) {
329                     // this is a config reference
330
for (int count = 0; count < depth; count++) {
331                         buffer.append(TAB);
332                     }
333
334                     buffer.append(TAB);
335                     buffer.append(children[index].getName());
336                     buffer.append(ARROW);
337                     buffer.append(children[index].getAbsoluteName());
338                     buffer.append(NEW_LINE);
339
340                 } else {
341                     appendSubtreeToBuffer(buffer, children[index], depth + 1);
342                 }
343             }
344         }
345     }
346
347
348     /**
349      * Retrieves the free memory available to the JVM
350      * @see java.lang.Runtime#freeMemory
351      * @return the amount of free memory in the JVM
352      */

353     public long getFreeMemory() {
354         return Runtime.getRuntime().freeMemory();
355     }
356
357     /**
358      * Retrieves the amount of memory researved by the JVM
359      * @see java.lang.Runtime#totalMemory
360      * @return the amount of memory researved by the JVM
361      */

362     public long getTotalMemory() {
363         return Runtime.getRuntime().totalMemory();
364     }
365
366     /**
367      * Retrieves the amount of memory the JVM may attempt to use
368      * @see java.lang.Runtime#maxMemory
369      * @return the amount of memory the JVM may attempt to use
370      */

371     public long getMaximumMemory() {
372         long maxMemory = -1;
373         try {
374             Runtime JavaDoc rt = Runtime.getRuntime();
375             Method JavaDoc m = Runtime JavaDoc.class.getMethod("maxMemory", new Class JavaDoc[0]);
376             maxMemory = ((Long JavaDoc) m.invoke(rt, new Object JavaDoc[0])).longValue();
377         } catch (NoSuchMethodException JavaDoc nsme) {
378             // This is expected if we are not on Java 1.4
379
} catch (IllegalAccessException JavaDoc iae) {
380             // Never expected
381
} catch (InvocationTargetException JavaDoc ite) {
382            // Never expected
383
}
384         return maxMemory;
385     }
386
387     /**
388      * Retrieves the number of processes available to this JVM
389      * @see java.lang.Runtime#availableProcessors
390      * @return the number of processes available to this JVM
391      */

392     public int getAvailableProcessors() {
393         int processors = -1;
394         try {
395             Runtime JavaDoc rt = Runtime.getRuntime();
396             Method JavaDoc m =
397                 Runtime JavaDoc.class.getMethod("availableProcessors", new Class JavaDoc[0]);
398
399             processors = ((Integer JavaDoc) m.invoke(rt, new Object JavaDoc[0])).intValue();
400         } catch (NoSuchMethodException JavaDoc nsme) {
401             // This is expected if we are not on Java 1.4
402
} catch (IllegalAccessException JavaDoc iae) {
403             // Never expected
404
} catch (InvocationTargetException JavaDoc ite) {
405            // Never expected
406
}
407         return processors;
408     }
409
410     /**
411      * Gets the root thread group in the system.
412      *
413      * @return root thread group in the system
414      */

415     private ThreadGroup JavaDoc getRootThreadGroup() {
416         ThreadGroup JavaDoc group = Thread.currentThread().getThreadGroup();
417         while (group.getParent() != null) {
418             group = group.getParent();
419         }
420
421         return group;
422     }
423
424     /**
425      * Retrieves the number of active threads in the JVM
426      * @see java.lang.Thread#activeCount
427      * @return the number of active threads in the JVM
428      */

429     public int getActiveThreadCount() {
430         return getRootThreadGroup().activeCount();
431     }
432
433     /**
434      * Retrieves the number of active thread groups in the JVM
435      * @see java.lang.ThreadGroup#activeGroupCount
436      * @return the number of active thread groups in the JVM
437      */

438     public int getActiveThreadGroupCount() {
439         return getRootThreadGroup().activeGroupCount();
440     }
441 }
442
Popular Tags