FileDocCategorySizeDatePackage
RepositoryManager.javaAPI DocGlassfish v2 API49656Thu Jul 26 16:33:46 BST 2007com.sun.enterprise.admin.servermgmt

RepositoryManager

public class RepositoryManager extends MasterPasswordFileManager
The RepositoryManager serves as a common base class for the following PEDomainsManager, PEInstancesManager, AgentManager (the SE Node Agent). Its purpose is to abstract out any shared functionality related to lifecycle management of domains, instances and node agents. This includes creation, deletion, listing, and starting and stopping.
author
kebbs

Fields Summary
protected static final String
CERTUTIL_CMD
protected static final String
NEW_LINE
private static final com.sun.enterprise.util.i18n.StringManager
_strMgr
private com.sun.enterprise.config.ConfigContext
_configContext
protected RepositoryManagerMessages
_messages
public static final String
DEBUG
Constructors Summary
public RepositoryManager()
Creates a new instance of RepositoryManager


           
      
        super();
        setMessages(new RepositoryManagerMessages(
            StringManager.getManager(PEDomainsManager.class),
            "illegalDomainName", 
            "domainName", "domainsRoot", "domainExists", 
            "domainDoesntExist", "domainDirNotValid", 
            "cannotDeleteDomainDir", "invalidDomainDir",
            "listDomainElement", "cannotDeleteInstance_invalidState",
            "instanceStartupException", "cannotStartInstance_invalidState",
            "startInstanceTimeOut", "portConflict", "startupFailed",
            "cannotStopInstance_invalidState",
            "cannotStopInstance", "timeoutStarting"));
    
Methods Summary
private voidappendKeyFileComment(java.lang.String fileName)

        
        final String commentLine = NEW_LINE + _strMgr.getString("adminUserComment");
        FileUtils.appendText(fileName, commentLine);
    
protected voidchangePasswordAliasKeystorePassword(RepositoryConfig config, java.lang.String oldPassword, java.lang.String newPassword)
Change the password protecting the password alias keystore

param
config
param
oldPassword old password
param
newPassword new password
throws
RepositoryException

        final PEFileLayout layout = getFileLayout(config);
        final File passwordAliases = layout.getPasswordAliasKeystore();
            
        //Change the password of the keystore alias file
        if (passwordAliases.exists()) {
            try {
                PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(), 
                    oldPassword.toCharArray());
                p.changePassword(newPassword.toCharArray());
            } catch (Exception ex) {
                throw new RepositoryException(
                    _strMgr.getString("passwordAliasPasswordNotChanged", passwordAliases), ex);
            }
        }            
    
private voidcheckDerbyDriver()

        final String DERBY_DRIVER_CLASS_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
        Class.forName(DERBY_DRIVER_CLASS_NAME);
    
protected voidcheckRepository(RepositoryConfig config)

        checkRepository(config, true, true);
    
public voidcheckRepository(RepositoryConfig config, boolean existingRepository)

        checkRepository(config, existingRepository, true);
    
public voidcheckRepository(RepositoryConfig config, boolean existingRepository, boolean checkRootDir)
Sanity check on the repository. This is executed prior to create/delete/start/stop.

   
        String repositoryName = config.getDisplayName();

        //check domain name for validity
        new RepositoryNameValidator(getMessages().getRepositoryNameMessage()).
            validate(repositoryName);
      
        if (checkRootDir || existingRepository) {
            //check domain root directory is read/writable
            new FileValidator(getMessages().getRepositoryRootMessage(), "drw").validate(
                config.getRepositoryRoot());
        }
        
        //check installation root directory is readable
        new FileValidator(_strMgr.getString("installRoot"), "dr").validate(
            config.getInstallRoot());
         
        //Ensure that the domain exists or does not exist
        if (existingRepository) {
            if (!repositoryExists(config)) {
                if (Boolean.getBoolean(DEBUG)) {
                    throw new RepositoryException(
                        getMessages().getNoExistsMessage(repositoryName,
                                                         getBigNoExistsMessage(config)));
                }
                else {
                    throw new RepositoryException(
                        getMessages().getNoExistsMessage(repositoryName,
                                                         getRepositoryDir(config).getAbsolutePath()));
                }
            } else if (!isValidRepository(config)) {
                throw new RepositoryException(
                    getMessages().getRepositoryNotValidMessage(
                        getRepositoryDir(config).getAbsolutePath()));
            }
        } else {
            if (repositoryExists(config)) {
                throw new RepositoryException(
                    getMessages().getExistsMessage(repositoryName,
                        getRepositoryRootDir(config).getAbsolutePath()));
            }
        }
    
