KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > servermgmt > RepositoryManager


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  * RepositoryManager.java
26  *
27  * Created on August 19, 2003, 2:29 PM
28  */

29
30 package com.sun.enterprise.admin.servermgmt;
31
32 import com.sun.enterprise.admin.util.TokenValueSet;
33 import com.sun.enterprise.admin.util.LineTokenReplacer;
34 import com.sun.enterprise.util.io.FileUtils;
35 import com.sun.enterprise.util.SystemPropertyConstants;
36 import com.sun.enterprise.admin.servermgmt.pe.PEFileLayout;
37 import com.sun.enterprise.admin.servermgmt.pe.PEInstancesManager;
38 import com.sun.enterprise.admin.servermgmt.pe.PEDomainsManager;
39 import com.sun.enterprise.util.i18n.StringManager;
40
41 import com.sun.enterprise.admin.common.constant.AdminConstants;
42 import com.sun.enterprise.security.auth.realm.file.FileRealm;
43 import com.sun.enterprise.security.auth.realm.BadRealmException;
44 import com.sun.enterprise.security.auth.realm.NoSuchRealmException;
45 import com.sun.enterprise.security.util.IASSecurityException;
46 import com.sun.enterprise.security.store.PasswordAdapter;
47 import com.sun.enterprise.security.RealmConfig;
48
49 import com.sun.enterprise.admin.common.Status;
50 import java.io.BufferedReader JavaDoc;
51
52 import java.io.File JavaDoc;
53 import java.io.FileReader JavaDoc;
54 import java.io.FilenameFilter JavaDoc;
55 import java.io.IOException JavaDoc;
56 import java.sql.Connection JavaDoc;
57 import java.sql.DriverManager JavaDoc;
58 import java.sql.Statement JavaDoc;
59
60 import java.util.HashMap JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.ArrayList JavaDoc;
63 import java.util.List JavaDoc;
64
65 //config imports
66
import com.sun.enterprise.config.ConfigFactory;
67 import com.sun.enterprise.config.ConfigContext;
68 import com.sun.enterprise.config.ConfigException;
69 import com.sun.enterprise.config.serverbeans.Server;
70 import com.sun.enterprise.config.serverbeans.Config;
71 import com.sun.enterprise.config.serverbeans.ServerHelper;
72 import com.sun.enterprise.config.serverbeans.JavaConfig;
73 import com.sun.enterprise.config.serverbeans.JmsService;
74 import com.sun.enterprise.config.serverbeans.AuthRealm;
75 import com.sun.enterprise.config.serverbeans.ServerHelper;
76 import com.sun.enterprise.config.serverbeans.JmxConnector;
77 import com.sun.enterprise.config.serverbeans.SecurityService;
78
79
80 import javax.management.remote.JMXAuthenticator JavaDoc;
81 import com.sun.enterprise.admin.server.core.jmx.auth.ASJMXAuthenticator;
82 import com.sun.enterprise.admin.server.core.jmx.auth.ASLoginDriverImpl;
83
84 //iMQ imports
85
import com.sun.enterprise.jms.IASJmsUtil;
86 import com.sun.messaging.jmq.jmsspi.JMSAdmin;
87 import javax.jms.JMSException JavaDoc;
88
89 import com.sun.enterprise.util.SystemPropertyConstants;
90 import com.sun.enterprise.util.ProcessExecutor;
91 import com.sun.enterprise.util.ExecException;
92
93 /**
94  * The RepositoryManager serves as a common base class for the following
95  * PEDomainsManager, PEInstancesManager, AgentManager (the SE Node Agent).
96  * Its purpose is to abstract out any shared functionality related to
97  * lifecycle management of domains, instances and node agents. This includes
98  * creation, deletion, listing, and starting and stopping.
99  *
100  * @author kebbs
101  */

