KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > cli > commands > DeployCommand


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
24 package com.sun.enterprise.cli.commands;
25
26 import com.sun.enterprise.cli.framework.*;
27 import com.sun.enterprise.deployment.backend.DeploymentStatus;
28 import com.sun.enterprise.deployment.client.DeploymentFacility;
29 import com.sun.enterprise.deployment.client.DeploymentFacilityFactory;
30 import com.sun.enterprise.deployment.client.JESProgressObject;
31 import com.sun.enterprise.deployment.client.JESTarget;
32 import com.sun.enterprise.deployment.client.ServerConnectionIdentifier;
33 import com.sun.enterprise.deployment.deploy.shared.AbstractArchive;
34 import com.sun.enterprise.deployment.deploy.shared.Archive;
35 import com.sun.enterprise.deployment.deploy.shared.ArchiveFactory;
36 import com.sun.enterprise.deployment.util.DeploymentProperties;
37 import com.sun.enterprise.server.Constants;
38 import javax.enterprise.deploy.spi.Target JavaDoc;
39 import javax.management.ObjectName JavaDoc;
40
41 // jdk imports
42
import java.io.*;
43 import java.net.URI JavaDoc;
44 import java.net.URISyntaxException JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.Properties JavaDoc;
49
50 /**
51  * This is the Deploy command
52  * @version $Revision: 1.6 $
53  */

