KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > applications > server > ServerLauncher


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.applications.server;
21
22 import java.io.ByteArrayInputStream JavaDoc;
23 import java.io.ByteArrayOutputStream JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Vector JavaDoc;
34
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37 import org.jdom.Element;
38 import org.jdom.JDOMException;
39 import org.jdom.output.XMLOutputter;
40
41 import com.sslexplorer.applications.ApplicationShortcut;
42 import com.sslexplorer.boot.PropertyDefinition;
43 import com.sslexplorer.boot.Util;
44 import com.sslexplorer.boot.XMLElement;
45 import com.sslexplorer.core.CoreException;
46 import com.sslexplorer.core.stringreplacement.SessionInfoReplacer;
47 import com.sslexplorer.core.stringreplacement.VariableReplacement;
48 import com.sslexplorer.extensions.ExtensionDescriptor;
49 import com.sslexplorer.extensions.actions.UndefinedParameterException;
50 import com.sslexplorer.security.SessionInfo;
51
52 /**
53  * This class do the almost the same things as agent application launcher. It
54  * check the extemsion file and do some replacement.
55  *
56  * @author Sebastien Belin <a HREF="mailto: seb@3sp.com">&lt;seb@3sp.com&gt;</a>
57  *
58  */

59 public class ServerLauncher {
60
61     File JavaDoc installDir;
62
63     File JavaDoc sharedDir;
64
65     String JavaDoc typeName;
66
67     String JavaDoc name;
68
69     public String JavaDoc exitMessage = "";
70
71     long totalBytesToDownload = 0;
72
73     Vector JavaDoc filesToDownload = new Vector JavaDoc();
74
75     Hashtable JavaDoc sharedFilesToDowload = new Hashtable JavaDoc();
76
77     protected Map JavaDoc<String JavaDoc, String JavaDoc> parameters;
78
79     Hashtable JavaDoc descriptorParams = new Hashtable JavaDoc();
80
81     boolean debug = false;
82
83     ApplicationServerType type;
84
85     int shortcutId;
86
87     Hashtable JavaDoc replacements = new Hashtable JavaDoc();
88
89     Vector JavaDoc transformations = new Vector JavaDoc();
90
91     String JavaDoc dependencies;
92
93     ExtensionDescriptor descriptor;
94
95     SessionInfo session;
96
97     ApplicationShortcut shortcut;
98
99     static Log log = LogFactory.getLog(ServerLauncher.class);
100
101     public ServerLauncher(ExtensionDescriptor descriptor, SessionInfo session,
102             ApplicationShortcut shortcut, Map JavaDoc<String JavaDoc, String JavaDoc> parameters) {
103         this.descriptor = descriptor;
104         this.session = session;
105         this.shortcut = shortcut;
106         this.parameters = parameters;
107     }
108
109     public int getShortcutId() {
110         return shortcutId;
111     }
112
113     public void setDebug(boolean debug) {
114         this.debug = debug;
115     }
116
117     public ApplicationServerType getApplicationType() {
118         return type;
119     }
120
121     private String JavaDoc processParameters(SessionInfo sessionInfo, Element element,
122             ExtensionDescriptor app, final ApplicationShortcut shortcut)
123             throws UndefinedParameterException, JDOMException, IOException JavaDoc,
124             CoreException {
125
126         List JavaDoc params = element.getChildren("parameter");
127
128         for (Iterator JavaDoc it = params.iterator(); it.hasNext();) {
129             Element p = (Element) it.next();
130
131             String JavaDoc name = p.getAttribute("name").getValue();
132             String JavaDoc value = (String JavaDoc) shortcut.getParameters().get(name);
133
134             if (value == null) {
135                 value = app.getParameterDefinition(name).getDefaultValue();
136                 if (value == null
137                         || value.equals(PropertyDefinition.UNDEFINED_PARAMETER)) {
138                     throw new UndefinedParameterException("Parameter " + name
139                             + " is undefined");
140                 }
141             }
142
143             VariableReplacement r = new VariableReplacement();
144             r.setApplicationShortcut(app, null);
145             r.setSession(sessionInfo);
146             p.setAttribute("value", r.replace(value));
147         }
148
149         XMLOutputter output = new XMLOutputter();
150         ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
151         output.output(element, out);
152
153         String JavaDoc xml = new String JavaDoc(out.toByteArray());
154
155         params = element.getChildren("parameter");
156
157         Map JavaDoc parameters = new HashMap JavaDoc();
158         for (Iterator JavaDoc it = params.iterator(); it.hasNext();) {
159             Element p = (Element) it.next();
160             parameters.put(p.getAttributeValue("name"), p
161                     .getAttributeValue("value"));
162         }
163
164         VariableReplacement r = new VariableReplacement();
165         r.setApplicationShortcut(app, parameters);
166         r.setSession(sessionInfo);
167         String JavaDoc processed = r.replace(xml);
168
169         if (log.isDebugEnabled())
170             log.debug("Returning '" + processed + "'");
171         return processed;
172     }
173
174     public void prepare() throws IOException JavaDoc {
175
176         if (log.isDebugEnabled())
177             log.debug("Checking parameters");
178
179         XMLElement element = new XMLElement();
180         try {
181             element.parseFromReader(new InputStreamReader JavaDoc(
182                     new ByteArrayInputStream JavaDoc(processParameters(
183                             session,
184                             descriptor
185                                     .createProcessedDescriptorElement(session),
186                             descriptor, shortcut).getBytes())));
187         } catch (Exception JavaDoc e1) {
188             // TODO Auto-generated catch block
189
e1.printStackTrace();
190         }
191
192         if (log.isDebugEnabled())
193             log.debug("Received a response from server");
194
195         if (!element.getName().equals("application")
196                 && !element.getName().equals("error")
197                 && !element.getName().equals("extension")) {
198             throw new IOException JavaDoc(
199                     "URL does not point to an application descriptor");
200         } else if (element.getName().equals("error")) {
201             throw new IOException JavaDoc(element.getContent());
202         }
203
204         name = (String JavaDoc) element.getAttribute("extension");
205         if (name == null) {
206             name = (String JavaDoc) element.getAttribute("application");
207         }
208
209         typeName = (String JavaDoc) element.getAttribute("type");
210
211         try {
212             type = (ApplicationServerType) Class
213                     .forName(
214                             "com.sslexplorer.applications.types."
215                                     + (String.valueOf(typeName.charAt(0))
216                                             .toUpperCase() + typeName
217                                             .substring(1)) + "Type")
218                     .newInstance();
219         } catch (Throwable JavaDoc t) {
220             throw new IOException JavaDoc(
221                     "Failed to load the application description extension for application type of "
222                             + typeName + ".");
223         }
224
225         if (log.isDebugEnabled())
226             log.debug("Application name is " + name);
227
228         if (log.isDebugEnabled())
229             log.debug("Creating install folder");
230
231         installDir = File.createTempFile("server", "tmp");
232         installDir.delete();
233         installDir = new File JavaDoc(installDir.getParent(), installDir.getName()
234                 + "dir");
235         installDir.mkdirs();
236
237         if (log.isDebugEnabled())
238             log.debug("Installing to " + installDir.getAbsolutePath());
239
240         Enumeration JavaDoc e = element.enumerateChildren();
241
242         while (e.hasMoreElements()) {
243             XMLElement el = (XMLElement) e.nextElement();
244
245             if (el.getName().equalsIgnoreCase("files")) {
246                 processFiles(el);
247             } else if (el.getName().equalsIgnoreCase("parameter")) {
248                 addParameter(el);
249             } else if (el.getName().equalsIgnoreCase("messages")) {
250                 // Ignore as its a server side element
251
} else if (el.getName().equalsIgnoreCase("description")) {
252                 // Simply ignore.. should we throw an exception if an element is
253
// not known?
254
} else if (el.getName().equalsIgnoreCase("replacements")) {
255                 FileReplacement replacement = new FileReplacement(installDir);
256                 replacement.processReplacementXML(el, this);
257                 replacements.put(replacement.getId(), replacement);
258             } else if (processLauncherElement(el)) {
259                 // This allows us to override more element types in extended
260
// application launchers (i.e. registry parameters)
261
continue;
262             } else if (el.getName().equalsIgnoreCase("transform")) {
263                 ParameterTransformation trans = new ParameterTransformation(el,
264                         this);
265                 transformations.addElement(trans);
266             } else {
267                 type.prepare(this, null, el);
268             }
269         }
270
271         if (log.isDebugEnabled())
272             log.debug("Applying parameter transformations");
273
274         for (Enumeration JavaDoc ep = transformations.elements(); ep.hasMoreElements();) {
275             ParameterTransformation trans = (ParameterTransformation) ep
276                     .nextElement();
277             trans.processTransformation();
278         }
279
280         if (log.isDebugEnabled())
281             log.debug("Creating replacements");
282
283         for (Enumeration JavaDoc ep = replacements.elements(); ep.hasMoreElements();) {
284             FileReplacement replacement = (FileReplacement) ep.nextElement();
285             replacement.createReplacementsFile(this);
286         }
287
288         if (log.isDebugEnabled())
289             log
290                     .debug("Replacements created, preparation of launcher complete.");
291     }
292
293     protected boolean processLauncherElement(XMLElement e) {
294         return false;
295     }
296
297     public String JavaDoc getName() {
298         return name;
299     }
300
301     public File JavaDoc getInstallDir() {
302         return installDir;
303     }
304
305     public void start() {
306         type.start();
307     }
308
309     private void addParameter(XMLElement e) throws IOException JavaDoc {
310         String JavaDoc parameter = (String JavaDoc) e.getAttribute("name");
311         String JavaDoc value = (String JavaDoc) e.getAttribute("value");
312         if (log.isDebugEnabled())
313             log.debug("Adding parameter " + parameter + " with value of "
314                     + value);
315         descriptorParams.put(parameter, SessionInfoReplacer.replace(session,
316                 value));
317     }
318
319     public void addParameter(String JavaDoc parameter, String JavaDoc value) {
320
321         if (log.isDebugEnabled())
322             log.debug("Adding parameter " + parameter + " with value of "
323                     + value);
324
325         descriptorParams.put(parameter, value);
326     }
327
328     public String JavaDoc replaceTokens(String JavaDoc str) {
329         str = replaceAllTokens(str, "${client:installDir}", installDir
330                 .getAbsolutePath());
331         for (Enumeration JavaDoc e = descriptorParams.keys(); e.hasMoreElements();) {
332             String JavaDoc key = (String JavaDoc) e.nextElement();
333             String JavaDoc val = (String JavaDoc) descriptorParams.get(key);
334             str = replaceAllTokens(str, "${param:" + key + "}", val);
335         }
336         return str;
337     }
338
339     static String JavaDoc replaceAllTokens(String JavaDoc source, String JavaDoc token, String JavaDoc value) {
340         int idx;
341
342         do {
343             idx = source.indexOf(token);
344
345             if (idx > -1) {
346                 source = source.substring(0, idx)
347                         + value
348                         + ((source.length() - idx <= token.length()) ? ""
349                                 : source.substring(idx + token.length()));
350             }
351
352         } while (idx > -1);
353
354         return source;
355     }
356
357     private boolean isArgument(XMLElement e) {
358         return e.getName().equalsIgnoreCase("arg")
359                 || e.getName().equalsIgnoreCase("jvm");
360     }
361
362     public static boolean checkVersion(String JavaDoc applicationJDK) {
363
364         int[] applicationVersion = ServerLauncher.getVersion(applicationJDK);
365         int[] installedJREVersion = ServerLauncher.getVersion(System
366                 .getProperty("java.version"));
367
368         for (int i = 0; i < applicationVersion.length
369                 && i < installedJREVersion.length; i++) {
370             if (applicationVersion[i] > installedJREVersion[i])
371                 return false;
372         }
373
374         return true;
375     }
376
377     public static int[] getVersion(String JavaDoc version) {
378
379         int idx = 0;
380         int pos = 0;
381         int[] result = new int[0];
382         do {
383
384             idx = version.indexOf('.', pos);
385             int v;
386             if (idx > -1) {
387                 v = Integer.parseInt(version.substring(pos, idx));
388                 pos = idx + 1;
389             } else {
390                 try {
391                     int sub = version.indexOf('_', pos);
392                     if (sub == -1) {
393                         sub = version.indexOf('-', pos);
394                     }
395                     if (sub > -1) {
396                         v = Integer.parseInt(version.substring(pos, sub));
397                     } else {
398                         v = Integer.parseInt(version.substring(pos));
399                     }
400                 } catch (NumberFormatException JavaDoc ex) {
401                     // Ignore the exception and return what version we have
402
break;
403                 }
404             }
405             int[] tmp = new int[result.length + 1];
406             System.arraycopy(result, 0, tmp, 0, result.length);
407             tmp[tmp.length - 1] = v;
408             result = tmp;
409
410         } while (idx > -1);
411
412         return result;
413     }
414
415     public void processFiles(XMLElement element) throws IOException JavaDoc {
416         processFiles(element, null);
417     }
418
419     public void processFiles(XMLElement element, String JavaDoc app) throws IOException JavaDoc {
420
421         Enumeration JavaDoc en = element.enumerateChildren();
422         XMLElement e;
423
424         while (en.hasMoreElements()) {
425             e = (XMLElement) en.nextElement();
426             if (e.getName().equalsIgnoreCase("file")) {
427                 File JavaDoc f = descriptor.getFile(e.getContent());
428                 Util.copy(f, new File JavaDoc(installDir, e.getContent()));
429             } else if (e.getName().equalsIgnoreCase("if")) {
430
431                 try {
432                     if (type.checkFileCondition(e)) {
433                         processFiles(e, app);
434                     }
435                 } catch (IllegalArgumentException JavaDoc iae) {
436                     String JavaDoc parameter = (String JavaDoc) e.getAttribute("parameter");
437
438                     if (parameter != null) {
439                         String JavaDoc requiredValue = (String JavaDoc) e.getAttribute("value");
440                         boolean not = "true".equalsIgnoreCase(((String JavaDoc) e
441                                 .getAttribute("not")));
442
443                         // Check the parameter
444
String JavaDoc value = (String JavaDoc) descriptorParams.get(parameter);
445
446                         if ((!not && requiredValue.equalsIgnoreCase(value))
447                                 || (not && !requiredValue
448                                         .equalsIgnoreCase(value))) {
449                             processFiles(e, app);
450                         }
451
452                     } else
453                         throw new IOException JavaDoc(
454                                 "<if> element requires type specific attributes or parameter/value attributes");
455                 }
456
457             } else
458                 throw new IOException JavaDoc("Invalid element <" + e.getName()
459                         + "> found in <files>");
460         }
461
462     }
463
464     public Hashtable JavaDoc getDescriptorParams() {
465         return descriptorParams;
466     }
467 }
468
Popular Tags