KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > barracuda > admin > BarracudaAdmin


1 /*
2  * Copyright (C) 2003 Christian Cryder [christianc@granitepeaks.com]
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  *
18  * $Id: BarracudaAdmin.java,v 1.9 2004/02/01 05:16:26 christianc Exp $
19  */

20 package org.enhydra.barracuda.admin;
21
22 import java.io.*;
23 import java.util.*;
24 import java.lang.ref.*;
25 import java.net.*;
26 import javax.servlet.*;
27 import javax.servlet.http.*;
28
29 import org.apache.log4j.*;
30 import org.w3c.dom.*;
31 import org.w3c.dom.html.*;
32
33 import org.enhydra.barracuda.admin.events.*;
34 import org.enhydra.barracuda.admin.xmlc.*;
35 import org.enhydra.barracuda.core.comp.*;
36 import org.enhydra.barracuda.core.event.*;
37 import org.enhydra.barracuda.core.event.helper.*;
38 import org.enhydra.barracuda.plankton.data.*;
39 import org.enhydra.barracuda.plankton.http.*;
40
41 /**
42  * This mini-app is can be used to administer Barracuda applications
43  */

44 public class BarracudaAdmin extends DefaultEventGateway {
45
46     //public constants
47
protected static final Logger logger = Logger.getLogger(BarracudaAdmin.class.getName());
48
49     public static String JavaDoc DEFAULT_ADMIN_PROPS = "org.enhydra.barracuda.admin.AdminDefs";
50
51     private static final String JavaDoc CMD_STR = "$cmd";
52     private static final String JavaDoc CMD_RESULT = "$cmd_result";
53     private static String JavaDoc sep = System.getProperty("line.separator");
54
55     protected ResourceBundle rb = null;
56     protected Class JavaDoc templateClass = AdminHTML.class;
57     protected Map cmdMap = new HashMap();
58
59     //this defines the various event handlers
60
private ListenerFactory getAdminFactory = new DefaultListenerFactory() {public BaseEventListener getInstance() {return new GetAdminHandler();} public String JavaDoc getListenerID() {return getID(GetAdminHandler.class);}};
61     private ListenerFactory renderAdminFactory = new DefaultListenerFactory() {public BaseEventListener getInstance() {return new RenderAdminHandler();} public String JavaDoc getListenerID() {return getID(RenderAdminHandler.class);}};
62
63     //------------------- BarracudaAdmin ------------------------
64
/**
65      * Public constructor
66      */

67     public BarracudaAdmin() {
68         //specify who's interested in what
69
specifyLocalEventInterests(getAdminFactory, GetAdmin.class);
70         specifyLocalEventInterests(renderAdminFactory, RenderAdmin.class);
71         
72         //setup the default admin file
73
setAdminFile(DEFAULT_ADMIN_PROPS);
74     }
75
76     //------------------------------------------------------------
77
// Model 2 - Controller Event Handlers
78
//------------------------------------------------------------
79
/**
80      * GetAdminHandler - handle the request to get the config
81      * screen.
82      */

83     class GetAdminHandler extends DefaultBaseEventListener {
84         public void handleControlEvent(ControlEventContext context) throws EventException, ServletException, IOException {
85             //check to see if there are any commands associated with the request
86
String JavaDoc cmdParm = context.getRequest().getParameter(CMD_STR);
87             Object JavaDoc cmdResult = null;
88             if (cmdParm!=null) {
89                 Object JavaDoc o = cmdMap.get(cmdParm);
90                 if (o!=null) {
91                     //now that we know we have a valid command, we need to
92
//handle it according to its type...
93

94                     //...if its an actual command
95
if (o instanceof TargetCommand) {
96                         TargetCommand command = (TargetCommand) o;
97                         cmdResult = command.handleCommand();
98                     
99                     //...otherwise it must be a URL
100
} else if (o instanceof TargetURL) {
101                         TargetURL turl = (TargetURL) o;
102                         cmdResult = turl.handleURL();
103                     }
104                 }
105             }
106
107             //forward control to the renderer
108
context.putState(CMD_RESULT, cmdResult);
109             context.getQueue().addEvent(new RenderAdmin());
110         }
111     }
112     
113
114
115     //------------------------------------------------------------
116
// Model 2 - View Event Handlers
117
//------------------------------------------------------------
118
/**
119      * RenderAdminHandler - this is where we handle any RenderAdmin
120      * event and actually generate the view.
121      */

122     class RenderAdminHandler extends BTemplateViewHandler {
123         public Object JavaDoc getTemplateModels() {return new LocalTemplateModel();}
124         public Class JavaDoc getTemplateClass() {return templateClass;}
125     }
126     
127     
128     //------------------------------------------------------------
129
// Components - TemplateModel
130
//------------------------------------------------------------
131
/**
132      * LocalTemplateModel
133      */

134     class LocalTemplateModel extends AbstractTemplateModel {
135         int cntr = -1;
136         int max = 5;
137     
138         //register the model by name
139
public String JavaDoc getName() {return "Admin";}
140
141         //provide items by key
142
public Object JavaDoc getItem(String JavaDoc key) {
143             ViewContext vc = getViewContext();
144             logger.debug("getItem, key: "+key);
145             
146             //start by looking for the key in the resource bundle
147
if (rb!=null) {
148                 //look for the url key in the resource bundle;
149
String JavaDoc url = null;
150                 try {url = rb.getString(key+".url");}
151                 catch (MissingResourceException e) {}
152                 
153                 //if we find a url param, assume we are dealing with a url;
154
//store the url and return a link with the key as a
155
//cmd parameter
156
if (url!=null) {
157                     logger.debug("found key: "+url);
158                     TargetURL turl = new TargetURL();
159                     turl.url = url;
160                     try {turl.params = rb.getString(key+".params");}
161                     catch (MissingResourceException e) {}
162                     try {turl.method = rb.getString(key+".method");}
163                     catch (MissingResourceException e) {
164                         try {turl.method = rb.getString("Default.method");}
165                         catch (MissingResourceException e2) {}
166                     }
167                     try {turl.user = rb.getString(key+".user");}
168                     catch (MissingResourceException e) {
169                         try {turl.user = rb.getString("Default.user");}
170                         catch (MissingResourceException e2) {}
171                     }
172                     try {turl.pwd = rb.getString(key+".pwd");}
173                     catch (MissingResourceException e) {
174                         try {turl.pwd = rb.getString("Default.pwd");}
175                         catch (MissingResourceException e2) {}
176                     }
177 //System.out.println("URL:"+turl);
178
cmdMap.put(key, turl);
179                     BLink blink = new BLink(null, new GetAdmin());
180                     blink.setParam(CMD_STR, key);
181                     return blink;
182                     
183                 //if not found, look for cmd
184
} else {
185                     TargetCommand command = new TargetCommand();
186                     try {command.cmd = rb.getString(key+".cmd");}
187                     catch (MissingResourceException e) {}
188                     if (command.cmd!=null) {
189                         logger.debug("found cmd: "+command.cmd);
190                         command.path = new File(rb.getString(key+".path"));
191 //System.out.println("Cmd:"+command);
192
cmdMap.put(key, command);
193                         BLink blink = new BLink(null, new GetAdmin());
194                         blink.setParam(CMD_STR, key);
195                         return blink;
196                     }
197                 }
198             } else {
199                 logger.warn("resource bundle missing");
200             }
201             
202             //if we didn't find the key in the resource bundle, handle normally
203
if (key.equals("CommandResults")) {
204                 EventContext ec = vc. getEventContext();
205                 Object JavaDoc cmdResult = ec.getState(CMD_RESULT);
206                 if (cmdResult==null) {
207                     return "";
208                 } else if (cmdResult instanceof List) {
209                     List l = (List) cmdResult;
210                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(500);
211                     for (int i=0; i<l.size(); i++) {
212                         sb.append(l.get(i)+sep);
213                     }
214                     return sb.toString();
215                 } else if (cmdResult instanceof Exception JavaDoc) {
216                     StringWriter sw = new StringWriter();
217                     ((Exception JavaDoc) cmdResult).printStackTrace(new PrintWriter(sw));
218                     return sw.toString();
219                 } else {
220                     return cmdResult.toString();
221                 }
222             } else {
223                 return super.getItem(key);
224             }
225         }
226     }
227
228
229
230     //------------------------------------------------------------
231
// Utility Stuff (overridable)
232
//------------------------------------------------------------
233
public void setAdminFile(String JavaDoc s) {
234         //first look for
235
try {
236             logger.info("setting admin file: "+s);
237             rb = ResourceBundle.getBundle(s);
238         } catch (Exception JavaDoc e) {
239             logger.error("Unable to locate resource bundle "+s+": "+e);
240         }
241     }
242
243     public void setTemplateClass(String JavaDoc s) {
244         try {
245             logger.info("setting template class: "+s);
246 //jrk_20020414.1_start
247
//Class.forName is java1. Since Java2, use
248
//Thread.currentThread().getContextClassLoader().loadClass("MyClass")
249
//This should fix some classloading issues in Engines with multiple
250
//class loaders (eg.. Tomcat-3.3.x and Tomcat-4.x.x)
251
//templateClass = Class.forName(s);
252
templateClass = Thread.currentThread().getContextClassLoader().loadClass(s);
253 //jrk_20020414.1_end
254
} catch (Exception JavaDoc e) {
255             logger.warn("Unable to locate class:"+s);
256             logger.warn("Using "+templateClass+" instead");
257         }
258     }
259
260     class TargetCommand {
261         public File path = null;
262         public String JavaDoc cmd = null;
263         
264         public Object JavaDoc handleCommand() {
265             logger.info("Executing cmd: "+this);
266             try {
267                 Process JavaDoc p = Runtime.getRuntime().exec(cmd, null, path);
268 // Process p = Runtime.getRuntime().exec("E:/WebProjects/lutris/cvs/Barracuda/src/ant.bat admin.sample1", null, path);
269
List results = new ArrayList(100);
270                 BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
271                 while (true) {
272                     String JavaDoc s = br.readLine();
273                     if (s==null) break;
274 // results.add(s);
275
while (true) {
276                         if (s.length()>132) {
277                             results.add(s.substring(0,132));
278                             s = s.substring(133);
279                         } else {
280                             results.add(s);
281                             break;
282                         }
283                     }
284                 }
285                 br.close();
286                 br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
287                 while (true) {
288                     String JavaDoc s = br.readLine();
289                     if (s==null) break;
290 // results.add(s);
291
while (true) {
292                         if (s.length()>132) {
293                             results.add(s.substring(0,132));
294                             s = s.substring(133);
295                         } else {
296                             results.add(s);
297                             break;
298                         }
299                     }
300                 }
301                 br.close();
302                 p.waitFor();
303                 logger.info("Exit status: "+p.exitValue());
304                 return results;
305             } catch (Exception JavaDoc e) {
306                 logger.error("Unexpected error executing cmd:"+e);
307                 e.printStackTrace();
308                 return e;
309             }
310         }
311         
312         public String JavaDoc toString() {
313             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(500);
314             sb.append("{path:"+path+" (exists="+path.exists()+") cmd:"+cmd);
315             return sb.toString();
316         }
317     }
318
319     class TargetURL {
320         public String JavaDoc url = null;
321         public String JavaDoc params = null;
322         public String JavaDoc method = "GET";
323         public String JavaDoc user = null;
324         public String JavaDoc pwd = null;
325         
326         public Object JavaDoc handleURL() {
327             logger.info("Retrieving url: "+this);
328             try {
329                 HttpRequester hr = new HttpRequester();
330                 Map props = null;
331                 if (params!=null) props = HttpConverter.cvtURLStringToMap (params, "&");
332                 hr.setRequest (url, method, props, user, pwd, null);
333                 hr.connect();
334                 List results = new ArrayList(100);
335                 String JavaDoc s;
336                 while ((s = hr.readLine())!=null) {
337 // results.add(s);
338
while (true) {
339                         if (s.length()>132) {
340                             results.add(s.substring(0,132));
341                             s = s.substring(133);
342                         } else {
343                             results.add(s);
344                             break;
345                         }
346                     }
347                 }
348                 hr.disconnect();
349                 return results;
350             } catch (Exception JavaDoc e) {
351                 e.printStackTrace();
352                 return e;
353             }
354         }
355
356         public String JavaDoc toString() {
357             return "{url:"+url+" params:"+params+" method:"+method+" user:"+user+" pwd:"+pwd+"}";
358         }
359     }
360
361     
362     
363     /**
364      * If you are having problems getting this to run, you can use this
365      * static main method for testing purposes. You'll need to modify the
366      * hardcoded values accordingly.
367      */

368     public static void main(String JavaDoc margs[]) {
369         new BarracudaAdmin().runTest();
370     }
371
372     public void runTest() {
373         TargetCommand tc = new TargetCommand();
374 /*
375         tc.path = new File("E:/WebProjects/lutris/cvs/Barracuda/src");
376         tc.args = new String[] {"ant.bat","admin.sample1"};
377         printTestResults(tc.handleCommand());
378 */

379         tc.path = new File("E:/WebProjects/lutris/cvs/Barracuda/src");
380         tc.cmd = "E:/WebProjects/lutris/cvs/Barracuda/src/ant.bat admin.sample1";
381         printTestResults(tc.handleCommand());
382 /*
383         TargetURL tu = new TargetURL();
384         tu.url = "http://cryder:8080/manager/list";
385         tu.params = null;
386         tu.user = "admin";
387         tu.pwd = "123123";
388         printTestResults(tu.handleURL());
389
390         tu.url = "http://cryder:8080/manager/reload?path=/examples";
391         printTestResults(tu.handleURL());
392 */

393     }
394     
395     public void printTestResults(Object JavaDoc cmdResult) {
396         System.out.println("Output...");
397         if (cmdResult instanceof List) {
398             List l = (List) cmdResult;
399             for (int i=0; i<l.size(); i++) {
400                 System.out.println(l.get(i));
401             }
402         } else if (cmdResult instanceof Exception JavaDoc) {
403             StringWriter sw = new StringWriter();
404             ((Exception JavaDoc) cmdResult).printStackTrace(new PrintWriter(sw));
405             System.out.println(sw.toString());
406         } else {
407             System.out.println(""+cmdResult);
408         }
409         System.out.println("");
410     }
411
412 }
Popular Tags