102 public class RepositoryManager extends MasterPasswordFileManager {
103             
104     /**
105      * The RepositoryManagerMessages class is used to abstract out
106      * ResourceBundle messages that are specific to a domain, node-agent,
107      * or server instance.
108      */

109     protected class RepositoryManagerMessages
110     {
111         private StringManager _strMgr;
112         private String JavaDoc _badNameMessage;
113         private String JavaDoc _repositoryNameMessage;
114         private String JavaDoc _repositoryRootMessage;
115         private String JavaDoc _existsMessage;
116         private String JavaDoc _noExistsMessage;
117         private String JavaDoc _repositoryNotValidMessage;
118         private String JavaDoc _cannotDeleteMessage;
119         private String JavaDoc _invalidPathMessage;
120         private String JavaDoc _listRepositoryElementMessage;
121         private String JavaDoc _cannotDeleteInstance_invalidState;
122         private String JavaDoc _instanceStartupExceptionMessage;
123         private String JavaDoc _cannotStartInstance_invalidStateMessage;
124         private String JavaDoc _startInstanceTimeOutMessage;
125         private String JavaDoc _portConflictMessage;
126         private String JavaDoc _startupFailedMessage;
127         private String JavaDoc _cannotStopInstance_invalidStateMessage;
128         private String JavaDoc _cannotStopInstanceMessage;
129         private String JavaDoc _timeoutStartingMessage;
130         private String JavaDoc _cannotDeleteJmsProviderInstance;
131
132         public RepositoryManagerMessages(
133             StringManager strMgr,
134             String JavaDoc badNameMessage,
135             String JavaDoc repositoryNameMessage,
136             String JavaDoc repositoryRootMessage,
137             String JavaDoc existsMessage,
138             String JavaDoc noExistsMessage,
139             String JavaDoc repositoryNotValidMessage,
140             String JavaDoc cannotDeleteMessage,
141             String JavaDoc invalidPathMessage,
142             String JavaDoc listRepositoryElementMessage,
143             String JavaDoc cannotDeleteInstance_invalidState,
144             String JavaDoc instanceStartupExceptionMessage,
145             String JavaDoc cannotStartInstance_invalidStateMessage,
146             String JavaDoc startInstanceTimeOutMessage,
147             String JavaDoc portConflictMessage,
148             String JavaDoc startupFailedMessage,
149             String JavaDoc cannotStopInstance_invalidStateMessage,
150             String JavaDoc cannotStopInstanceMessage,
151             String JavaDoc timeoutStartingMessage)
152         {
153             _strMgr = strMgr;
154             _badNameMessage = badNameMessage;
155             _repositoryNameMessage = repositoryNameMessage;
156             _repositoryRootMessage = repositoryRootMessage;
157             _existsMessage = existsMessage;
158             _noExistsMessage = noExistsMessage;
159             _repositoryNotValidMessage = repositoryNotValidMessage;
160             _cannotDeleteMessage = cannotDeleteMessage;
161             _invalidPathMessage = invalidPathMessage;
162             _listRepositoryElementMessage = listRepositoryElementMessage;
163             _cannotDeleteInstance_invalidState = cannotDeleteInstance_invalidState;
164             _instanceStartupExceptionMessage = instanceStartupExceptionMessage;
165             _cannotStartInstance_invalidStateMessage =
166                 cannotStartInstance_invalidStateMessage;
167             _startInstanceTimeOutMessage = startInstanceTimeOutMessage;
168             _portConflictMessage = portConflictMessage;
169             _startupFailedMessage = startupFailedMessage;
170             _cannotStopInstance_invalidStateMessage =
171                 cannotStopInstance_invalidStateMessage;
172             _cannotStopInstanceMessage = cannotStopInstanceMessage;
173             _timeoutStartingMessage = timeoutStartingMessage;
174         }
175
176         public String JavaDoc getRepositoryNameMessage() {
177             return _strMgr.getString(_repositoryNameMessage);
178         }
179
180         public String JavaDoc getBadNameMessage(String JavaDoc repositoryName) {
181             return _strMgr.getString(_badNameMessage, repositoryName);
182         }
183
184         public String JavaDoc getRepositoryRootMessage() {
185             return _strMgr.getString(_repositoryRootMessage);
186         }
187
188         public String JavaDoc getNoExistsMessage(String JavaDoc repositoryName, String JavaDoc repositoryLocation) {
189             return _strMgr.getString(_noExistsMessage, repositoryName, repositoryLocation);
190         }
191
192         public String JavaDoc getExistsMessage(String JavaDoc repositoryName, String JavaDoc repositoryLocation) {
193             return _strMgr.getString(_existsMessage, repositoryName, repositoryLocation);
194         }
195
196         public String JavaDoc getRepositoryNotValidMessage(String JavaDoc path) {
197             return _strMgr.getString(_repositoryNotValidMessage, path);
198         }
199
200         public String JavaDoc getCannotDeleteMessage(String JavaDoc repositoryName) {
201             return _strMgr.getString(_cannotDeleteMessage, repositoryName);
202         }
203
204         public String JavaDoc getInvalidPathMessage(String JavaDoc path) {
205             return _strMgr.getString(_invalidPathMessage, path);
206         }
207
208         public String JavaDoc getListRepositoryElementMessage(String JavaDoc repositoryName,
209             String JavaDoc repositoryStatus) {
210             return _strMgr.getString(_listRepositoryElementMessage, repositoryName,
211                 repositoryStatus);
212         }
213
214         public String JavaDoc getCannotDeleteInstanceInvalidState(String JavaDoc name,
215             String JavaDoc state) {
216             return _strMgr.getString(_cannotDeleteInstance_invalidState,
217                 name, state);
218         }
219
220         public String JavaDoc getInstanceStartupExceptionMessage(String JavaDoc name) {
221             return _strMgr.getString(_instanceStartupExceptionMessage, name);
222         }
223
224         public String JavaDoc getCannotStartInstanceInvalidStateMessage(String JavaDoc name,
225             String JavaDoc state) {
226             return _strMgr.getString(_cannotStartInstance_invalidStateMessage,
227                 name, state);
228         }
229
230         public String JavaDoc getStartInstanceTimeOutMessage(String JavaDoc name) {
231             return _strMgr.getString(_startInstanceTimeOutMessage, name);
232         }
233
234         public String JavaDoc getStartupFailedMessage(String JavaDoc name) {
235             return _strMgr.getString(_startupFailedMessage, name);
236         }
237
238         public String JavaDoc getStartupFailedMessage(String JavaDoc name, int port) {
239             if (port != 0) {
240                 return _strMgr.getString(_portConflictMessage, new Object JavaDoc[]{name, String.valueOf(port)});
241             } else {
242                 return _strMgr.getString(_startupFailedMessage, name);
243             }
244         }
245
246         public String JavaDoc getCannotStopInstanceInvalidStateMessage(String JavaDoc name,
247             String JavaDoc state) {
248             return _strMgr.getString(_cannotStopInstance_invalidStateMessage,
249                 name, state);
250         }
251
252         public String JavaDoc getCannotStopInstanceMessage(String JavaDoc name) {
253             return _strMgr.getString(_cannotStopInstanceMessage, name);
254         }
255
256         public String JavaDoc getTimeoutStartingMessage(String JavaDoc name) {
257             return _strMgr.getString(_timeoutStartingMessage, name);
258         }
259     }
260        
261     protected static final String JavaDoc NEW_LINE =
262         System.getProperty("line.separator");
263     
264     private static final StringManager _strMgr =
265         StringManager.getManager(RepositoryManager.class);
266     
267     private ConfigContext _configContext = null;
268       
269     protected RepositoryManagerMessages _messages = null;
270     
271     public static final String JavaDoc DEBUG = "Debug";
272
273     /** Creates a new instance of RepositoryManager */
274     public RepositoryManager() {
275         super();
276         setMessages(new RepositoryManagerMessages(
277             StringManager.getManager(PEDomainsManager.class),
278             "illegalDomainName",
279             "domainName", "domainsRoot", "domainExists",
280             "domainDoesntExist", "domainDirNotValid",
281             "cannotDeleteDomainDir", "invalidDomainDir",
282             "listDomainElement", "cannotDeleteInstance_invalidState",
283             "instanceStartupException", "cannotStartInstance_invalidState",
284             "startInstanceTimeOut", "portConflict", "startupFailed",
285             "cannotStopInstance_invalidState",
286             "cannotStopInstance", "timeoutStarting"));
287     }
288
289     protected void setMessages(RepositoryManagerMessages messages) {
290         _messages = messages;
291     }
292
293     protected RepositoryManagerMessages getMessages() {
294         return _messages;
295     }
296        
297     protected void generateFromTemplate(TokenValueSet tokens,
298         File JavaDoc template, File JavaDoc destinationFile) throws IOException JavaDoc
299     {
300         LineTokenReplacer replacer = new LineTokenReplacer(tokens);
301         replacer.replace(template, destinationFile);
302     }
303         
304     protected boolean repositoryExists(RepositoryConfig config)
305     {
306         return FileUtils.safeGetCanonicalFile(getRepositoryDir(config)).exists();
307     }
308     
309     protected boolean isValidRepository(File JavaDoc f)
310     {
311         return new File JavaDoc(new File JavaDoc(f, PEFileLayout.BIN_DIR),
312             PEFileLayout.START_SERV_OS).exists();
313     }
314
315     protected boolean isValidRepository(RepositoryConfig config) {
316         return getFileLayout(config).getStartServ().exists();
317     }
318       
319     protected File JavaDoc getRepositoryDir(RepositoryConfig config)
320     {
321         return getFileLayout(config).getRepositoryDir();
322     }
323     
324     protected File JavaDoc getRepositoryRootDir(RepositoryConfig config)
325     {
326         return getFileLayout(config).getRepositoryRootDir();
327     }
328     
329     protected void checkRepository(RepositoryConfig config)
330         throws RepositoryException
331     {
332         checkRepository(config, true, true);
333     }
334
335     public void checkRepository(RepositoryConfig config,
336         boolean existingRepository)
337         throws RepositoryException
338     {
339         checkRepository(config, existingRepository, true);
340     }
341
342     /**
343      * Sanity check on the repository. This is executed prior to create/delete/start/stop.
344      */

345     public void checkRepository(RepositoryConfig config,
346         boolean existingRepository,
347         boolean checkRootDir)
348         throws RepositoryException
349     {
350         String JavaDoc repositoryName = config.getDisplayName();
351
352         //check domain name for validity
353
new RepositoryNameValidator(getMessages().getRepositoryNameMessage()).
354             validate(repositoryName);
355       
356         if (checkRootDir || existingRepository) {
357             //check domain root directory is read/writable
358
new FileValidator(getMessages().getRepositoryRootMessage(), "drw").validate(
359                 config.getRepositoryRoot());
360         }
361         
362         //check installation root directory is readable
363
new FileValidator(_strMgr.getString("installRoot"), "dr").validate(
364             config.getInstallRoot());
365          
366         //Ensure that the domain exists or does not exist
367
if (existingRepository) {
368             if (!repositoryExists(config)) {
369                 throw new RepositoryException(
370                     getMessages().getNoExistsMessage(repositoryName,
371                         getRepositoryRootDir(config).getAbsolutePath()));
372             } else if (!isValidRepository(config)) {
373                 throw new RepositoryException(
374                     getMessages().getRepositoryNotValidMessage(
375                         getRepositoryDir(config).getAbsolutePath()));
376             }
377         } else {
378             if (repositoryExists(config)) {
379                 throw new RepositoryException(
380                     getMessages().getExistsMessage(repositoryName,
381                         getRepositoryRootDir(config).getAbsolutePath()));
382             }
383         }
384     }
385
386     /**
387      * Sets the permissions for the domain directory, its config directory,
388      * startserv/stopserv scripts etc.
389      */

390     protected void setPermissions(RepositoryConfig repositoryConfig) throws RepositoryException
391     {
392         final PEFileLayout layout = getFileLayout(repositoryConfig);
393         final File JavaDoc domainDir = layout.getRepositoryDir();
394         try {
395             chmod("-R 755", domainDir);
396         } catch (Exception JavaDoc e) {
397             throw new RepositoryException(
398                 _strMgr.getString("setPermissionError"), e);
399         }
400     }
401     
402     /**
403      * Deletes the repository (domain, node agent, server instance).
404      */

405     protected void deleteRepository(
406         RepositoryConfig config)
407         throws RepositoryException
408     {
409         deleteRepository(config, true);
410     }
411    
412    
413     /**
414      * Deletes the repository (domain, node agent, server instance). If
415      * the deleteJMSProvider flag is set, we delete the jms instance.
416      * The jms instance is present in the domain only and not when
417      * the repository corresponds to a server instance or node agent.
418      */

419     protected void deleteRepository(
420         RepositoryConfig config, boolean deleteJMSProvider)
421         throws RepositoryException
422     {
423         checkRepository(config, true);
424    
425         //Ensure that the entity to be deleted is stopped
426
final int status = getInstancesManager(config).getInstanceStatus();
427         if (status != Status.kInstanceNotRunningCode) {
428             throw new RepositoryException(
429                 getMessages().getCannotDeleteInstanceInvalidState(
430                     config.getDisplayName(),
431                     Status.getStatusString(status)));
432         }
433
434         // FIXME: This is set temporarily so the instances that are deleted
435
// don't require domain.xml (instance may never have been started) and it
436
// also removes the dependencey on imqadmin.jar.
437
// This should ne move in some way to PEDomainsManager since
438
// JMS providers are really only present in the domain and not node agent
439
// or server instance.
440
if (deleteJMSProvider) {
441             deleteJMSProviderInstance(config);
442         }
443         
444         //Blast the directory
445
File JavaDoc repository = getRepositoryDir(config);
446         try {
447             FileUtils.liquidate(repository);
448         } catch (Exception JavaDoc e) {
449             throw new RepositoryException(getMessages().getCannotDeleteMessage(
450                 repository.getAbsolutePath()), e);
451         }
452        
453         //Double check to ensure that it was really deleted
454
if (repositoryExists(config)) {
455             throw new RepositoryException(
456                 getMessages().getCannotDeleteMessage(repository.getAbsolutePath()));
457         }
458     }
459    
460     /**
461      * Return all repositories (domains, node agents, server instances)
462      */

463     protected String JavaDoc[] listRepository(RepositoryConfig config) throws RepositoryException
464     {
465         File JavaDoc repository = getRepositoryRootDir(config);
466         String JavaDoc[] dirs = new String JavaDoc[0];
467         try {
468             File JavaDoc f = repository.getCanonicalFile();
469             if (!f.isDirectory()) {
470                 throw new RepositoryException(getMessages().getInvalidPathMessage(
471                     f.getAbsolutePath()));
472             }
473             dirs = f.list(new FilenameFilter JavaDoc() {
474                 //Only accept directories that are valid (contain the property startserv script)
475
public boolean accept(File JavaDoc dir, String JavaDoc name) {
476                     File JavaDoc f = new File JavaDoc(dir, name);
477                     if (!f.isDirectory()) {
478                         return false;
479                     } else {
480                         return isValidRepository(f);
481                     }
482                 }
483             });
484             if (dirs == null) {
485                 dirs = new String JavaDoc[0];
486             }
487         } catch (Exception JavaDoc e) {
488             throw new RepositoryException(e);
489         }
490         return dirs;
491     }
492
493     public InstancesManager getInstancesManager(RepositoryConfig config)
494     {
495         return new PEInstancesManager(config);
496     }
497
498     /**
499      * Return all repositories (domains, node agents, server instances)
500      * and their corresponding status (e.g. running or stopped) in
501      * string form.
502      */

503     protected String JavaDoc[] listDomainsAndStatusAsString(
504         RepositoryConfig config) throws RepositoryException
505     {
506         try {
507             RuntimeStatusList statusList = getRuntimeStatus(config);
508             RuntimeStatus status = null;
509             String JavaDoc[] result = new String JavaDoc[statusList.size()];
510             for (int i = 0; i < statusList.size(); i++) {
511                 status = statusList.getStatus(i);
512                 result[i] = getMessages().getListRepositoryElementMessage(
513                     status.getName(), status.toShortString());
514             }
515             return result;
516         } catch (Exception JavaDoc e) {
517             throw new RepositoryException(e);
518         }
519     }
520        
521     protected RepositoryConfig getConfigForRepositoryStatus(RepositoryConfig config,
522         String JavaDoc repository)
523     {
524         //The repository here corresponds to either the domain or node agent name
525
return new RepositoryConfig(repository, config.getRepositoryRoot());
526     }
527     
528     /**
529      * Return all repositories (domains, node agents, server instances)
530      * and their corresponding status (e.g. running or stopped)
531      */

532     public RuntimeStatusList getRuntimeStatus(
533         RepositoryConfig config) throws RepositoryException
534     {
535         String JavaDoc[] repositories = listRepository(config);
536         RuntimeStatusList result = new RuntimeStatusList(repositories.length);
537         int status;
538         for (int i = 0; i < repositories.length; i++) {
539             final InstancesManager mgr = getInstancesManager(
540                 getConfigForRepositoryStatus(config, repositories[i]));
541             result.add(RuntimeStatus.getRuntimeStatus(repositories[i], mgr));
542         }
543         return result;
544     }
545
546     /** This method creates a separate administrative keyfile. This is to separate
547      * the administrative users from other users. All the administrative
548      * operations will be authenticated against this file realm by default.
549      * @see PEFileLayout#ADMIN_KEY_FILE
550      */

551     protected void createAdminKeyFile(final RepositoryConfig config, final String JavaDoc
552         user, final String JavaDoc clearPwd) throws RepositoryException {
553         final PEFileLayout layout = getFileLayout(config);
554         final File JavaDoc src = layout.getKeyFileTemplate();
555         final File JavaDoc dest = layout.getAdminKeyFile();
556         try {
557             FileUtils.copy(src, dest);
558             modifyKeyFile(dest, user, clearPwd);
559         } catch (final Exception JavaDoc e) {
560             throw new RepositoryException(_strMgr.getString("keyFileNotCreated"), e);
561         }
562     }
563       
564     /**
565      * Create the FileRealm kefile from the given user and password.
566      */

567     protected void createKeyFile(RepositoryConfig config, String JavaDoc user,
568         String JavaDoc password) throws RepositoryException
569     {
570         final PEFileLayout layout = getFileLayout(config);
571         final File JavaDoc src = layout.getKeyFileTemplate();
572         final File JavaDoc dest = layout.getKeyFile();
573         try {
574             FileUtils.copy(src, dest);
575             /* This keyfile is simply a copy of the template as by default
576                at the domain creation time, we do not add administrative user
577                to it. J2EE application users will be added to this file later.
578             */

579         } catch (Exception JavaDoc e) {
580             throw new RepositoryException(_strMgr.getString("keyFileNotCreated"), e);
581         }
582     }
583     
584     
585     /** Modifies the contents of given keyfile with administrator's user-name
586      * and password. Uses the FileRealm classes that application server's
587      * Runtime uses.
588     */

589     private void modifyKeyFile(File JavaDoc keyFile, String JavaDoc user, String JavaDoc password) throws
590     IOException JavaDoc, BadRealmException, IASSecurityException,
591         NoSuchRealmException
592     {
593         final String JavaDoc keyFilePath = keyFile.getAbsolutePath();
594         final FileRealm fileRealm = new FileRealm(keyFilePath);
595         final String JavaDoc[] group =
596             new String JavaDoc[]{AdminConstants.DOMAIN_ADMIN_GROUP_NAME};
597         fileRealm.addUser(user, password, group);
598         fileRealm.writeKeyFile(keyFilePath);
599         appendKeyFileComment(keyFilePath);
600     }
601     
602     private void appendKeyFileComment(String JavaDoc fileName)
603     {
604         final String JavaDoc commentLine = NEW_LINE + _strMgr.getString("adminUserComment");
605         FileUtils.appendText(fileName, commentLine);
606     }
607    
608     /**
609      * Create the default server.policy file.
610      */

611     protected void createServerPolicyFile(RepositoryConfig config) throws RepositoryException
612     {
613         final PEFileLayout layout = getFileLayout(config);
614         final File JavaDoc src = layout.getPolicyFileTemplate();
615         final File JavaDoc dest = layout.getPolicyFile();
616         try {
617             FileUtils.copy(src, dest);
618         } catch (IOException JavaDoc ioe) {
619             throw new RepositoryException(
620                 _strMgr.getString("serverPolicyNotCreated"), ioe);
621         }
622     }
623     
624     /**
625      * We validate the master password by trying to open the password alias keystore.
626      * This means that the keystore must already exist.
627      * @param config
628      * @param password
629      * @throws RepositoryException
630      */

631     public void validateMasterPassword(RepositoryConfig config,
632         String JavaDoc password) throws RepositoryException
633     {
634         final PEFileLayout layout = getFileLayout(config);
635         final File JavaDoc passwordAliases = layout.getPasswordAliasKeystore();
636         try {
637             PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(),
638                 password.toCharArray());
639         } catch (IOException JavaDoc ex) {
640             throw new RepositoryException(_strMgr.getString("masterPasswordInvalid"));
641         } catch (Exception JavaDoc ex) {
642             throw new RepositoryException(
643                 _strMgr.getString("couldNotValidateMasterPassword", passwordAliases), ex);
644         }
645     }
646     
647     /**
648      * retrieve clear password from password alias keystore
649      * @param config
650      * @param password
651      * @param alias for which the clear text password would returns
652      * @throws RepositoryException
653      */