protected voidcreateAdminKeyFile(RepositoryConfig config, java.lang.String user, java.lang.String clearPwd)
This method creates a separate administrative keyfile. This is to separate the administrative users from other users. All the administrative operations will be authenticated against this file realm by default.

see
PEFileLayout#ADMIN_KEY_FILE

        final PEFileLayout layout = getFileLayout(config);
        final File src = layout.getKeyFileTemplate();
        final File dest = layout.getAdminKeyFile();      
        try {
            FileUtils.copy(src, dest);
            modifyKeyFile(dest, user, clearPwd);
        } catch (final Exception e) {
            throw new RepositoryException(_strMgr.getString("keyFileNotCreated"), e);
        }
    
private voidcreateEjbTimerDatabaseTable(java.lang.String createStatement, java.lang.String dbDir)

        checkDerbyDriver();
        final String url = getDatabaseUrl(dbDir);
        final Connection conn = DriverManager.getConnection(url);
        deleteTable(conn);
        final Statement cs = conn.createStatement();
        cs.executeUpdate(createStatement);
    
public voidcreateHttpBCInstallRoot(com.sun.enterprise.admin.servermgmt.pe.PEFileLayout layout)
This method is used to create httpsoapbc install root

param
layout PEFileLayout


        FileUtils.copy(
               layout.getHttpBcArchiveSource(), 
               layout.getHttpBcArchiveDestination());
 
        ZipFile zf = new ZipFile(layout.getHttpBcArchiveSource(), layout.getHttpBcInstallRoot());
        ArrayList list = zf.explode();
    
protected voidcreateJBIInstance(java.lang.String instanceName, RepositoryConfig config)
Create JBI instance.

        final PEFileLayout layout = getFileLayout(config);
        layout.createJBIDirectories();
        final TokenValueSet tvSet = new TokenValueSet();
        final String tvDelimiter = "@";
        final String tJbiInstanceName = "JBI_INSTANCE_NAME";
        final String tJbiInstanceRoot = "JBI_INSTANCE_ROOT";
        try {

            final TokenValue tvJbiInstanceName = new TokenValue(tJbiInstanceName, 
                  instanceName, tvDelimiter);
            final TokenValue tvJbiInstanceRoot = new TokenValue(tJbiInstanceRoot, 
                  layout.getRepositoryDir().getCanonicalPath(),tvDelimiter);
            tvSet.add(tvJbiInstanceName);
            tvSet.add(tvJbiInstanceRoot);
            final File src = layout.getJbiTemplateFile();
            final File dest = layout.getJbiRegistryFile();

            generateFromTemplate(tvSet, src, dest);
            
            final File httpConfigSrc = layout.getHttpBcConfigTemplate();
            final File httpConfigDest = layout.getHttpBcConfigFile();
            //tokens will be added in a follow-up integration 
            final TokenValueSet httpTvSet = new TokenValueSet();            
            generateFromTemplate(httpTvSet, httpConfigSrc, httpConfigDest);
            
            createHttpBCInstallRoot(layout);
            createJavaEESEInstallRoot(layout);
            createWSDLSLInstallRoot(layout);
            
        } catch (Exception ioe) {
            throw new RepositoryException(
                _strMgr.getString("jbiRegistryFileNotCreated"), ioe);
        }
    
public voidcreateJavaEESEInstallRoot(com.sun.enterprise.admin.servermgmt.pe.PEFileLayout layout)
This method is used to create Java EESE install root

