KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > deployment > main > DeployTool


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23  package com.sun.enterprise.tools.deployment.main;
24
25 import java.io.*;
26 import java.net.*;
27 import com.sun.enterprise.tools.deployment.backend.JarInstaller;
28 import com.sun.enterprise.tools.deployment.backend.DeploymentSessionImpl;
29 import com.sun.enterprise.tools.deployment.backend.DeploymentSession;
30 //import com.sun.enterprise.tools.deployment.ui.utils.UIConfig; //IASRI 4691307
31
import java.rmi.RemoteException JavaDoc;
32 import java.util.*;
33 import java.util.zip.*;
34 import java.util.jar.*;
35 import com.sun.ejb.sqlgen.DBInfo;
36 import com.sun.ejb.sqlgen.SQLGenerator;
37 import com.sun.enterprise.tools.packager.ComponentPackager;
38 import com.sun.enterprise.util.LocalStringManagerImpl;
39 import com.sun.enterprise.util.NotificationEvent;
40 import com.sun.enterprise.util.FileUtil;
41
42 import com.sun.enterprise.deployment.xml.*;
43 import com.sun.enterprise.deployment.*;
44
45 /** The master object of the J2EE deployment tool.
46 * @author Danny Coward
47 */

48
49 public class DeployTool {
50     private ApplicationManager applicationManager;
51     private StandAloneManager standaloneManager;
52     private ServerManager serverManager;
53     private ComponentPackager componentPackager;
54     private File workingDirectory;
55     private File toolHomeDirectory;
56     private static LocalStringManagerImpl localStrings =
57     new LocalStringManagerImpl(DeployTool.class);
58     public static final String JavaDoc HOME_DIR = ".assemblytool"; //IASRI 4691307 // NOI18N
59

60     private static DeployTool deployToolInstance = null;
61
62     /* eventually, this should be an externally configurable item */
63     public static final String JavaDoc UI_STARTUP_CLASS = "com.sun.enterprise.tools.deployment.ui.DT"; // NOI18N
64
protected UIFactory uiFactory = null;
65     
66     private String JavaDoc userdir = null;
67     /**
68      * Construct a new deploytool indicating whether this tool has a UI or not.
69      */

70     
71     //add an method for specifying userdir. IASRI 4691307
72
public DeployTool(boolean hasUI, String JavaDoc dir){
73         userdir = dir;
74         _deploytool(hasUI);
75     }
76     
77     
78     public DeployTool(boolean hasUI) {
79         _deploytool(hasUI);
80     }
81     
82     private void _deploytool(boolean hasUI){
83         
84     deployToolInstance = this;
85
86         //If user specify userdir, will set that to UIConfig so that getConfigDirectory() will return that.
87
// IASRI 4691307
88
/* cannot do this because server.xml excludes ui directory. Will cause problem to build.
89         if (userdir != null){
90                 UIConfig.setUserDir(userdir);
91         }
92          **/

93     this.uiFactory = createUIFactory(hasUI);
94     
95         if (this.uiFactory != null){
96         /* ui */
97             // IASRI 4691307
98
// If the server build.xml include the ui directory, we won't need to test userdir here.
99
// just call uiFactory.getConfigDirectory();
100
File cfgDir = null;
101             if (userdir == null){
102                 cfgDir = this.uiFactory.getConfigDirectory();
103             }else{
104                 cfgDir = new File(userdir);
105                 cfgDir.mkdirs();
106             }
107         File tmpDir = this.uiFactory.getTempDirectory();
108             System.out.println("user directory = " + cfgDir); // IASRI 4691307 info user. // NOI18N
109
System.out.println("temp directory = " + tmpDir); // IASRI 4691307 info user. // NOI18N
110
this.applicationManager = new ApplicationManager(cfgDir, tmpDir);
111         this.standaloneManager = new StandAloneManager(cfgDir, tmpDir);
112         this.serverManager = new ServerManager(cfgDir);
113         this.uiFactory.startUI();
114
115     } else {
116
117         /* non-ui */
118         File toolDir = this.getToolHomeDirectory();
119         File tempDir = this.getWorkingDirectory();
120             System.out.println("user directory = " + toolDir); // IASRI 4691307 info user. // NOI18N
121
System.out.println("temp directory = " + tempDir); // IASRI 4691307 info user. // NOI18N
122
this.applicationManager = new ApplicationManager(toolDir, tempDir);
123         this.standaloneManager = new StandAloneManager(toolDir, tempDir);
124         this.serverManager = new ServerManager(toolDir);
125
126     }
127
128     }
129
130     public static DeployTool getDeployToolInstance() {
131     // The created DeployTool instance is needed by the deploytool ui.
132
// This method allows the ui to obtain the instance.
133
return deployToolInstance;
134     }
135
136     /* load ui classes if UI is requested */
137     protected static UIFactory createUIFactory(boolean hasUI) {
138
139     if (hasUI) {
140
141         try {
142
143             /* locate the class (make sure it's a UIFactory) */
144             Class JavaDoc uiFactoryClass = Class.forName(UI_STARTUP_CLASS);
145             if (!UIFactory.class.isAssignableFrom(uiFactoryClass)) {
146                 throw new ClassCastException JavaDoc("Class does not implement UIFactory"); // NOI18N
147
}
148
149             /* instantiate/initialize ui */
150             return (UIFactory)uiFactoryClass.newInstance();
151
152         } catch (Throwable JavaDoc t) {
153
154             System.out.println(localStrings.getLocalString(
155             "enterprise.tools.deployment.main.error_creating_ui",
156             "Unable to create UI: " + t));
157
158         }
159
160     }
161
162     return null;
163
164     }
165
166     /**
167      * Return a generated Application object given a module file
168      */

169     public Application deployStandaloneModule(File moduleFile)
170         throws Exception JavaDoc {
171
172         // derive an app name
173
File tmpDir = FileUtil.getTempDirectory();
174         String JavaDoc appName = "app." + moduleFile.getName().replace('.', '_'); // NOI18N
175
File appFile = new File(tmpDir, appName + ".ear"); // NOI18N
176
int i = 0;
177         while (appFile.exists()) {
178             i++;
179         appFile = new File(tmpDir, appName + "_" + i + ".ear"); // NOI18N
180
}
181         // update appName based on appFile
182
if (i > 0) {
183             appName = appName + "_" + i; // NOI18N
184
}
185         appFile.deleteOnExit();
186         Application app = new Application(appName, appFile);
187         if (EjbBundleArchivist.isEjbBundle(moduleFile)) {
188             app.addEjbJarFile(moduleFile);
189         } else if (WebBundleArchivist.isWebBundle(moduleFile)) {
190             app.addWebJarFile(moduleFile);
191         } else if (ApplicationClientArchivist.isApplicationClientJar(moduleFile)) {
192             app.addAppClientJarFile(moduleFile);
193         } else {
194             throw new IllegalArgumentException JavaDoc("Unsupported module type: " + // NOI18N
195
moduleFile);
196         }
197         return app;
198     }
199
200     // internal API for CTS harness, should go when they start using public interfaces
201
public void deploy(Application application, String JavaDoc serverName, DeploymentSession deploymentSession, File clientCodeFile)
202         throws Exception JavaDoc
203     {
204         deploy(application.getName(), application.getApplicationArchivist().getApplicationFile(), serverName, deploymentSession, clientCodeFile);
205     }
206     
207     public void deploy(String JavaDoc applicationName, File appArchiveFile,
208     String JavaDoc serverName, DeploymentSession deploymentSession, File clientCodeFile)
209     throws Exception JavaDoc {
210             
211     System.out.println(localStrings.getLocalString(
212         "enterprise.tools.deployment.main.deployapplicationfileonserversaveasclientjar",
213         "Deploy the application in {0} on the server {1} saving the client jar as {2}",
214         new Object JavaDoc[] { appArchiveFile, serverName, clientCodeFile }));
215     Object JavaDoc[] msg = { applicationName, serverName };
216     // byte[] clientCode = null;
217
String JavaDoc clientCode = null;
218     Log.print(this,localStrings.getLocalString(
219         "enterprise.tools.deployment.main.deploytool.deploy_command",
220         "Deploy {0} on {1}", msg));
221     JarInstaller backend = this.getServerManager().getServerForName(serverName);
222     DeploymentSession deploymentSessionToUse = null;
223     if (deploymentSession == null) {
224         deploymentSessionToUse = this.getServerManager().createDeploymentSession(serverName);
225     } else {
226         deploymentSessionToUse = deploymentSession;
227     }
228     
229     FileInputStream fis = new FileInputStream(appArchiveFile);
230     DataInputStream dis = new DataInputStream(fis);
231     byte[] jarData = new byte[(int) appArchiveFile.length()];
232     dis.readFully(jarData);
233     dis.close();
234     fis.close();
235     clientCode = backend.deployApplication(jarData, applicationName, deploymentSessionToUse);
236     Log.print(this, localStrings.getLocalString(
237                             "enterprise.tools.deployment.main.clientcodeat",
238                             "client code at {0}", new Object JavaDoc[] {clientCode}));
239     if (clientCode != null && clientCodeFile != null) {
240         writeClientJarToFile(clientCode, clientCodeFile);
241         deploymentSessionToUse.notification(new NotificationEvent(this, DeploymentSession.CLIENT_CODE_RETURNED, this));
242         deploymentSessionToUse.setStatusMessage(localStrings.getLocalString(
243                                         "enterprise.tools.deployment.main.clientcodefordeployedapplicationsavedtofile",
244                                         "Client code for the deployed application {0} saved to {1}", new Object JavaDoc[] {applicationName, clientCodeFile}));
245     }
246     }
247     
248     private void writeClientJarToFile(String JavaDoc clientCode,
249                 File clientCodeFile ) throws IOException {
250     URL u = new URL(clientCode);
251     HttpURLConnection http = (HttpURLConnection) u.openConnection();
252     int code = http.getResponseCode();
253     if(code != 200) {
254         System.out.println(localStrings.getLocalString(
255                                "enterprise.tools.deployment.main.cannotdownloadURL",
256                                "Cannot download URL {0}", new Object JavaDoc[] {clientCode}));
257         System.out.println(localStrings.getLocalString(
258                                "enterprise.tools.deployment.main.status",
259                                "Status: {0}", new Object JavaDoc[] {new Integer JavaDoc(code)}));
260         throw new IOException(localStrings.getLocalString(
261                                   "enterprise.tools.deployment.main.cannotdownloadURL",
262                                   "Cannot download URL {0}", new Object JavaDoc[] {clientCode}));
263     }
264     BufferedInputStream is = new BufferedInputStream(http.getInputStream());
265     FileOutputStream fos = new FileOutputStream(clientCodeFile);
266     int len = 0;
267     int contentLength = http.getContentLength();
268     // System.out.println("CONTENT LENGTH:" + contentLength);
269
byte[] buf = new byte[contentLength+1];
270     while((len = is.read(buf)) != -1)
271         fos.write(buf, 0, len);
272     }
273
274     private void saveAsBytes(byte[] data, File file) throws IOException {
275     if (data == null) {
276         throw new IOException(localStrings.getLocalString(
277                                   "enterprise.tools.deployment.main.nulldataforclientcodefile",
278                                   "null data for client code file"));
279     }
280     FileOutputStream fileStream = new FileOutputStream(file);
281     fileStream.write(data, 0, data.length);
282     fileStream.close();
283     }
284     
285     /** Parse the given runtime information file and update the given application
286     * with its data.
287     */

288     public void setRuntimeDeploymentInfo(Application application, File runtimeDeploymentInfo) throws Exception JavaDoc {
289     //ApplicationArchivist archivist = new ApplicationArchivist();
290
FileInputStream fis = new FileInputStream(runtimeDeploymentInfo);
291     RuntimeDescriptorNode node = (RuntimeDescriptorNode) RuntimeDescriptorNode.readRuntimeDescriptorNodes(fis).elementAt(0);
292     node.updateRuntimeInformation(application);
293     this.getApplicationManager().saveApplication(application);
294     
295     Object JavaDoc[] msg = {application.getName()};
296     Log.print(this, localStrings.getLocalString( "enterprise.tools.deployment.main.deploytool.setruntime_command", "Done setting runtime deployment information on {0} to: {1}", msg));
297     }
298   
299     /** Open the given application from the supplied filename and update any of the CMP entity beans therein
300     * with default generated SQL statements for the persistent methods from the datdbases running
301     * on the given server. Use overwrite to desructively overwrite existing SQL statements.
302     */

303     public void doGenerateSQL(String JavaDoc applicationFilename, String JavaDoc serverName, boolean overWrite) throws Exception JavaDoc
304     {
305     DBInfo dbInfo = this.getServerManager().getDBInfo(serverName);
306     Application application = ApplicationArchivist.openAT( //bug# 4774785; 4691307
307
new File(applicationFilename));
308
309     Iterator itr = application.getEjbBundleDescriptors().iterator();
310     while ( itr.hasNext() ) {
311         EjbBundleDescriptor ebd = (EjbBundleDescriptor)itr.next();
312
313             SQLGenerator.generateSQL(ebd, ebd.getCMPResourceReference(),
314                                      overWrite, dbInfo);
315     }
316
317     application.getApplicationArchivist().save(application.getApplicationArchivist().getApplicationFile(), true);
318     System.out.println(localStrings.getLocalString(
319                                "enterprise.tools.deployment.main.donegeneratingSQL",
320                                "Done generating SQL"));
321     }
322
323
324     public ComponentPackager getComponentPackager() {
325     if (this.componentPackager == null) {
326         this.componentPackager = new ComponentPackager();
327     }
328     return this.componentPackager;
329     }
330     
331     /** Gets the object responsible for managing applications. */
332     public ApplicationManager getApplicationManager() {
333     return applicationManager;
334     }
335         
336     /** Gets the object responsible for managing stand-alone objects. */
337     public StandAloneManager getStandAloneManager() {
338     return standaloneManager;
339     }
340
341     /** Gets the object responsible for managing servers. */
342     public ServerManager getServerManager() {
343     return serverManager;
344     }
345     
346     /**
347     * Return the working directory of the tool.
348     */

349     
350     public File getWorkingDirectory() {
351     // this give /var/tmp ! which does not seem to be writable
352
//String temp = System.getProperty("java.io.tmpdir");
353
//if (temp == null) {
354
// temp = "/tmp";
355
//}
356
//return new File(temp, "jpedeploytool");
357

358     String JavaDoc home = System.getProperty("user.home");
359     if (home == null) {
360         home = ""; // NOI18N
361
}
362     File tmp = new File(home, "tmp"); // NOI18N
363
tmp.mkdirs();
364     return tmp;
365     }
366
367     /** Gets the user home directory.
368     */

369     public File getToolHomeDirectory() {
370         
371     
372         
373         // IASRI 4691307 for supporting -userdir option
374
//test to see if userdir was set, if so use that instead of home directory.
375

376         //String home = System.getProperty("user.home");
377
//if (home == null) {
378
//home = "";
379
//}
380
//return new File(home, HOME_DIR);
381

382         File homedir;
383         if (userdir != null){
384             homedir = new File(userdir);
385         }else{
386             String JavaDoc home = System.getProperty("user.home");
387             if (home == null) {
388                 home = ""; // NOI18N
389
}
390             homedir= new File(home, HOME_DIR);
391         }
392         homedir.mkdirs();
393         return homedir;
394     // end of IASRI 4691307
395
}
396     
397     /** Formatted version of me as a String.*/
398     public String JavaDoc toString() {
399     return "Deploy Tool"; // NOI18N
400
}
401     
402     // testing only
403

404     static public void main(String JavaDoc[] args) {
405         try {
406             DeployTool tool = new DeployTool(false);
407             Application app = tool.deployStandaloneModule
408                 (new File("/home/tcng/Test/ejb.jar")); // NOI18N
409
System.err.println(app.toString());
410             app = tool.deployStandaloneModule
411                 (new File("/home/tcng/Test/app.jar")); // NOI18N
412
System.err.println(app.toString());
413             app = tool.deployStandaloneModule
414                 (new File("/home/tcng/Test/web.war")); // NOI18N
415
System.err.println(app.toString());
416             
417         } catch (Exception JavaDoc ex) {
418             ex.printStackTrace();
419         }
420     }
421
422 }
423
Popular Tags