654     public String JavaDoc getClearPasswordForAlias(RepositoryConfig config,
655         String JavaDoc password,String JavaDoc alias) throws RepositoryException
656     {
657         final PEFileLayout layout = getFileLayout(config);
658         final File JavaDoc passwordAliases = layout.getPasswordAliasKeystore();
659         try {
660             PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(),
661                 password.toCharArray());
662             String JavaDoc clearPwd = p.getPasswordForAlias(alias);
663             return clearPwd;
664         } catch (Exception JavaDoc ex) {
665             return null;
666         }
667     }
668     
669     public void validateAdminUserAndPassword(RepositoryConfig config,
670         String JavaDoc user, String JavaDoc password) throws RepositoryException
671     {
672         try {
673             //Read in domain.xml. This will fail with a ConfigException if there is no domain.xml
674
final PEFileLayout layout = getFileLayout(config);
675             ConfigContext configContext = getConfigContext(config);
676             //Fetch the name of the realm for the DAS system jmx connector
677
String JavaDoc dasName = ServerHelper.getDAS(configContext).getName();
678             JmxConnector conn = ServerHelper.getServerSystemConnector(configContext,
679                 dasName);
680             String JavaDoc realmName = conn.getAuthRealmName();
681             SecurityService security = ServerHelper.getConfigForServer(configContext,
682                 dasName).getSecurityService();
683             //Load in the file realm
684
//Before loading the realm, we must ensure that com.sun.aas.instanceRoot
685
//is set correcty, since the keyfile is most likely referenced using this.
686
//In addition java.security.auth.login.config must be setup.
687
String JavaDoc oldRoot = System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);
688             String JavaDoc oldConf = System.getProperty("java.security.auth.login.config");
689             System.setProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY,
690                 layout.getRepositoryDir().getAbsolutePath());
691             System.setProperty("java.security.auth.login.config",
692                 layout.getLoginConf().getAbsolutePath());
693             RealmConfig.createRealms(realmName,
694                 new AuthRealm[] {security.getAuthRealmByName(realmName)});
695             //Restore previous values just in case.
696
if (oldRoot != null) {
697                 System.setProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY, oldRoot);
698             }
699             if (oldConf != null) {
700                 System.setProperty("java.security.auth.login.config", oldConf);
701             }
702             //Finally do the authentication of user and password
703
final ASJMXAuthenticator authenticator = new ASJMXAuthenticator();
704             authenticator.setRealmName(realmName);
705             authenticator.setLoginDriver(new ASLoginDriverImpl());
706             authenticator.authenticate(new String JavaDoc[] {user, password});
707         } catch (Exception JavaDoc ex) {
708             throw new RepositoryException(
709                 _strMgr.getString("couldNotValidateMasterPassword", user), ex);
710         }
711     }
712     
713     /**
714      * Create the password alias keystore (initially empty)
715      * @param config
716      * @param password password protecting the keystore
717      * @throws RepositoryException
718      */

