KickJava   Java API By Example, From Geeks To Geeks.

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


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 /*
25  * $Id: CreateDomainCommand.java,v 1.12 2006/02/06 06:11:14 km105526 Exp $
26  */

27
28 package com.sun.enterprise.cli.commands;
29
30 import com.sun.appserv.management.client.prefs.LoginInfo;
31 import com.sun.appserv.management.client.prefs.LoginInfoStore;
32 import com.sun.appserv.management.client.prefs.LoginInfoStoreFactory;
33 import com.sun.enterprise.cli.framework.CommandValidationException;
34 import com.sun.enterprise.cli.framework.CommandException;
35 import com.sun.enterprise.cli.framework.CLILogger;
36
37 import com.sun.enterprise.util.net.NetUtils;
38 import com.sun.enterprise.util.io.FileUtils;
39
40 import com.sun.enterprise.admin.servermgmt.DomainConfig;
41 import com.sun.enterprise.admin.servermgmt.DomainsManager;
42
43 // jdk imports
44
import java.io.File JavaDoc;
45
46 import java.util.Properties JavaDoc;
47 import java.util.StringTokenizer JavaDoc;
48
49
50
51 /**
52  * This is a local command that creates a new domain
53  * @version $Revision: 1.12 $
54  */

55 public class CreateDomainCommand extends BaseLifeCycleCommand
56 {
57     // constant variables for create-domain options
58
private static final String JavaDoc DOMAIN_PATH = "path";
59     private static final String JavaDoc INSTANCE_PORT = "instanceport";
60     private static final String JavaDoc DOCROOT = "docroot";
61     private static final String JavaDoc TEMPLATE = "template";
62     private static final String JavaDoc DOMAIN_PROPERTIES = "domainproperties";
63     private static final String JavaDoc CHECKPORTS_OPTION = "checkports";
64     private static final int DEFAULT_HTTPSSL_PORT = 8181;
65     private static final int DEFAULT_IIOPSSL_PORT = 3820;
66     private static final int DEFAULT_IIOPMUTUALAUTH_PORT = 3920;
67     private static final int DEFAULT_INSTANCE_PORT = 8080;
68     private static final int DEFAULT_JMS_PORT = 7676;
69     private static final String JavaDoc DEFAULT_JMS_USER = "admin";
70     private static final String JavaDoc DEFAULT_JMS_PASSWORD = "admin";
71     private static final int DEFAULT_IIOP_PORT = 3700;
72     private static final int DEFAULT_JMX_PORT = 8686;
73
74     public static String JavaDoc DOMAINDIR_OPTION = "domaindir";
75     private static String JavaDoc SAVELOGIN_OPTION = "savelogin";
76
77     private String JavaDoc domainName = null;
78     private String JavaDoc adminUser = null;
79     private String JavaDoc adminPassword = null;
80     private String JavaDoc masterPassword = null;
81
82     /** Creates new CreateDomainCommand */
83     public CreateDomainCommand()
84     {
85     }
86
87     /**
88      * An abstract method that validates the options
89      * on the specification in the xml properties file
90      * @return true if successfull
91      */

92     public boolean validateOptions() throws CommandValidationException
93     {
94         return super.validateOptions();
95     }
96
97     
98     /* validates adminpassword and masterpassword */
99     public void validatePasswords() throws CommandValidationException
100     {
101         //verify adminpassword is greater than 8 characters
102
if (!isPasswordValid(adminPassword)) {
103             throw new CommandValidationException(getLocalizedString("PasswordLimit",
104                 new Object JavaDoc[]{ADMIN_PASSWORD}));
105         }
106         
107         //verify masterpassword is greater than 8 characters
108
if (!isPasswordValid(masterPassword)) {
109             throw new CommandValidationException(getLocalizedString("PasswordLimit",
110                 new Object JavaDoc[]{MASTER_PASSWORD}));
111         }
112
113         //verify that domainName is valid
114
CLILogger.getInstance().printDebugMessage("domainName = " + domainName);
115     }
116
117
118     /**
119      * this methods returns the admin password and is used to get the admin password
120      * for create-domain. The password can be passed in on the command line
121      * (--adminpassword), environment variable (AS_ADMIN_ADMINPASSWORD),
122      * or in the password file (--passwordfile).
123      * first it checks if adminpassword option is specified on command line.
124      * if not, then it'll try to get AS_ADMIN_ADMINPASSWORD from the password file.
125      * if that still does not exist then get AS_ADMIN_PASSWORD from
126      * ./asadminprefs file.
127      * if all else fails, then prompt the user for the password if interactive=true.
128      * @return admin password
129      * @throws CommandValidationException if could not get adminpassword option
130      */

131     protected String JavaDoc getAdminPassword()
132         throws CommandValidationException, CommandException
133     {
134         //getPassword(optionName, allowedOnCommandLine, readPrefsFile, readPasswordOptionFromPrefs, readMasterPasswordFile, mgr, config,
135
//promptUser, confirm, validate)
136
return getPassword(ADMIN_PASSWORD, "AdminPasswordPrompt", "AdminPasswordConfirmationPrompt",
137                             true, true, false, false, null, null,
138                             true, true, true, true);
139     }
140
141     
142     /**
143      * An abstract method that executes the command
144      * @throws CommandException
145      */

146     public void runCommand()
147         throws CommandException, CommandValidationException
148     {
149         validateOptions();
150         setLoggerLevel();
151
152         //verify for no-spaces in domaindir option on non-windows platform
153
String JavaDoc domainDirValue = getOption(DOMAINDIR_OPTION);
154         if ((domainDirValue != null) && !isWindows() && isSpaceInPath(domainDirValue))
155             throw new CommandException(getLocalizedString("SpaceNotAllowedInPath",
156                                                             new Object JavaDoc[]{DOMAINDIR_OPTION}));
157         //domain validation upfront (i.e. before we prompt)
158
try {
159             domainName = (String JavaDoc)operands.firstElement();
160             DomainsManager manager = getFeatureFactory().getDomainsManager();
161             DomainConfig config = getDomainConfig(domainName);
162             manager.validateDomain(config, false);
163         } catch (Exception JavaDoc e) {
164             CLILogger.getInstance().printDetailMessage(e.getLocalizedMessage());
165             throw new CommandException(getLocalizedString("CouldNotCreateDomain",
166                 new Object JavaDoc[] {domainName}), e);
167         }
168         
169         adminUser = getAdminUser();
170
171         adminPassword = getAdminPassword();
172         masterPassword = getMasterPassword(true);
173         validatePasswords();
174     
175         try
176         {
177             //verify admin port is valid
178
verifyPortIsValid(getOption(ADMIN_PORT));
179             //instance option is entered then verify instance port is valid
180
if (getOption(INSTANCE_PORT) != null)
181                 verifyPortIsValid(getOption(INSTANCE_PORT));
182         
183             //get domain properties from options or from option
184
Properties JavaDoc domainProperties = getDomainProperties(getOption(DOMAIN_PROPERTIES));
185             //we give priority to the --adminport option
186
domainProperties.remove(DomainConfig.K_ADMIN_PORT);
187             //saving the login information happens inside this method
188
createTheDomain(getDomainsRoot(), domainProperties);
189         }
190         catch (Exception JavaDoc e)
191         {
192             CLILogger.getInstance().printDetailMessage(e.getLocalizedMessage());
193             throw new CommandException(getLocalizedString("CouldNotCreateDomain",
194                 new Object JavaDoc[] {domainName}), e);
195         }
196     }
197
198
199     /**
200        Verify that the port is valid.
201        Port must be greater than 0 and less than 65535.
202        This method will also check if the port is in used.
203        @param portNum - the port number to verify
204        @throws CommandException if Port is not valid
205        @throws CommandValidationException is port number is not a numeric value.
206        
207      */

208     private void verifyPortIsValid(String JavaDoc portNum)
209         throws CommandException, CommandValidationException
210     {
211
212         final int portToVerify = convertPortStr(portNum);
213
214         if (portToVerify <= 0 || portToVerify > 65535)
215         {
216             throw new CommandException(getLocalizedString("InvalidPortRange",
217                                          new Object JavaDoc[] {portNum}));
218         }
219         if (getBooleanOption(CHECKPORTS_OPTION) && !NetUtils.isPortFree(portToVerify))
220         {
221             throw new CommandException(getLocalizedString("PortInUse",
222                                          new Object JavaDoc[] {(String JavaDoc) operands.firstElement(),
223                                                        portNum}));
224         }
225         CLILogger.getInstance().printDebugMessage("Port =" + portToVerify);
226     }
227     
228
229     /**
230      * create the domain
231      * @param domainPath - domain path to insert in domainConfig
232      * @param domainProperties - properties to insert in domainConfig
233      * @throws CommandException if domain cannot be created
234      */

235     private void createTheDomain(final String JavaDoc domainPath,
236                                  Properties JavaDoc domainProperties)
237         throws Exception JavaDoc
238     {
239         Integer JavaDoc adminPort = new Integer JavaDoc(getOption(ADMIN_PORT));
240             
241
242         //
243
// fix for bug# 4930684
244
// domain name is validated before the ports
245
//
246

247         String JavaDoc domainFilePath = (domainPath + File.separator + domainName);
248         if (FileUtils.safeGetCanonicalFile(new File JavaDoc(domainFilePath)).exists()) {
249                 throw new CommandValidationException(
250                     getLocalizedString("DomainExists", new Object JavaDoc[] {domainName}));
251         }
252     
253         final Integer JavaDoc instancePort = getPort(domainProperties,
254                                              DomainConfig.K_INSTANCE_PORT,
255                                              getOption(INSTANCE_PORT),
256                                              Integer.toString(DEFAULT_INSTANCE_PORT),
257                                              "HTTP Instance");
258         
259         final Integer JavaDoc jmsPort = getPort(domainProperties,
260                                         DomainConfig.K_JMS_PORT, null,
261                                         Integer.toString(DEFAULT_JMS_PORT), "JMS");
262         
263 /* Bug# 4859518
264     The authentication of jms broker will fail if the jms user is not in the
265     user database referred by jms broker. Setting the jms user and password to
266     "admin" which is always present in the user db. Once the mechanism to update
267     the user db with given jms user/password is in place we should set the
268     user specified values for jms user and password.
269     final String jmsUser = adminUser;
270     final String jmsPassword = adminPassword;
271 */

272         final String JavaDoc jmsUser = DEFAULT_JMS_USER;
273         final String JavaDoc jmsPassword = DEFAULT_JMS_PASSWORD;
274         
275         final Integer JavaDoc orbPort = getPort(domainProperties,
276                                         DomainConfig.K_ORB_LISTENER_PORT,
277                                         null, Integer.toString(DEFAULT_IIOP_PORT),
278                                         "IIOP");
279                 
280         final Integer JavaDoc httpSSLPort = getPort(domainProperties,
281                                             DomainConfig.K_HTTP_SSL_PORT, null,
282                                             Integer.toString(DEFAULT_HTTPSSL_PORT),
283                                             "HTTP_SSL");
284
285         final Integer JavaDoc iiopSSLPort = getPort(domainProperties,
286                                             DomainConfig.K_IIOP_SSL_PORT, null,
287                                             Integer.toString(DEFAULT_IIOPSSL_PORT),
288                                             "IIOP_SSL");
289
290         final Integer JavaDoc iiopMutualAuthPort = getPort(domainProperties,
291                                                    DomainConfig.K_IIOP_MUTUALAUTH_PORT, null,
292                                                    Integer.toString(DEFAULT_IIOPMUTUALAUTH_PORT),
293                                                    "IIOP_MUTUALAUTH");
294
295         //FIXTHIS: Currently the jmx admin port is used only for SE/EE where the DAS as
296
//in addition to the http admin listener a jsr160 connector listener. This jmx connector
297
//will be exposed to access the mbean API of the DAS. If we choose to expose the API
298
//in PE, then this jsr160 listener will be added to the PE domain.xml and this will be
299
//needed. If we choose not to, then this should be moved into SE/EE specific code
300
//(namely DomainsManager.createDomain).
301
final Integer JavaDoc jmxPort = getPort(domainProperties,
302                                         DomainConfig.K_JMX_PORT, null,
303                                         Integer.toString(DEFAULT_JMX_PORT),
304                                         "JMX_ADMIN");
305                 
306         Boolean JavaDoc saveMasterPassword = getSaveMasterPassword(masterPassword);
307         
308         //System.out.println("adminPassword=" + adminPassword + " masterPassword=" + masterPassword +
309
// " saveMasterPassword=" + saveMasterPassword);
310

311         DomainConfig domainConfig = new DomainConfig(domainName,
312                                                      adminPort, domainPath, adminUser,
313                                                      adminPassword,
314                                                      masterPassword,
315                                                      saveMasterPassword, instancePort, jmsUser,
316                                                      jmsPassword, jmsPort, orbPort,
317                                                      httpSSLPort, iiopSSLPort,
318                                                      iiopMutualAuthPort, jmxPort,
319                                                      domainProperties);
320         if (getOption(TEMPLATE) != null) {
321             domainConfig.put(DomainConfig.K_TEMPLATE_NAME, getOption(TEMPLATE));
322         }
323
324         domainConfig.put(DomainConfig.K_VALIDATE_PORTS, new Boolean JavaDoc(getBooleanOption(CHECKPORTS_OPTION)));
325
326         DomainsManager manager = getFeatureFactory().getDomainsManager();
327         
328         manager.createDomain(domainConfig);
329         CLILogger.getInstance().printDetailMessage(getLocalizedString("DomainCreated",
330                                                                       new Object JavaDoc[] {domainName}));
331         checkAsadminPrefsFile();
332         if (getBooleanOption(SAVELOGIN_OPTION))
333             saveLogin(adminPort, adminUser, adminPassword, domainName);
334     }
335
336
337         /**
338          * This routine checks if the .asadminprefs file exists in the home
339          * directory. If it exists, then a warning message is displayed.
340          * This message is to warn user that the remote commands will
341          * retrieve user and password from .asadminpref file if it is not
342          * entered on the command line, environment variable or passwordfile
343          **/

344     private void checkAsadminPrefsFile()
345     {
346         try {
347             checkForFileExistence(System.getProperty("user.home"), ASADMINPREFS);
348             CLILogger.getInstance().printMessage(getLocalizedString("AsadminPrefFileDetected", new Object JavaDoc[] {domainName}));
349         }
350         catch(CommandException ce) {
351                 //do nothing since we do not want to display a warning msg
352
//if the file does not exist.
353
}
354     }
355
356
357
358     /**
359      * get port from from the properties option or default or free port
360      * @param properties - properties from command line
361      * @param key - key for the type of port
362      * @param portStr -
363      * @param defaultPort - default port to use
364      * @name - of port
365      * @throws CommandValidationException if error in retrieve port
366      */

367     private Integer JavaDoc getPort(Properties JavaDoc properties,
368                             String JavaDoc key,
369                             String JavaDoc portStr,
370                             String JavaDoc defaultPort,
371                             String JavaDoc name)
372         throws CommandValidationException
373     {
374         int port = 0;
375         boolean portNotSpecified = false;
376         boolean invalidPortSpecified = false;
377         boolean defaultPortUsed = false;
378         if ((portStr != null) && !portStr.equals(""))
379         {
380             port = convertPortStr(portStr);
381             if ((port <= 0) || (port > 65535))
382                 invalidPortSpecified = true;
383         }
384         else if (properties != null)
385         {
386             String JavaDoc property = properties.getProperty(key);
387             if ((property != null) && !property.equals("")) {
388                 port = convertPortStr(property);
389             }
390             else {
391                 portNotSpecified = true;
392             }
393         }
394         else {
395             portNotSpecified = true;
396         }
397         if (portNotSpecified) {
398             port = convertPortStr(defaultPort);
399             defaultPortUsed = true;
400         }
401         if(getBooleanOption(CHECKPORTS_OPTION) && !NetUtils.isPortFree(port))
402     {
403             port = NetUtils.getFreePort();
404                 //don't understand why this is a printMessage not an Exception??
405
//maybe there will always be a port ??
406
if (portNotSpecified) {
407                 if (defaultPortUsed) {
408                     CLILogger.getInstance().printDetailMessage(
409                         getLocalizedString("DefaultPortInUse",
410                                            new Object JavaDoc[] {name, defaultPort, Integer.toString(port)}));
411                 }
412                 else {
413                     CLILogger.getInstance().printDetailMessage(
414                         getLocalizedString("PortNotSpecified",
415                                            new Object JavaDoc[] {name, new Integer JavaDoc(port)}));
416                 }
417             }
418             else if (invalidPortSpecified){
419                 CLILogger.getInstance().printDetailMessage(
420                     getLocalizedString("InvalidPortRangeMsg",
421                                        new Object JavaDoc[] {name, new Integer JavaDoc(port)}));
422             }
423             else {
424                 CLILogger.getInstance().printDetailMessage(
425                     getLocalizedString("PortInUseMsg",
426                                        new Object JavaDoc[] {name, new Integer JavaDoc(port)}));
427             }
428         }
429         else if (defaultPortUsed) {
430             CLILogger.getInstance().printDetailMessage(
431                 getLocalizedString("UsingDefaultPort",
432                                    new Object JavaDoc[] {name, Integer.toString(port)}));
433         }
434         
435         if (properties != null) {
436             properties.remove(key);
437         }
438         return new Integer JavaDoc(port);
439     }
440
441
442     /**
443      * Get domain properties from options
444      * @param propertyValues from options
445      * @return domain properties
446      * @throws CommandException if cannot get properties
447      **/

448     private Properties JavaDoc getDomainProperties(final String JavaDoc propertyValues)
449         throws CommandException, CommandValidationException
450     {
451         Properties JavaDoc propertyList = new Properties JavaDoc();
452
453         if (propertyValues == null) return propertyList;
454         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(propertyValues, DELIMITER);
455         while (st.hasMoreTokens())
456         {
457             String JavaDoc propertyString = st.nextToken();
458             while (st.hasMoreTokens() &&
459                    propertyString.endsWith(Character.toString(ESCAPE_CHAR)))
460             {
461                 propertyString = propertyString.concat(st.nextToken());
462             }
463             final int index = propertyString.indexOf(Character.toString(EQUAL_SIGN));
464             if (index == -1)
465                 throw new CommandValidationException(getLocalizedString("InvalidPropertySyntax"));
466             final String JavaDoc propertyName = propertyString.substring(0, index);
467             final String JavaDoc propertyValue = propertyString.substring(index+1);
468             propertyList.put(propertyName, propertyValue);
469         }
470         CLILogger.getInstance().printDebugMessage("domain properties = " + propertyList);
471         return propertyList;
472     }
473
474     /**
475      * Converts the port string to port int
476      * @param port - the port number
477      * @return
478      * @throws CommandValidationExeption if port string is not numeric
479      */

480     private int convertPortStr(final String JavaDoc port)
481         throws CommandValidationException
482     {
483         try
484         {
485             return Integer.parseInt(port);
486         }
487         catch(Exception JavaDoc e)
488         {
489             throw new CommandValidationException(
490                 getLocalizedString("InvalidPortNumber",
491                                    new Object JavaDoc[] {port}));
492         }
493     }
494
495     /** Saves the login information to the login store. Usually this is the file
496      * ".asadminpass" in user's home directory.
497     */

498     private void saveLogin(final int port, final String JavaDoc user, final String JavaDoc password, final String JavaDoc dn)
499     {
500         final CLILogger logger = CLILogger.getInstance();
501         try {
502             //by definition, the host name will default to "localhost" and entry is overwritten
503
final LoginInfoStore store = LoginInfoStoreFactory.getStore(null);
504             final LoginInfo login = new LoginInfo("localhost", port, user, password);
505             if (store.exists(login.getHost(), login.getPort())) {
506                 //just let the user know that the user has chosen to overwrite the login information. This is non-interactive, on purpose
507
final Object JavaDoc[] params = new Object JavaDoc[] {login.getHost(), ""+login.getPort()};
508                 final String JavaDoc msg = getLocalizedString("OverwriteLoginMsgCreateDomain", params);
509                 logger.printMessage(msg);
510             }
511             store.store(login, true);
512             final Object JavaDoc[] params = new String JavaDoc[] {user, dn, store.getName()};
513             final String JavaDoc msg = getLocalizedString("LoginInfoStoredCreateDomain", params);
514             logger.printMessage(msg);
515         }
516         catch(final Exception JavaDoc e) {
517             final Object JavaDoc[] params = new String JavaDoc[] {user, dn};
518             final String JavaDoc msg = getLocalizedString("LoginInfoStoredCreateDomain", params);
519             logger.printWarning(msg);
520             if (logger.isDebug())
521                 logger.printExceptionStackTrace(e);
522         }
523     }
524 }
525
Popular Tags