param
layout PEFileLayout

        FileUtils.copy(
               layout.getJavaEESEArchiveSource(), 
               layout.getJavaEESEArchiveDestination());
       
        ZipFile zf = new ZipFile(layout.getJavaEESEArchiveSource(), layout.getJavaEESEInstallRoot());
        ArrayList list = zf.explode();
    
protected voidcreateKeyFile(RepositoryConfig config, java.lang.String user, java.lang.String password)
Create the FileRealm kefile from the given user and password.

        final PEFileLayout layout = getFileLayout(config);
        final File src = layout.getKeyFileTemplate();
        final File dest = layout.getKeyFile();
        try {
            FileUtils.copy(src, dest);
            /* This keyfile is simply a copy of the template as by default
               at the domain creation time, we do not add administrative user
               to it. J2EE application users will be added to this file later.
            */
        } catch (Exception e) {
            throw new RepositoryException(_strMgr.getString("keyFileNotCreated"), e);
        }
    
protected voidcreateMQInstance(RepositoryConfig config)
Create MQ instance.

        final PEFileLayout layout = getFileLayout(config);
        final File broker = layout.getImqBrokerExecutable();
        final File mqVarHome = layout.getImqVarHome();
        try {
            mqVarHome.mkdirs();
            final List cmdInput = new ArrayList();
            cmdInput.add(broker.getAbsolutePath()); 
            cmdInput.add("-init");
            cmdInput.add("-varhome");
            cmdInput.add(mqVarHome.getAbsolutePath());
            ProcessExecutor pe = new ProcessExecutor
            ((String[])cmdInput.toArray(new String[cmdInput.size()]));
            pe.execute(false, false);
        } catch (Exception ioe) {
             /*
             Dont do anything. 

             IMQ instance is created just to make sure that 
             Off line IMQ commands can be executed, even before
             starting the broker. A typical scenario is while 
             on-demand startup is off, user might try to do
             imqusermgr. Here broker may not have started.

             Failure in creating the instance doesnt need to 
             abort domain creation.
             */
        }
    
protected voidcreatePasswordAliasKeystore(RepositoryConfig config, java.lang.String password)
Create the password alias keystore (initially empty)

param
config
param
password password protecting the keystore
throws
RepositoryException

        
        final PEFileLayout layout = getFileLayout(config);
        final File passwordAliases = layout.getPasswordAliasKeystore();
        try {
            PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(), 
                password.toCharArray());
            p.writeStore();
        } catch (Exception ex) {
            throw new RepositoryException(
                _strMgr.getString("passwordAliasKeystoreNotCreated", passwordAliases), ex);
        }
    
protected voidcreateServerPolicyFile(RepositoryConfig config)
Create the default server.policy file.

        final PEFileLayout layout = getFileLayout(config);
        final File src = layout.getPolicyFileTemplate();
        final File dest = layout.getPolicyFile();
        try {
            FileUtils.copy(src, dest);
        } catch (IOException ioe) {
            throw new RepositoryException(
                _strMgr.getString("serverPolicyNotCreated"), ioe);
        }
    
protected voidcreateTimerDbn(RepositoryConfig config)
Create the timer database dbn file.

        final PEFileLayout layout = getFileLayout(config);
    final File src = layout.getTimerDbnTemplate();
        final File dest = layout.getTimerDbn();
        try {
            FileUtils.copy(src, dest);
        } catch (IOException ioe) {
            throw new RepositoryException(
                _strMgr.getString("timerDbnNotCreated"), ioe);
        }
    
protected voidcreateTimerWal(RepositoryConfig config)
Create the timer database wal file.

        final PEFileLayout layout = getFileLayout(config);
        final File src = layout.getTimerWalTemplate();
        final File dest = layout.getTimerWal();
        try {
            FileUtils.copy(src, dest);
        } catch (IOException ioe) {
            throw new RepositoryException(
                _strMgr.getString("timerWalNotCreated"), ioe);
        }
    
public voidcreateWSDLSLInstallRoot(com.sun.enterprise.admin.servermgmt.pe.PEFileLayout layout)
This method is used to create WSDLSL install root