719     protected void createPasswordAliasKeystore(RepositoryConfig config,
720         String JavaDoc password) throws RepositoryException
721     {
722         final PEFileLayout layout = getFileLayout(config);
723         final File JavaDoc passwordAliases = layout.getPasswordAliasKeystore();
724         try {
725             PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(),
726                 password.toCharArray());
727             p.writeStore();
728         } catch (Exception JavaDoc ex) {
729             throw new RepositoryException(
730                 _strMgr.getString("passwordAliasKeystoreNotCreated", passwordAliases), ex);
731         }
732     }
733     
734     /**
735      * Change the password protecting the password alias keystore
736      * @param config
737      * @param oldPassword old password
738      * @param newPassword new password
739      * @throws RepositoryException
740      */

741     protected void changePasswordAliasKeystorePassword(RepositoryConfig config,
742         String JavaDoc oldPassword, String JavaDoc newPassword) throws RepositoryException
743     {
744         final PEFileLayout layout = getFileLayout(config);
745         final File JavaDoc passwordAliases = layout.getPasswordAliasKeystore();
746             
747         //Change the password of the keystore alias file
748
if (passwordAliases.exists()) {
749             try {
750                 PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(),
751                     oldPassword.toCharArray());
752                 p.changePassword(newPassword.toCharArray());
753             } catch (Exception JavaDoc ex) {
754                 throw new RepositoryException(
755                     _strMgr.getString("passwordAliasPasswordNotChanged", passwordAliases), ex);
756             }
757         }
758     }
759
760     /**
761      * Create MQ instance.
762      */

