KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > activemq > console > Main


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

18 package org.apache.activemq.console;
19
20 import java.io.File JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.PrintStream JavaDoc;
23 import java.lang.reflect.InvocationTargetException JavaDoc;
24 import java.lang.reflect.Method JavaDoc;
25 import java.net.JarURLConnection JavaDoc;
26 import java.net.MalformedURLException JavaDoc;
27 import java.net.URI JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.net.URLClassLoader JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Arrays JavaDoc;
32 import java.util.Comparator JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.LinkedList JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Set JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.StringTokenizer JavaDoc;
39
40 /**
41  * Main class that can bootstrap an ActiveMQ broker console. Handles command line
42  * argument parsing to set up and run broker tasks.
43  *
44  * @version $Revision$
45  */

46 public class Main {
47
48     public static final String JavaDoc TASK_DEFAULT_CLASS = "org.apache.activemq.console.command.ShellCommand";
49
50     private File JavaDoc activeMQHome;
51     private File JavaDoc activeMQBase;
52     private ClassLoader JavaDoc classLoader;
53     private Set JavaDoc extensions = new HashSet JavaDoc(5);
54     private Set JavaDoc activeMQClassPath = new HashSet JavaDoc(5);
55
56
57     private static boolean useDefExt = true;
58
59     public static void main(String JavaDoc[] args) {
60         Main app = new Main();
61
62         // Convert arguments to collection for easier management
63
List JavaDoc tokens = new LinkedList JavaDoc(Arrays.asList(args));
64         // Parse for extension directory option
65
app.parseExtensions(tokens);
66
67         // Add the following to the classpath:
68
//
69
// ${activemq.base}/conf
70
// ${activemq.base}/lib/* (only if activemq.base != activemq.home)
71
// ${activemq.home}/lib/*
72
// ${activemq.base}/lib/optional/* (only if activemq.base != activemq.home)
73
// ${activemq.home}/lib/optional/*
74
// ${activemq.base}/lib/web/* (only if activemq.base != activemq.home)
75
// ${activemq.home}/lib/web/*
76
//
77
if(useDefExt && app.canUseExtdir()) {
78
79             boolean baseIsHome = app.getActiveMQBase().equals(app.getActiveMQHome());
80
81             File JavaDoc baseLibDir = new File JavaDoc(app.getActiveMQBase(), "lib");
82             File JavaDoc homeLibDir = new File JavaDoc(app.getActiveMQHome(), "lib");
83
84             if(!baseIsHome) {
85                 app.addExtensionDirectory(baseLibDir);
86             }
87             app.addExtensionDirectory(homeLibDir);
88
89             if(!baseIsHome) {
90                 app.addExtensionDirectory(new File JavaDoc(baseLibDir, "optional"));
91                 app.addExtensionDirectory(new File JavaDoc(baseLibDir, "web"));
92             }
93             app.addExtensionDirectory(new File JavaDoc(homeLibDir, "optional"));
94             app.addExtensionDirectory(new File JavaDoc(homeLibDir, "web"));
95
96         }
97
98         // Add any custom classpath specified from the system property activemq.classpath
99
app.addClassPathList(System.getProperty("activemq.classpath"));
100
101         try {
102             app.runTaskClass(tokens);
103         } catch (ClassNotFoundException JavaDoc e) {
104             System.out.println("Could not load class: " + e.getMessage());
105             try {
106                 ClassLoader JavaDoc cl = app.getClassLoader();
107                 if( cl!=null ) {
108                     System.out.println("Class loader setup: ");
109                     printClassLoaderTree(cl);
110                 }
111             } catch (MalformedURLException JavaDoc e1) {
112             }
113         } catch (Throwable JavaDoc e) {
114             System.out.println("Failed to execute main task. Reason: " + e);
115         }
116     }
117
118     /**
119      * Print out what's in the classloader tree being used.
120      *
121      * @param cl
122      * @return depth
123      */

124     private static int printClassLoaderTree(ClassLoader JavaDoc cl) {
125         int depth = 0;
126         if( cl.getParent()!=null ) {
127             depth = printClassLoaderTree(cl.getParent())+1;
128         }
129
130         StringBuffer JavaDoc indent = new StringBuffer JavaDoc();
131         for (int i = 0; i < depth; i++) {
132             indent.append(" ");
133         }
134
135         if( cl instanceof URLClassLoader JavaDoc ) {
136             URLClassLoader JavaDoc ucl = (URLClassLoader JavaDoc) cl;
137             System.out.println(indent+cl.getClass().getName()+" {");
138             URL JavaDoc[] urls = ucl.getURLs();
139             for (int i = 0; i < urls.length; i++) {
140                 System.out.println(indent+" "+urls[i]);
141             }
142             System.out.println(indent+"}");
143         } else {
144             System.out.println(indent+cl.getClass().getName());
145         }
146         return depth;
147     }
148
149     public void parseExtensions(List JavaDoc tokens) {
150         if (tokens.isEmpty()) {
151             return;
152         }
153
154         int count = tokens.size();
155         int i = 0;
156
157         // Parse for all --extdir and --noDefExt options
158
while (i < count) {
159             String JavaDoc token = (String JavaDoc)tokens.get(i);
160             // If token is an extension dir option
161
if (token.equals("--extdir")) {
162                 // Process token
163
count--;
164                 tokens.remove(i);
165
166                 // If no extension directory is specified, or next token is another option
167
if (i >= count || ((String JavaDoc)tokens.get(i)).startsWith("-")) {
168                     System.out.println("Extension directory not specified.");
169                     System.out.println("Ignoring extension directory option.");
170                     continue;
171                 }
172
173                 // Process extension dir token
174
count--;
175                 File JavaDoc extDir = new File JavaDoc((String JavaDoc)tokens.remove(i));
176
177                 if(!canUseExtdir()) {
178                     System.out.println("Extension directory feature not available due to the system classpath being able to load: " + TASK_DEFAULT_CLASS);
179                     System.out.println("Ignoring extension directory option.");
180                     continue;
181                 }
182
183                 if (!extDir.isDirectory()) {
184                     System.out.println("Extension directory specified is not valid directory: " + extDir);
185                     System.out.println("Ignoring extension directory option.");
186                     continue;
187                 }
188
189                 addExtensionDirectory(extDir);
190             } else if (token.equals("--noDefExt")) { // If token is --noDefExt option
191
count--;
192                 tokens.remove(i);
193                 useDefExt = false;
194             } else {
195                 i++;
196             }
197         }
198
199     }
200
201     public void runTaskClass(List JavaDoc tokens) throws Throwable JavaDoc {
202
203         System.out.println("ACTIVEMQ_HOME: "+ getActiveMQHome());
204         System.out.println("ACTIVEMQ_BASE: "+ getActiveMQBase());
205
206         ClassLoader JavaDoc cl = getClassLoader();
207
208         // Use reflection to run the task.
209
try {
210             String JavaDoc[] args = (String JavaDoc[]) tokens.toArray(new String JavaDoc[tokens.size()]);
211             Class JavaDoc task = cl.loadClass(TASK_DEFAULT_CLASS);
212             Method JavaDoc runTask = task.getMethod("main", new Class JavaDoc[] { String JavaDoc[].class, InputStream JavaDoc.class, PrintStream JavaDoc.class });
213             runTask.invoke(task.newInstance(), new Object JavaDoc[] { args, System.in, System.out });
214         } catch (InvocationTargetException JavaDoc e) {
215             throw e.getCause();
216         }
217     }
218
219     public void addExtensionDirectory(File JavaDoc directory) {
220         extensions.add(directory);
221     }
222
223     public void addClassPathList(String JavaDoc fileList) {
224         if (fileList != null && fileList.length() > 0) {
225             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(fileList, ";");
226             while (tokenizer.hasMoreTokens()) {
227                 addClassPath(new File JavaDoc(tokenizer.nextToken()));
228             }
229         }
230     }
231
232     public void addClassPath(File JavaDoc classpath) {
233         activeMQClassPath.add(classpath);
234     }
235
236     /**
237      * The extension directory feature will not work if the broker factory is already in the classpath
238      * since we have to load him from a child ClassLoader we build for it to work correctly.
239      *
240      * @return true, if extension dir can be used. false otherwise.
241      */

242     public boolean canUseExtdir() {
243         try {
244             Main.class.getClassLoader().loadClass(TASK_DEFAULT_CLASS);
245             return false;
246         } catch (ClassNotFoundException JavaDoc e) {
247             return true;
248         }
249     }
250
251     public ClassLoader JavaDoc getClassLoader() throws MalformedURLException JavaDoc {
252         if(classLoader==null) {
253             // Setup the ClassLoader
254
classLoader = Main.class.getClassLoader();
255             if (!extensions.isEmpty() || !activeMQClassPath.isEmpty()) {
256
257                 ArrayList JavaDoc urls = new ArrayList JavaDoc();
258
259                 for (Iterator JavaDoc iter = activeMQClassPath.iterator(); iter.hasNext();) {
260                     File JavaDoc dir = (File JavaDoc) iter.next();
261                     // try{ System.out.println("Adding to classpath: " + dir.getCanonicalPath()); }catch(Exception e){}
262
urls.add(dir.toURL());
263                 }
264
265                 for (Iterator JavaDoc iter = extensions.iterator(); iter.hasNext();) {
266                     File JavaDoc dir = (File JavaDoc) iter.next();
267                     if( dir.isDirectory() ) {
268                         File JavaDoc[] files = dir.listFiles();
269                         if( files!=null ) {
270
271                             // Sort the jars so that classpath built is consistently
272
// in the same order. Also allows us to use jar names to control
273
// classpath order.
274
Arrays.sort(files, new Comparator JavaDoc(){
275                                 public int compare(Object JavaDoc o1, Object JavaDoc o2) {
276                                     File JavaDoc f1 = (File JavaDoc) o1;
277                                     File JavaDoc f2 = (File JavaDoc) o2;
278                                     return f1.getName().compareTo(f2.getName());
279                                 }
280                             });
281
282                             for (int j = 0; j < files.length; j++) {
283                                 if( files[j].getName().endsWith(".zip") || files[j].getName().endsWith(".jar") ) {
284                                     // try{ System.out.println("Adding to classpath: " + files[j].getCanonicalPath()); }catch(Exception e){}
285
urls.add(files[j].toURL());
286                                 }
287                             }
288                         }
289                     }
290                 }
291
292                 URL JavaDoc u[] = new URL JavaDoc[urls.size()];
293                 urls.toArray(u);
294                 classLoader = new URLClassLoader JavaDoc(u, classLoader);
295             }
296             Thread.currentThread().setContextClassLoader(classLoader);
297         }
298         return classLoader;
299     }
300
301     public void setActiveMQHome(File JavaDoc activeMQHome) {
302         this.activeMQHome = activeMQHome;
303     }
304
305     public File JavaDoc getActiveMQHome() {
306         if(activeMQHome==null) {
307             if(System.getProperty("activemq.home") != null) {
308                 activeMQHome = new File JavaDoc(System.getProperty("activemq.home"));
309             }
310
311             if(activeMQHome==null){
312                 // guess from the location of the jar
313
URL JavaDoc url = Main.class.getClassLoader().getResource("org/apache/activemq/console/Main.class");
314                 if (url != null) {
315                     try {
316                         JarURLConnection JavaDoc jarConnection = (JarURLConnection JavaDoc) url.openConnection();
317                         url = jarConnection.getJarFileURL();
318                         URI JavaDoc baseURI = new URI JavaDoc(url.toString()).resolve("..");
319                         activeMQHome = new File JavaDoc(baseURI).getCanonicalFile();
320                         System.setProperty("activemq.home",activeMQHome.getAbsolutePath());
321                     } catch (Exception JavaDoc ignored) {
322                     }
323                 }
324             }
325
326             if(activeMQHome==null){
327                 activeMQHome = new File JavaDoc("../.");
328                 System.setProperty("activemq.home",activeMQHome.getAbsolutePath());
329             }
330         }
331
332         return activeMQHome;
333     }
334
335     public File JavaDoc getActiveMQBase() {
336         if(activeMQBase==null) {
337             if(System.getProperty("activemq.base") != null) {
338                 activeMQBase = new File JavaDoc(System.getProperty("activemq.base"));
339             }
340
341             if(activeMQBase==null){
342                 activeMQBase = getActiveMQHome();
343                 System.setProperty("activemq.base",activeMQBase.getAbsolutePath());
344             }
345         }
346
347         return activeMQBase;
348     }
349 }
350
Popular Tags