param
layout PEFileLayout

        FileUtils.copy(
               layout.getWSDLSLArchiveSource(), 
               layout.getWSDLSLArchiveDestination());
        
        ZipFile zf = new ZipFile(layout.getWSDLSLArchiveSource(), layout.getWSDLSLInstallRoot());
        ArrayList list = zf.explode();

    
voiddeleteJMSProviderInstance(RepositoryConfig config)
Cleans the mq broker instances created for all the server instances that are managed by this domain. This method is added to this class for the following reasons 1) Depends on the preConditions of the deleteRespository method - like instance not running. 2) Requires the repository to exist.

param
config
throws
RepositoryException

        final PEFileLayout layout = getFileLayout(config);
        final String repositoryName = config.getRepositoryName();
        try
        {
            final JMSAdmin jmsAdmin = IASJmsUtil.getJMSAdminFactory().
                                                    getJMSAdmin();
            final ConfigContext ctx = getConfigContext(config);
            final Server[] servers = getServers(ctx);
            for (int i = 0; i < servers.length; i++)
            {
                final String mqInstanceName = IASJmsUtil.getBrokerInstanceName(
                    repositoryName, 
                    servers[i].getName(), 
                    getJmsService(servers[i], ctx));
                final String javaHome = getJavaHome(servers[i], ctx);

                try
                {
            String iMQBin = System.getProperty(
                                  SystemPropertyConstants.IMQ_BIN_PROPERTY,
                      layout.getImqBinDir().getAbsolutePath());
            String iMQInstances = layout.getRepositoryDir() + File.separator +
                                  IASJmsUtil.MQ_DIR_NAME;
            String[] optArgs = new String[4];

            optArgs[0] = "-javahome";
            optArgs[1] = javaHome;
            optArgs[2] = "-varhome";
            optArgs[3] = iMQInstances;

                    //4966940
                    jmsAdmin.deleteProviderInstance(
                iMQBin,
            optArgs,
                        mqInstanceName);
                    //4966940
                }
                catch (JMSException jmse)
                {
                    /*
                      Eating the exception for now. This exception will
                      be thrown even in cases whre the broker instance
                      was not yet created (broker instance is created
                      only during server startup).
                     */
                }
            }
        }
        catch (Exception e)
        {
            throw new RepositoryException(
                _strMgr.getString("cannotDeleteJmsProviderInstance"), e);
        }
    
protected voiddeleteRepository(RepositoryConfig config)
Deletes the repository (domain, node agent, server instance).

        deleteRepository(config, true);    
    
protected voiddeleteRepository(RepositoryConfig config, boolean deleteJMSProvider)
Deletes the repository (domain, node agent, server instance). If the deleteJMSProvider flag is set, we delete the jms instance. The jms instance is present in the domain only and not when the repository corresponds to a server instance or node agent.

        checkRepository(config, true);
   
        //Ensure that the entity to be deleted is stopped
        final int status = getInstancesManager(config).getInstanceStatus();
        if (status != Status.kInstanceNotRunningCode) {
            throw new RepositoryException(
                getMessages().getCannotDeleteInstanceInvalidState(
                    config.getDisplayName(),
                    Status.getStatusString(status)));
        }

        // FIXME: This is set temporarily so the instances that are deleted
        // don't require domain.xml (instance may never have been started) and it
        // also removes the dependencey on imqadmin.jar.
        // This should ne move in some way to PEDomainsManager since 
        // JMS providers are really only present in the domain and not node agent
        // or server instance.
        if (deleteJMSProvider) {
            deleteJMSProviderInstance(config);
        }
        
        //Blast the directory
        File repository = getRepositoryDir(config);
        try {
            FileUtils.liquidate(repository);
        } catch (Exception e) {
            throw new RepositoryException(getMessages().getCannotDeleteMessage( 
                repository.getAbsolutePath()), e);
        }
       
        //Double check to ensure that it was really deleted
        if (repositoryExists(config)) {
            throw new RepositoryException(
                getMessages().getCannotDeleteMessage(repository.getAbsolutePath()));
        }
    