763     protected void createMQInstance(
764         RepositoryConfig config) throws RepositoryException
765     {
766         final PEFileLayout layout = getFileLayout(config);
767         final File JavaDoc broker = layout.getImqBrokerExecutable();
768         final File JavaDoc mqVarHome = layout.getImqVarHome();
769         try {
770             mqVarHome.mkdirs();
771             final List JavaDoc cmdInput = new ArrayList JavaDoc();
772             cmdInput.add(broker.getAbsolutePath());
773             cmdInput.add("-init");
774             cmdInput.add("-varhome");
775             cmdInput.add(mqVarHome.getAbsolutePath());
776             ProcessExecutor pe = new ProcessExecutor
777             ((String JavaDoc[])cmdInput.toArray(new String JavaDoc[cmdInput.size()]));
778             pe.execute(false, false);
779         } catch (Exception JavaDoc ioe) {
780              /*
781              Dont do anything.
782
783              IMQ instance is created just to make sure that
784              Off line IMQ commands can be executed, even before
785              starting the broker. A typical scenario is while
786              on-demand startup is off, user might try to do
787              imqusermgr. Here broker may not have started.
788
789              Failure in creating the instance doesnt need to
790              abort domain creation.
791              */

792         }
793     }
794
795       
796     /**
797      * Create the timer database wal file.
798      */