54 public class DeployCommand extends S1ASCommand
55 {
56     private static final String JavaDoc TARGET_OPTION = "target";
57     private static final String JavaDoc CONTEXT_ROOT_OPTION = "contextroot";
58     private static final String JavaDoc FORCE_OPTION = "force";
59     private static final String JavaDoc PRECOMPILE_JSP_OPTION = "precompilejsp";
60     private static final String JavaDoc VERIFY_OPTION = "verify";
61     private static final String JavaDoc UPLOAD_OPTION = "upload";
62     private static final String JavaDoc ENABLED_OPTION = "enabled";
63     private static final String JavaDoc COMPONENT_NAME = "name";
64     private static final String JavaDoc RETRIEVE_DIR = "retrieve";
65     private static final String JavaDoc VIRTUALSERVERS_OPTION = "virtualservers";
66     private static final String JavaDoc DB_VENDOR_NAME_OPTION = "dbvendorname";
67     private static final String JavaDoc CREATE_TABLES_OPTION = "createtables";
68     private static final String JavaDoc DROP_AND_CREATE_TABLES_OPTION = "dropandcreatetables";
69     private static final String JavaDoc UNIQUE_TABLENAMES_OPTION = "uniquetablenames";
70     private static final String JavaDoc DEPLOYMENTPLAN_OPTION = "deploymentplan";
71     private static final String JavaDoc AVAILABILITY_ENABLED_OPTION= "availabilityenabled";
72     private static final String JavaDoc GENERATE_RMI_STUBS_OPTION = "generatermistubs";
73     private static final String JavaDoc LIBRARIES_OPTION = "libraries";
74
75     private String JavaDoc filePath = null;
76     private String JavaDoc serverFilePath = null;
77     private boolean isUpload = false;
78     private String JavaDoc componentName = null;
79
80     /**
81      * An abstract method that Executes the command
82      * @throws CommandException
83      */

84     public void runCommand()
85         throws CommandException, CommandValidationException
86     {
87         validateOptions();
88
89         DeploymentFacility df = DeploymentFacilityFactory.getDeploymentFacility();
90         ServerConnectionIdentifier conn = createServerConnectionIdentifier(
91             getHost(), getPort(), getUser(), getPassword());
92         df.connect(conn);
93
94         //prepare data
95
final String JavaDoc targetName = getOption(TARGET_OPTION);
96         
97         final String JavaDoc deploymentPlan = getOption(DEPLOYMENTPLAN_OPTION);
98         JESProgressObject progressObject = null;
99     try
100         {
101             AbstractArchive arch = (new ArchiveFactory()).openArchive(filespecToJarURI(filePath));
102             AbstractArchive plan = null;
103             if (deploymentPlan != null) {
104                 plan = (new ArchiveFactory()).openArchive(filespecToJarURI(deploymentPlan));
105             }
106             //value of the map is String only
107
Map JavaDoc deployOptions = createDeploymentProperties();
108
109             if (df.isConnected())
110             {
111                 Target[] targets = df.createTargets(new String JavaDoc[]{targetName});
112                 if (targets == null)
113                 {
114                     //CLILogger.getInstance().printError(getLocalizedString("InvalidTarget"));
115
throw new CommandException(getLocalizedString("InvalidTarget", new Object JavaDoc[] {targetName}));
116                 }
117
118                 progressObject = df.deploy(targets, arch, plan, deployOptions);
119             } else
120             {
121                 CLILogger.getInstance().printError(
122                                    getLocalizedString("CouldNotConnectToDAS"));
123             }
124         }
125         catch (Exception JavaDoc e)
126         {
127             //e.printStackTrace();
128
if (e.getLocalizedMessage() != null)
129                 CLILogger.getInstance().printDetailMessage(
130                     e.getLocalizedMessage());
131
132             throw new CommandException(getLocalizedString(
133                 "CommandUnSuccessful", new Object JavaDoc[] {name} ), e);
134         }
135
136         
137         DeploymentStatus status = df.waitFor(progressObject);
138         final String JavaDoc statusString = status.getStageStatusMessage();
139
140         if (status != null && status.getStatus() == DeploymentStatus.FAILURE) {
141             checkDeployStatus(status, statusString);
142         }
143
144         final String JavaDoc retrievePath = getOption(RETRIEVE_DIR);
145         if (retrievePath != null){
146             try {
147                 CLILogger.getInstance().printDebugMessage("componentName = " + componentName +
148                                                   " retrievePath = " + retrievePath);
149                 final String JavaDoc fileName = df.downloadFile(new File(retrievePath), componentName, null);
150                 CLILogger.getInstance().printDebugMessage("downloaded stubs to : " + fileName );
151         }
152         catch(Exception JavaDoc e){
153             throw new CommandException((getLocalizedString(
154                     "InvalidValueInOption", new Object JavaDoc[] {RETRIEVE_DIR,
155                     retrievePath})) + "\n"+ e.getLocalizedMessage());
156         }
157     }
158
159         if (status != null && status.getStatus() == DeploymentStatus.WARNING) {
160             CLILogger.getInstance().printDetailMessage(getLocalizedString(
161                 "CommandSuccessfulWithMsg",
162                 new Object JavaDoc[] {name, statusString}));
163         } else {
164             CLILogger.getInstance().printDetailMessage(getLocalizedString(
165                                                        "CommandSuccessful",
166                                                        new Object JavaDoc[] {name} ) );
167         }
168     }
169
170     /**
171      *Convert a file spec into a jar URI.
172      *@param filePath to be converted into a URI
173      *@return URI with scheme=jar for the file
174      */

175     private URI JavaDoc filespecToJarURI(String JavaDoc fileSpec) throws URISyntaxException JavaDoc {
176         File archiveFile = new File(fileSpec);
177         String JavaDoc prefix = (archiveFile.isDirectory()) ? "file" : "jar";
178         URI JavaDoc archiveFileURI = archiveFile.toURI();
179         URI JavaDoc archiveJarURI = new URI JavaDoc(prefix, "" /* authority */, archiveFileURI.getSchemeSpecificPart(), null, null);
180         return archiveJarURI;
181     }
182
183     /**
184      * creates the DeployProperties which is used as a parameter to the
185      * deploy operation.
186      * @return Properties
187      */

188     private Map JavaDoc createDeploymentProperties()
189     {
190         final String JavaDoc virtualServers = getOption(VIRTUALSERVERS_OPTION);
191         final String JavaDoc contextRoot = getContextRoot();
192         final String JavaDoc dbVendorName = getOption(DB_VENDOR_NAME_OPTION);
193         final String JavaDoc createTable = getOption(CREATE_TABLES_OPTION);
194         final String JavaDoc dropCreateTable = getOption(DROP_AND_CREATE_TABLES_OPTION);
195         final String JavaDoc uniqueTableNames = getOption(UNIQUE_TABLENAMES_OPTION);
196         final String JavaDoc target = getOption(TARGET_OPTION);
197         final String JavaDoc libraries = getOption(LIBRARIES_OPTION);
198         
199         Properties props = new Properties();
200
201         if (props != null)
202             props.put(DeploymentProperties.TARGET, target);
203         
204         if (serverFilePath != null && isUpload)
205             props.put(DeploymentProperties.ARCHIVE_NAME, serverFilePath);
206         else if(filePath != null)
207             props.put(DeploymentProperties.ARCHIVE_NAME, filePath);
208
209
210         if(contextRoot != null)
211             props.put(DeploymentProperties.CONTEXT_ROOT, contextRoot);
212
213         if(virtualServers != null)
214             props.put(DeploymentProperties.VIRTUAL_SERVERS,
215                               virtualServers);
216
217         if(dbVendorName != null)
218             props.put(Constants.CMP_DB_VENDOR_NAME, dbVendorName);
219
220         if(createTable != null)
221             props.put(Constants.CMP_CREATE_TABLES, createTable);
222         
223         if(dropCreateTable != null)
224             props.put(Constants.CMP_DROP_AND_CREATE_TABLES, dropCreateTable);
225
226         if(uniqueTableNames != null)
227             props.put(Constants.CMP_UNIQUE_TABLE_NAMES, uniqueTableNames);
228
229         if(libraries != null)
230             props.put(DeploymentProperties.DEPLOY_OPTION_LIBRARIES_KEY, libraries);
231
232             //the following properties is either a required option/operand
233
//or it contains a default value in the CLIDescriptors.xml
234
//so do not neet to check for "null"
235
props.put(DeploymentProperties.NAME, componentName);
236
237         props.put(DeploymentProperties.VERIFY,
238                           getOption(VERIFY_OPTION));
239
240         props.put(DeploymentProperties.PRECOMPILE_JSP,
241                           getOption(PRECOMPILE_JSP_OPTION));
242
243         props.put(DeploymentProperties.ENABLE,
244                           getOption(ENABLED_OPTION));
245         
246         props.put(DeploymentProperties.FORCE,
247                           getOption(FORCE_OPTION));
248         
249         props.put(DeploymentProperties.AVAILABILITY_ENABLED,
250                           getOption(AVAILABILITY_ENABLED_OPTION));
251         
252         props.put(DeploymentProperties.GENERATE_RMI_STUBS,
253                           getOption(GENERATE_RMI_STUBS_OPTION));
254         
255         final String JavaDoc retrievePath = getOption(RETRIEVE_DIR);
256         if (retrievePath != null){
257             props.put(DeploymentProperties.CLIENTJARREQUESTED, "true");
258         };
259
260         return props;
261
262     }
263
264
265     /**
266        Check the deployment status returned from the backend deployment.
267        This method will iterate through the stages of the DeploymentStatus.
268        If the first stage fails then it's a j2eec phase failure.
269        CommandException will be thrown if j2eec phase failed.
270        The next stages are the associate, start phases. If the j2eec phase
271        passed but start phase failed then the deployment was successfull but
272        not loaded. The backend message will be displayed.
273        @param status - DeploymentStatus returned from the backend deployment.
274        @throws CommandException if j2eec phase failed.
275      */

276     private void checkDeployStatus(DeploymentStatus status,
277         String JavaDoc statusString) throws CommandException
278     {
279         if (status != null && status.getStatus() == DeploymentStatus.FAILURE) {
280             throw new CommandException(getLocalizedString(
281                 "CommandUnSuccessfulWithMsg", new Object JavaDoc[] {name,
282                 statusString} ));
283         }
284     }
285     
286     
287     /**
288      * An abstract method that validates the options
289      * on the specification in the xml properties file
290      * This method verifies for the correctness of number of
291      * operands and if all the required options are supplied by the client.
292      * @return boolean returns true if success else returns false
293      */

294     public boolean validateOptions() throws CommandValidationException
295     {
296         super.validateOptions();
297         if (getOption(CREATE_TABLES_OPTION) !=null &&
298             getOption(DROP_AND_CREATE_TABLES_OPTION) != null)
299             throw new CommandValidationException(getLocalizedString(
300                                                      "MutuallyExclusiveOption",
301                                                      new Object JavaDoc[] {CREATE_TABLES_OPTION,
302                                                      DROP_AND_CREATE_TABLES_OPTION
303                                                      }));
304
305         filePath = (String JavaDoc) getOperands().get(0);
306         isUpload = getOption(UPLOAD_OPTION)==null?false:getBooleanOption(UPLOAD_OPTION);
307         componentName = getComponentName();
308         return true;
309     }
310
311
312     /**
313      * get the context root from command option. If context root is null
314      * then it will get from the filepath in the operand.
315      * @param returns context root
316      */

317     private String JavaDoc getContextRoot()
318     {
319         String JavaDoc contextRoot = getOption(CONTEXT_ROOT_OPTION);
320         return contextRoot;
321     }
322
323     
324     /**
325      * get the component name. if component name is null then get it from
326      * the file path in the operand
327      * @throws CommandValidationException if could not get component name
328      */

329     private String JavaDoc getComponentName() throws CommandValidationException
330     {
331         String JavaDoc name = getOption(COMPONENT_NAME);
332         if (name == null)
333         {
334             name = getNameFromFilePath();
335         }
336             //if name is still null or empty then throw an exception
337
if ((name == null) || (name.equals("")))
338             throw new CommandValidationException(getLocalizedString("ComponentNameNull"));
339         return name;
340     }
341
342
343     /**
344      * get the file name from the filepath
345      * @return file name
346      */

347     private String JavaDoc getNameFromFilePath()
348     {
349         String JavaDoc fileNameOperand = (String JavaDoc) getOperands().get(0);
350         final String JavaDoc fileName = new File(fileNameOperand).getName();
351         int toIndex = fileName.lastIndexOf('.');
352         if (toIndex < 0)
353         {
354             toIndex = fileName.length();
355         }
356         return fileName.substring(0, toIndex);
357     }
358 }
359
Popular Tags