private voiddeleteTable(java.sql.Connection conn)

        try {
            final Statement ds = conn.createStatement();
            final String deleteTable = "delete table " + PEFileLayout.EJB_TIMER_TABLE_NAME;
            ds.executeUpdate(deleteTable);
        } catch (final Exception e) 
        {
            // There is an excellent chance that an Exception will get
            // thrown -- we are just making sure the table is deleted, if
            // it happens to exist, before creating a fresh new one.  We definitely
            // don't want to throw this back out to the caller.
            // thus -- ignore this Exception
            // wbn July 2007
        } 
    
protected booleandomainUsesNSS(RepositoryConfig rc)

        try {
            final ConfigContext cc = getConfigContext(rc);
            final String sn        = 
                SystemPropertyConstants.DEFAULT_SERVER_INSTANCE_NAME;
            final boolean useNSS   = ServerHelper.serverUsesNss(cc, sn);
            return ( useNSS );
        } catch (final Exception e) {
            throw new RuntimeException(e); //can't recover :)
        }
    
private java.lang.StringformatSqlStatement(java.io.File sqlf)
A very rudimentary method to read the sql file and get the large create-table statement out of it. This statement needs to be the first statement in the file.

        final StringBuilder sb = new StringBuilder(); //use it whenever possible!
        final char SQL_DELIMITER = ';";
        final BufferedReader br = new BufferedReader(new FileReader(sqlf));
        String line = null;
        try {
            while ((line = br.readLine())!= null) {
                line = line.replaceAll("\\t", " ");
                sb.append(line);
                if (line.indexOf(SQL_DELIMITER) != -1)
                    break;
            }
        } finally {
            br.close();  
        }
        //this line should contain "create table" ..., but no check for now
        String fs = sb.toString();
        final int indexOfSemiColon = fs.indexOf(SQL_DELIMITER);
        if (indexOfSemiColon != -1) {
            fs = fs.substring(0, indexOfSemiColon);
        }
        if (Boolean.getBoolean(DEBUG)) {
            System.out.println(fs);
        }
        
        return ( fs );
    
protected voidgenerateFromTemplate(com.sun.enterprise.admin.util.TokenValueSet tokens, java.io.File template, java.io.File destinationFile)

        LineTokenReplacer replacer = new LineTokenReplacer(tokens, "UTF-8");
        replacer.replace(template, destinationFile);
    
private java.lang.StringgetBigNoExistsMessage(RepositoryConfig config)

        File repdir = getRepositoryDir(config);
        File canrepdir = FileUtils.safeGetCanonicalFile(repdir);
        File canrepdirparent = canrepdir.getParentFile();

        String s = "";
        s += "\nRep. Dir:" + repdir;
        s += "\nDump of RepositoryConfig: " + config.toString();
        s += "\nCanonical File: " + canrepdir;
        s += "\nParent File: " + canrepdirparent;

        
        boolean regex = repdir.exists();
        boolean canex = canrepdir.exists();
        boolean parentex = canrepdirparent.exists();
        boolean regdir = repdir.isDirectory();
        boolean candir = canrepdir.isDirectory();
        boolean parentdir = canrepdirparent.isDirectory();
        
        s += "\nrepdir exists: " + regex + ", canon exists: " + canex + ", parent exists: " + parentex +
                ", reg is dir: " + regdir + ", canon isdir: " + candir +
                ", parent is dir: " + parentdir;
        s += "\nInstance root sys property (";
        s += SystemPropertyConstants.INSTANCE_ROOT_PROPERTY;
        s +=  "): ";
        s += System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);
        
        return s;
    
public java.lang.StringgetClearPasswordForAlias(RepositoryConfig config, java.lang.String password, java.lang.String alias)
retrieve clear password from password alias keystore

param
config
param
password
param
alias for which the clear text password would returns
throws
RepositoryException

        final PEFileLayout layout = getFileLayout(config);
        final File passwordAliases = layout.getPasswordAliasKeystore();
        try {
            PasswordAdapter p = new PasswordAdapter(passwordAliases.getAbsolutePath(), 
                password.toCharArray());
            String clearPwd = p.getPasswordForAlias(alias);
            return clearPwd;
        } catch (Exception ex) {
            return null;
        }
    