799     protected void createTimerWal(
800         RepositoryConfig config) throws RepositoryException
801     {
802         final PEFileLayout layout = getFileLayout(config);
803         final File JavaDoc src = layout.getTimerWalTemplate();
804         final File JavaDoc dest = layout.getTimerWal();
805         try {
806             FileUtils.copy(src, dest);
807         } catch (IOException JavaDoc ioe) {
808             throw new RepositoryException(
809                 _strMgr.getString("timerWalNotCreated"), ioe);
810         }
811     }
812
813     /**
814      * Create the timer database dbn file.
815      */

816     protected void createTimerDbn(
817         RepositoryConfig config) throws RepositoryException
818     {
819         final PEFileLayout layout = getFileLayout(config);
820     final File JavaDoc src = layout.getTimerDbnTemplate();
821         final File JavaDoc dest = layout.getTimerDbn();
822         try {
823             FileUtils.copy(src, dest);
824         } catch (IOException JavaDoc ioe) {
825             throw new RepositoryException(
826                 _strMgr.getString("timerDbnNotCreated"), ioe);
827         }
828     }
829
830     protected void handleDerby(final RepositoryConfig config) throws RepositoryException {
831         final String JavaDoc DL = "derby.log"; // this is the file that derby creates its log in.
832
final File JavaDoc derbyLog = new File JavaDoc(DL);
833         try {
834             final PEFileLayout layout = getFileLayout(config);
835             final File JavaDoc derbySqlFile = layout.getDerbyEjbTimerSqlFile();
836             final String JavaDoc tableStatement = formatSqlStatement(derbySqlFile);
837             final String JavaDoc dbDir = layout.getDerbyEjbTimerDatabaseDirectory().getAbsolutePath();
838             createEjbTimerDatabaseTable(tableStatement, dbDir);
839         } catch (final Exception JavaDoc ae) {
840             final String JavaDoc c = readDerbyLogFile(derbyLog);
841             throw new RepositoryException(_strMgr.getString("derbyEjbTimerDBNotCreated", c), ae);
842         } finally {
843             System.gc();
844             final boolean d = derbyLog.delete();
845             if (!d)
846                 derbyLog.deleteOnExit();
847         }
848     }
849     /** A very rudimentary method to read the sql file and get the large
850      * create-table statement out of it. This statement needs to be the first
851      * statement in the file.
852      */

