KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > base > container > ComponentContainer


1 /*
2  * $Id: ComponentContainer.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2003 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.base.container;
26
27 import java.io.File JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.net.MalformedURLException JavaDoc;
30 import java.net.URL JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33
34 import org.ofbiz.base.component.AlreadyLoadedException;
35 import org.ofbiz.base.component.ComponentConfig;
36 import org.ofbiz.base.component.ComponentException;
37 import org.ofbiz.base.component.ComponentLoaderConfig;
38 import org.ofbiz.base.start.Classpath;
39 import org.ofbiz.base.util.Debug;
40 import org.ofbiz.base.util.UtilValidate;
41
42 /**
43  * ComponentContainer - StartupContainer implementation for Components
44  * <p/>
45  * Example ofbiz-container.xml configuration:
46  * <pre>
47  * <container name="component-container" class="org.ofbiz.base.component.ComponentContainer"/>
48  * </pre>
49  *
50  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
51  * @version $Rev: 5462 $
52  * @since 3.0
53  */

54 public class ComponentContainer implements Container {
55
56     public static final String JavaDoc module = ComponentContainer.class.getName();
57
58     //protected static List loadedComponents2 = null;
59
protected Classpath classPath = new Classpath(System.getProperty("java.class.path"));
60     protected String JavaDoc configFileLocation = null;
61     private boolean loaded = false;
62
63     /**
64      * @see org.ofbiz.base.container.Container#init(java.lang.String[], java.lang.String)
65      */

66     public void init(String JavaDoc[] args, String JavaDoc configFile) throws ContainerException {
67         this.configFileLocation = configFile;
68
69         // get the config for this container
70
ContainerConfig.Container cc = ContainerConfig.getContainer("component-container", configFileLocation);
71
72         // check for an override loader config
73
String JavaDoc loaderConfig = null;
74         if (cc.getProperty("loader-config") != null) {
75             loaderConfig = cc.getProperty("loader-config").value;
76         }
77
78         // check for en override update classpath
79
boolean updateClassPath = true;
80         if (cc.getProperty("update-classpath") != null) {
81             updateClassPath = "true".equalsIgnoreCase(cc.getProperty("update-classpath").value);
82         }
83
84         // load the components
85
try {
86             loadComponents(loaderConfig, updateClassPath);
87         } catch (AlreadyLoadedException e) {
88             throw new ContainerException(e);
89         } catch (ComponentException e) {
90             throw new ContainerException(e);
91         }
92     }
93
94     /**
95      * @see org.ofbiz.base.container.Container#start()
96      */

97     public boolean start() throws ContainerException {
98         return true;
99     }
100
101     public synchronized void loadComponents(String JavaDoc loaderConfig, boolean updateClasspath) throws AlreadyLoadedException, ComponentException {
102         // set the loaded list; and fail if already loaded
103
//if (loadedComponents == null) {
104
// loadedComponents = new LinkedList();
105
if (!loaded) {
106             loaded = true;
107         } else {
108             throw new AlreadyLoadedException("Components already loaded, cannot start");
109         }
110
111         // get the components to load
112
List JavaDoc components = ComponentLoaderConfig.getRootComponents(loaderConfig);
113
114         // load each component
115
if (components != null) {
116             Iterator JavaDoc ci = components.iterator();
117             while (ci.hasNext()) {
118                 ComponentLoaderConfig.ComponentDef def = (ComponentLoaderConfig.ComponentDef) ci.next();
119                 this.loadComponentFromConfig(def);
120             }
121         }
122
123         // set the new classloader/classpath on the current thread
124
if (updateClasspath) {
125             System.setProperty("java.class.path", classPath.toString());
126             ClassLoader JavaDoc cl = classPath.getClassLoader();
127             Thread.currentThread().setContextClassLoader(cl);
128         }
129
130         Debug.logInfo("All components loaded", module);
131     }
132
133     private void loadComponentFromConfig(ComponentLoaderConfig.ComponentDef def) {
134         if (def.type == ComponentLoaderConfig.SINGLE_COMPONENT) {
135             ComponentConfig config = null;
136             try {
137                 config = ComponentConfig.getComponentConfig(def.name, def.location);
138                 if (UtilValidate.isEmpty(def.name)) {
139                     def.name = config.getGlobalName();
140                 }
141             } catch (ComponentException e) {
142                 Debug.logError("Cannot load component : " + def.name + " @ " + def.location + " : " + e.getMessage(), module);
143             }
144             if (config == null) {
145                 Debug.logError("Cannot load component : " + def.name + " @ " + def.location, module);
146             } else {
147                 this.loadComponent(config);
148             }
149         } else if (def.type == ComponentLoaderConfig.COMPONENT_DIRECTORY) {
150             this.loadComponentDirectory(def.location);
151         }
152     }
153
154     private void loadComponentDirectory(String JavaDoc directoryName) {
155         Debug.logInfo("Auto-Loading component directory : [" + directoryName + "]", module);
156         File JavaDoc parentPath = new File JavaDoc(directoryName);
157         if (!parentPath.exists() || !parentPath.isDirectory()) {
158             Debug.logError("Auto-Load Component directory not found : " + directoryName, module);
159         } else {
160             File JavaDoc componentLoadConfig = new File JavaDoc(parentPath, "component-load.xml");
161             if (componentLoadConfig != null && componentLoadConfig.exists()) {
162                 URL JavaDoc configUrl = null;
163                 try {
164                     configUrl = componentLoadConfig.toURL();
165                     List JavaDoc componentsToLoad = ComponentLoaderConfig.getComponentsFromConfig(configUrl);
166                     if (componentsToLoad != null) {
167                         Iterator JavaDoc i = componentsToLoad.iterator();
168                         while (i.hasNext()) {
169                             ComponentLoaderConfig.ComponentDef def = (ComponentLoaderConfig.ComponentDef) i.next();
170                             this.loadComponentFromConfig(def);
171                         }
172                     }
173                 } catch (MalformedURLException JavaDoc e) {
174                     Debug.logError(e, "Unable to locate URL for component loading file: " + componentLoadConfig.getAbsolutePath(), module);
175                 } catch (ComponentException e) {
176                     Debug.logError(e, "Unable to load components from URL: " + configUrl.toExternalForm(), module);
177                 }
178             } else {
179                 String JavaDoc subs[] = parentPath.list();
180                 for (int i = 0; i < subs.length; i++) {
181                     try {
182                         File JavaDoc componentPath = new File JavaDoc(parentPath.getCanonicalPath() + "/" + subs[i]);
183                         if (componentPath.isDirectory() && !subs[i].equals("CVS")) {
184                             // make sure we have a component configuraton file
185
String JavaDoc componentLocation = componentPath.getCanonicalPath();
186                             File JavaDoc configFile = new File JavaDoc(componentLocation + "/ofbiz-component.xml");
187                             if (configFile.exists()) {
188                                 ComponentConfig config = null;
189                                 try {
190                                     // pass null for the name, will default to the internal component name
191
config = ComponentConfig.getComponentConfig(null, componentLocation);
192                                 } catch (ComponentException e) {
193                                     Debug.logError(e, "Cannot load component : " + componentPath.getName() + " @ " + componentLocation + " : " + e.getMessage(), module);
194                                 }
195                                 if (config == null) {
196                                     Debug.logError("Cannot load component : " + componentPath.getName() + " @ " + componentLocation, module);
197                                 } else {
198                                     loadComponent(config);
199                                 }
200                             }
201                         }
202                     } catch (IOException JavaDoc ioe) {
203                         Debug.logError(ioe, module);
204                     }
205                 }
206             }
207         }
208     }
209
210     private void loadComponent(ComponentConfig config) {
211         // make sure the component is enabled
212
if (!config.enabled()) {
213             Debug.logInfo("Not Loading component : [" + config.getComponentName() + "] (disabled)", module);
214             return;
215         }
216
217         Debug.logInfo("Loading component : [" + config.getComponentName() + "]", module);
218         List JavaDoc classpathInfos = config.getClasspathInfos();
219         String JavaDoc configRoot = config.getRootLocation();
220         configRoot = configRoot.replace('\\', '/');
221         // set the root to have a trailing slash
222
if (!configRoot.endsWith("/")) {
223             configRoot = configRoot + "/";
224         }
225         if (classpathInfos != null) {
226             Iterator JavaDoc cpi = classpathInfos.iterator();
227             while (cpi.hasNext()) {
228                 ComponentConfig.ClasspathInfo cp = (ComponentConfig.ClasspathInfo) cpi.next();
229                 String JavaDoc location = cp.location.replace('\\', '/');
230                 // set the location to not have a leading slash
231
if (location.startsWith("/")) {
232                     location = location.substring(1);
233                 }
234                 if ("dir".equals(cp.type)) {
235                     classPath.addComponent(configRoot + location);
236                 } else if ("jar".equals(cp.type)) {
237                     String JavaDoc dirLoc = location;
238                     if (dirLoc.endsWith("/*")) {
239                         // strip off the slash splat
240
dirLoc = location.substring(0, location.length() - 2);
241                     }
242                     File JavaDoc path = new File JavaDoc(configRoot + dirLoc);
243                     if (path.exists()) {
244                         if (path.isDirectory()) {
245                             // load all .jar and .zip files in this directory
246
File JavaDoc files[] = path.listFiles();
247                             for (int i = 0; i < files.length; i++) {
248                                 String JavaDoc file = files[i].getName();
249                                 if (file.endsWith(".jar") || file.endsWith(".zip")) {
250                                     classPath.addComponent(files[i]);
251                                 }
252                             }
253                         } else {
254                             // add a single file
255
classPath.addComponent(configRoot + location);
256                         }
257                     } else {
258                         Debug.logWarning("Location '" + configRoot + dirLoc + "' does not exist", module);
259                     }
260                 } else {
261                     Debug.logError("Classpath type '" + cp.type + "' is not supported; '" + location + "' not loaded", module);
262                 }
263             }
264         }
265     }
266
267     /**
268      * @see org.ofbiz.base.container.Container#stop()
269      */

270     public void stop() throws ContainerException {
271     }
272
273     /**
274      * Static method for easy loading of components for use when the container system is not.
275      *
276      * @param updateClasspath Tells the component loader to update the classpath, and thread classloader
277      * @throws AlreadyLoadedException
278      * @throws ComponentException
279      */

280     public static synchronized void loadComponents(boolean updateClasspath) throws AlreadyLoadedException, ComponentException {
281         ComponentContainer cc = new ComponentContainer();
282         cc.loadComponents(null, updateClasspath);
283         cc = null;
284     }
285 }
Popular Tags