private static com.sun.enterprise.config.serverbeans.ConfiggetConfig(com.sun.enterprise.config.serverbeans.Server server, com.sun.enterprise.config.ConfigContext ctx)

        return ServerHelper.getConfigForServer(ctx, server.getName());        
    
protected synchronized com.sun.enterprise.config.ConfigContextgetConfigContext(RepositoryConfig config)

        if (_configContext == null) {
            final PEFileLayout layout = getFileLayout(config);
            _configContext = ConfigFactory.createConfigContext(
                layout.getDomainConfigFile().getAbsolutePath());
        }
        return _configContext;
    
protected RepositoryConfiggetConfigForRepositoryStatus(RepositoryConfig config, java.lang.String repository)

        //The repository here corresponds to either the domain or node agent name
        return new RepositoryConfig(repository, config.getRepositoryRoot());
    
private java.lang.StringgetDatabaseUrl(java.lang.String dbDir)

        final StringBuilder sb = new StringBuilder("jdbc:derby:");
        sb.append(FileUtils.makeForwardSlashes(dbDir));
        sb.append(";create=true");
        return (sb.toString());
    
public InstancesManagergetInstancesManager(RepositoryConfig config)

        return new PEInstancesManager(config);
    
protected java.lang.String[]getInteractiveOptions(java.lang.String user, java.lang.String password, java.lang.String masterPassword, java.util.HashMap extraPasswords)

        
        int numKeys = extraPasswords == null ? 0 : extraPasswords.size();
        String[] options = new String[3 + numKeys];
        // set interativeOptions for security to hand to starting process from ProcessExecutor
        options[0] = user;
        options[1] = password;
        options[2] = masterPassword;
        if (extraPasswords != null) {
            Iterator it = extraPasswords.keySet().iterator();
            String key = null;
            for (int i = 0; i < numKeys; i++) {
                key = (String)it.next();
                options[3 + i] = key + "=" + (String)extraPasswords.get(key);
            }
        }
        return options;
    
private static java.lang.StringgetJavaHome(com.sun.enterprise.config.serverbeans.Server server, com.sun.enterprise.config.ConfigContext ctx)

        final JavaConfig javaConfig = getConfig(server, ctx).getJavaConfig();
        return javaConfig.getJavaHome();
    
private static com.sun.enterprise.config.serverbeans.JmsServicegetJmsService(com.sun.enterprise.config.serverbeans.Server server, com.sun.enterprise.config.ConfigContext ctx)

        return getConfig(server, ctx).getJmsService();
    
protected com.sun.enterprise.admin.servermgmt.RepositoryManager$RepositoryManagerMessagesgetMessages()

        return _messages;
    
protected java.io.FilegetRepositoryDir(RepositoryConfig config)

        return getFileLayout(config).getRepositoryDir();
    
protected java.io.FilegetRepositoryRootDir(RepositoryConfig config)

        return getFileLayout(config).getRepositoryRootDir();
    
public RuntimeStatusListgetRuntimeStatus(RepositoryConfig config)
Return all repositories (domains, node agents, server instances) and their corresponding status (e.g. running or stopped)

        String[] repositories = listRepository(config);

        RuntimeStatusList result = new RuntimeStatusList(repositories.length);
        int status;
        for (int i = 0; i < repositories.length; i++) {
            final InstancesManager mgr = getInstancesManager(
                getConfigForRepositoryStatus(config, repositories[i]));
            result.add(RuntimeStatus.getRuntimeStatus(repositories[i], mgr));
        }
        return result;
    
private static com.sun.enterprise.config.serverbeans.Server[]getServers(com.sun.enterprise.config.ConfigContext ctx)

        return ServerHelper.getServersInDomain(ctx);        
    