853     private String JavaDoc formatSqlStatement(final File JavaDoc sqlf) throws Exception JavaDoc {
854         final StringBuilder JavaDoc sb = new StringBuilder JavaDoc(); //use it whenever possible!
855
final char SQL_DELIMITER = ';';
856         final BufferedReader JavaDoc br = new BufferedReader JavaDoc(new FileReader JavaDoc(sqlf));
857         String JavaDoc line = null;
858         try {
859             while ((line = br.readLine())!= null) {
860                 line = line.replaceAll("\\t", " ");
861                 sb.append(line);
862                 if (line.indexOf(SQL_DELIMITER) != -1)
863                     break;
864             }
865         } finally {
866             br.close();
867         }
868         //this line should contain "create table" ..., but no check for now
869
String JavaDoc fs = sb.toString();
870         final int indexOfSemiColon = fs.indexOf(SQL_DELIMITER);
871         if (indexOfSemiColon != -1) {
872             fs = fs.substring(0, indexOfSemiColon);
873         }
874         if (Boolean.getBoolean(DEBUG)) {
875             System.out.println(fs);
876         }
877         
878         return ( fs );
879     }
880
881     private void createEjbTimerDatabaseTable(final String JavaDoc createStatement, final String JavaDoc dbDir) throws Exception JavaDoc {
882         checkDerbyDriver();
883         final String JavaDoc url = getDatabaseUrl(dbDir);
884         final Connection JavaDoc conn = DriverManager.getConnection(url);
885         deleteTable(conn);
886         final Statement JavaDoc cs = conn.createStatement();
887         cs.executeUpdate(createStatement);
888     }
889     
890     private void deleteTable(final Connection JavaDoc conn) {
891         try {
892             final Statement JavaDoc ds = conn.createStatement();
893             final String JavaDoc deleteTable = "delete table " + PEFileLayout.EJB_TIMER_TABLE_NAME;
894             ds.executeUpdate(deleteTable);
895         } catch (final Exception JavaDoc e) {} // just to make sure that table is deleted
896
}
897     private String JavaDoc getDatabaseUrl(final String JavaDoc dbDir) {
898         final StringBuilder JavaDoc sb = new StringBuilder JavaDoc("jdbc:derby:");
899         sb.append(FileUtils.makeForwardSlashes(dbDir));
900         sb.append(";create=true");
901         return (sb.toString());
902     }
903     private void checkDerbyDriver() throws Exception JavaDoc {
904         final String JavaDoc DERBY_DRIVER_CLASS_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
905         Class.forName(DERBY_DRIVER_CLASS_NAME);
906     }
907     
908     /** By default, </code> derby database will create a file called "derby.log" in the
909      * current directory </code> when embedded
910      * database is created. We need the contents to be read and returned as a String.
911      * It is expected that this file is not huge. Use judiciously. It is being used
912      * only to return the errors in case the embedded database could not be created.
913      * Under normal circumstances, database creation should *always* succeed while
914      * creating the domain.
915      */