protected voidhandleDerby(RepositoryConfig config)

        final String DL = "derby.log"; // this is the file that derby creates its log in.
        final File derbyLog = new File(DL);
        try {
            final PEFileLayout layout = getFileLayout(config);
            final File derbySqlFile = layout.getDerbyEjbTimerSqlFile();
            final String tableStatement = formatSqlStatement(derbySqlFile);
            final String dbDir = layout.getDerbyEjbTimerDatabaseDirectory().getAbsolutePath();
            createEjbTimerDatabaseTable(tableStatement, dbDir);
        } catch (final Exception ae) {
            final String c = readDerbyLogFile(derbyLog);
            throw new RepositoryException(_strMgr.getString("derbyEjbTimerDBNotCreated", c), ae);
        } finally {
            if(!derbyLog.delete())
                derbyLog.deleteOnExit();
        }
    
public static booleanisNSSSupportAvailable()
Determines if the NSS support is available in this installation. The check involves availability of the certutil executable.

return
true if certutil exists false otherwise

        File certUtilFile = null;
        if (OS.isWindows()) {
            certUtilFile = new File(CERTUTIL_CMD + ".exe");
        } else {
            certUtilFile = new File(CERTUTIL_CMD);
        }
        if (certUtilFile.exists()) {
            return ( true );
        }
        return ( false );
    
protected booleanisValidRepository(java.io.File f)

        return new File(new File(f, PEFileLayout.BIN_DIR),
            PEFileLayout.START_SERV_OS).exists();
    
protected booleanisValidRepository(RepositoryConfig config)

        return getFileLayout(config).getStartServ().exists();
    
protected java.lang.String[]listDomainsAndStatusAsString(RepositoryConfig config)
Return all repositories (domains, node agents, server instances) and their corresponding status (e.g. running or stopped) in string form.

        try {
            RuntimeStatusList statusList = getRuntimeStatus(config); 
            RuntimeStatus status = null;
            String[] result = new String[statusList.size()];
            for (int i = 0; i < statusList.size(); i++) {
                status = statusList.getStatus(i);
                result[i] = getMessages().getListRepositoryElementMessage( 
                    status.getName(), status.toShortString());
            }
            return result;
        } catch (Exception e) {
            throw new RepositoryException(e);
        }        
    
protected java.lang.String[]listRepository(RepositoryConfig config)
Return all repositories (domains, node agents, server instances)

        File repository = getRepositoryRootDir(config);
        String[] dirs = new String[0];
        try {
            File f = repository.getCanonicalFile();
            if (!f.isDirectory()) {
                throw new RepositoryException(getMessages().getInvalidPathMessage(
                    f.getAbsolutePath())); 
            }
            dirs = f.list(new FilenameFilter() {
                //Only accept directories that are valid (contain the property startserv script)
                public boolean accept(File dir, String name) {
                    File f = new File(dir, name);
                    if (!f.isDirectory()) {
                        return false;
                    } else {
                        return isValidRepository(f);
                    }
                }
            });
            if (dirs == null) { 
                dirs = new String[0]; 
            }
        } catch (Exception e) {
            throw new RepositoryException(e);
        }
        return dirs;     
    
private voidmodifyKeyFile(java.io.File keyFile, java.lang.String user, java.lang.String password)
Modifies the contents of given keyfile with administrator's user-name and password. Uses the FileRealm classes that application server's Runtime uses.

        final String keyFilePath = keyFile.getAbsolutePath();
        final FileRealm fileRealm = new FileRealm(keyFilePath);       
        final String[] group = 
            new String[]{AdminConstants.DOMAIN_ADMIN_GROUP_NAME};
        fileRealm.addUser(user, password, group);
        fileRealm.writeKeyFile(keyFilePath);
        appendKeyFileComment(keyFilePath);
    
private java.lang.StringreadDerbyLogFile(java.io.File log)
By default, derby database will create a file called "derby.log" in the current directory when embedded database is created. We need the contents to be read and returned as a String. It is expected that this file is not huge. Use judiciously. It is being used only to return the errors in case the embedded database could not be created. Under normal circumstances, database creation should *always* succeed while creating the domain.

        final StringBuilder sb = new StringBuilder();
        try {
            final String s = FileUtils.readSmallFile(log);
            sb.append(s);
        } catch (final Exception e) {
            final String msg = _strMgr.getString("noDerbyLog");
            sb.append(msg);
        }
        return ( sb.toString() );
    