916     private String JavaDoc readDerbyLogFile(final File JavaDoc log) {
917         final StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
918         try {
919             final String JavaDoc s = FileUtils.readSmallFile(log);
920             sb.append(s);
921         } catch (final Exception JavaDoc e) {
922             final String JavaDoc msg = _strMgr.getString("noDerbyLog");
923             sb.append(msg);
924         }
925         return ( sb.toString() );
926     }
927     /**
928      * A ConfigContext is maintained. The resetConfigContext method can be called to
929      * reset the ConfigContext, causing getConfigContext() to reread the config contex
930      * from disk.
931      */

932     protected synchronized void resetConfigContext()
933     {
934         _configContext = null;
935     }
936     
937     protected synchronized ConfigContext getConfigContext(RepositoryConfig config)
938         throws ConfigException
939     {
940         if (_configContext == null) {
941             final PEFileLayout layout = getFileLayout(config);
942             _configContext = ConfigFactory.createConfigContext(
943                 layout.getDomainConfigFile().getAbsolutePath());
944         }
945         return _configContext;
946     }
947     
948     /**
949      * Cleans the mq broker instances created for all the
950      * server instances that are managed by this domain.
951      * This method is added to this class for the following reasons
952      * 1) Depends on the preConditions of the deleteRespository method
953      * - like instance not running.
954      * 2) Requires the repository to exist.
955      * @param config
956      * @throws RepositoryException
957      */

958     void deleteJMSProviderInstance(RepositoryConfig config)
959         throws RepositoryException
960     {
961         final PEFileLayout layout = getFileLayout(config);
962         final String JavaDoc repositoryName = config.getRepositoryName();
963         try
964         {
965             final JMSAdmin jmsAdmin = IASJmsUtil.getJMSAdminFactory().
966                                                     getJMSAdmin();
967             final ConfigContext ctx = getConfigContext(config);
968             final Server[] servers = getServers(ctx);
969             for (int i = 0; i < servers.length; i++)
970             {
971                 final String JavaDoc mqInstanceName = IASJmsUtil.getBrokerInstanceName(
972                     repositoryName,
973                     servers[i].getName(),
974                     getJmsService(servers[i], ctx));
975                 final String JavaDoc javaHome = getJavaHome(servers[i], ctx);
976
977                 try
978                 {
979             String JavaDoc iMQBin = System.getProperty(
980                                   SystemPropertyConstants.IMQ_BIN_PROPERTY,
981                       layout.getImqBinDir().getAbsolutePath());
982             String JavaDoc iMQInstances = layout.getRepositoryDir() + File.separator +
983                                   IASJmsUtil.MQ_DIR_NAME;
984             String JavaDoc[] optArgs = new String JavaDoc[4];
985
986             optArgs[0] = "-javahome";
987             optArgs[1] = javaHome;
988             optArgs[2] = "-varhome";
989             optArgs[3] = iMQInstances;
990
991                     //4966940
992
jmsAdmin.deleteProviderInstance(
993                 iMQBin,
994             optArgs,
995                         mqInstanceName);
996                     //4966940
997
}
998                 catch (JMSException JavaDoc jmse)
999                 {
1000                    /*
1001                      Eating the exception for now. This exception will
1002                      be thrown even in cases whre the broker instance
1003                      was not yet created (broker instance is created
1004                      only during server startup).
1005                     */

1006                }
1007            }
1008        }
1009        catch (Exception JavaDoc e)
1010        {
1011            throw new RepositoryException(
1012                _strMgr.getString("cannotDeleteJmsProviderInstance"), e);
1013        }
1014    }
1015
1016    protected String JavaDoc[] getInteractiveOptions(String JavaDoc user, String JavaDoc password,
1017        String JavaDoc masterPassword, HashMap JavaDoc extraPasswords)
1018    {
1019        int numKeys = extraPasswords == null ? 0 : extraPasswords.size();
1020        String JavaDoc[] options = new String JavaDoc[3 + numKeys];
1021        // set interativeOptions for security to hand to starting process from ProcessExecutor
1022
options[0] = user;
1023        options[1] = password;
1024        options[2] = masterPassword;
1025        if (extraPasswords != null) {
1026            Iterator JavaDoc it = extraPasswords.keySet().iterator();
1027            String JavaDoc key = null;
1028            for (int i = 0; i < numKeys; i++) {
1029                key = (String JavaDoc)it.next();
1030                options[3 + i] = key + "=" + (String JavaDoc)extraPasswords.get(key);
1031            }
1032        }
1033        return options;
1034    }
1035    
1036    private static Server[] getServers(ConfigContext ctx)
1037        throws ConfigException
1038    {
1039        return ServerHelper.getServersInDomain(ctx);
1040    }
1041
1042    private static String JavaDoc getJavaHome(Server server, ConfigContext ctx)
1043        throws ConfigException
1044    {
1045        final JavaConfig javaConfig = getConfig(server, ctx).getJavaConfig();
1046        return javaConfig.getJavaHome();
1047    }
1048
1049    private static JmsService getJmsService(Server server, ConfigContext ctx)
1050        throws ConfigException
1051    {
1052        return getConfig(server, ctx).getJmsService();
1053    }
1054
1055    private static Config getConfig(Server server, ConfigContext ctx)
1056        throws ConfigException
1057    {
1058        return ServerHelper.getConfigForServer(ctx, server.getName());
1059    }
1060}
1061
Popular Tags