protected booleanrepositoryExists(RepositoryConfig config)

        return FileUtils.safeGetCanonicalFile(getRepositoryDir(config)).exists();
    
protected synchronized voidresetConfigContext()
A ConfigContext is maintained. The resetConfigContext method can be called to reset the ConfigContext, causing getConfigContext() to reread the config contex from disk.

        _configContext = null;
    
protected voidsetMessages(com.sun.enterprise.admin.servermgmt.RepositoryManager$RepositoryManagerMessages messages)

        _messages = messages;
    
protected voidsetPermissions(RepositoryConfig repositoryConfig)
Sets the permissions for the domain directory, its config directory, startserv/stopserv scripts etc.

                
        final PEFileLayout layout = getFileLayout(repositoryConfig);
        final File domainDir = layout.getRepositoryDir();
        try {                
            chmod("-R 755", domainDir);                                        
        } catch (Exception e) {
            throw new RepositoryException(
                _strMgr.getString("setPermissionError"), e);
        }        
    
public voidvalidateAdminUserAndPassword(RepositoryConfig config, java.lang.String user, java.lang.String password)

        try {       
            //Read in domain.xml. This will fail with a ConfigException if there is no domain.xml
            final PEFileLayout layout = getFileLayout(config);
            ConfigContext configContext = getConfigContext(config);
            //Fetch the name of the realm for the DAS system jmx connector
            String dasName = ServerHelper.getDAS(configContext).getName();            
            JmxConnector conn = ServerHelper.getServerSystemConnector(configContext, 
                dasName);
            String realmName = conn.getAuthRealmName();
            SecurityService security = ServerHelper.getConfigForServer(configContext, 
                dasName).getSecurityService();      
            //Load in the file realm
            //Before loading the realm, we must ensure that com.sun.aas.instanceRoot
            //is set correcty, since the keyfile is most likely referenced using this.
            //In addition java.security.auth.login.config must be setup.
            String oldRoot = System.getProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY);
            String oldConf = System.getProperty("java.security.auth.login.config");
            System.setProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY,
                layout.getRepositoryDir().getAbsolutePath());
            System.setProperty("java.security.auth.login.config",
                layout.getLoginConf().getAbsolutePath());
            RealmConfig.createRealms(realmName, 
                new AuthRealm[] {security.getAuthRealmByName(realmName)}); 
            //Restore previous values just in case.
            if (oldRoot != null) {
                System.setProperty(SystemPropertyConstants.INSTANCE_ROOT_PROPERTY, oldRoot);
            }
            if (oldConf != null) {
                System.setProperty("java.security.auth.login.config", oldConf);
            }
            //Finally do the authentication of user and password
            final ASJMXAuthenticator authenticator = new ASJMXAuthenticator();            
            authenticator.setRealmName(realmName);        
            authenticator.setLoginDriver(new ASLoginDriverImpl());        
            authenticator.authenticate(new String[] {user, password});
        } catch (Exception ex) {       
            throw new RepositoryException(
                _strMgr.getString("couldNotValidateMasterPassword", user), ex);
        }
    
public voidvalidateMasterPassword(RepositoryConfig config, java.lang.String password)
We validate the master password by trying to open the password alias keystore. This means that the keystore must already exist.

param
config
param
password
throws
RepositoryException

        final PEFileLayout layout = getFileLayout(config);
        final File passwordAliases = layout.getPasswordAliasKeystore();
        try {
            // WBN July 2007
            // we are constructing this object ONLY to see if it throws
            // an Exception.  We do not use the object.
            new PasswordAdapter(passwordAliases.getAbsolutePath(), 
                password.toCharArray());
        } catch (IOException ex) {
            throw new RepositoryException(_strMgr.getString("masterPasswordInvalid"));
        } catch (Exception ex) {        
            throw new RepositoryException(
                _strMgr.getString("couldNotValidateMasterPassword", passwordAliases), ex);
        }