public void setUp() {
   super.setUp();
   if (embeddedRegistryService != null) {
     return;
   }
   try {
     embeddedRegistryService = ctx.getEmbeddedRegistryService();
     RealmUnawareRegistryCoreServiceComponent comp =
         new RealmUnawareRegistryCoreServiceComponent();
     comp.setRealmService(ctx.getRealmService());
     comp.registerBuiltInHandlers(embeddedRegistryService);
     // get the realm config to retrieve admin username, password
     RealmConfiguration realmConfig = ctx.getRealmService().getBootstrapRealmConfiguration();
     registry =
         embeddedRegistryService.getConfigUserRegistry(
             realmConfig.getAdminUserName(), realmConfig.getAdminPassword());
     systemRegistry = embeddedRegistryService.getConfigSystemRegistry();
   } catch (RegistryException e) {
     fail("Failed to initialize the registry. Caused by: " + e.getMessage());
   }
 }
  public static DataSource createUserStoreDataSource(RealmConfiguration realmConfig) {
    String dataSourceName = realmConfig.getUserStoreProperty(JDBCRealmConstants.DATASOURCE);
    if (dataSourceName != null) {
      return lookupDataSource(dataSourceName);
    }
    RDBMSConfiguration dsConfig = new RDBMSConfiguration();
    dsConfig.setDriverClassName(realmConfig.getUserStoreProperty(JDBCRealmConstants.DRIVER_NAME));
    if (dsConfig.getDriverClassName() == null) {
      return null;
    }
    dsConfig.setUrl(realmConfig.getUserStoreProperty(JDBCRealmConstants.URL));
    dsConfig.setUsername(realmConfig.getUserStoreProperty(JDBCRealmConstants.USER_NAME));
    dsConfig.setPassword(realmConfig.getUserStoreProperty(JDBCRealmConstants.PASSWORD));

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_ACTIVE) != null
        && !realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_ACTIVE).equals("")) {
      dsConfig.setMaxActive(
          Integer.parseInt(realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_ACTIVE)));
    } else {
      dsConfig.setMaxActive(DEFAULT_MAX_ACTIVE);
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.MIN_IDLE) != null
        && !realmConfig.getUserStoreProperty(JDBCRealmConstants.MIN_IDLE).equals("")) {
      dsConfig.setMinIdle(
          Integer.parseInt(realmConfig.getUserStoreProperty(JDBCRealmConstants.MIN_IDLE)));
    } else {
      dsConfig.setMinIdle(DEFAULT_MIN_IDLE);
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_IDLE) != null
        && !realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_IDLE).equals("")) {
      dsConfig.setMinIdle(
          Integer.parseInt(realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_IDLE)));
    } else {
      dsConfig.setMinIdle(DEFAULT_MAX_IDLE);
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_WAIT) != null
        && !realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_WAIT).equals("")) {
      dsConfig.setMaxWait(
          Integer.parseInt(realmConfig.getUserStoreProperty(JDBCRealmConstants.MAX_WAIT)));
    } else {
      dsConfig.setMaxWait(DEFAULT_MAX_WAIT);
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.TEST_WHILE_IDLE) != null
        && !realmConfig.getUserStoreProperty(JDBCRealmConstants.TEST_WHILE_IDLE).equals("")) {
      dsConfig.setTestWhileIdle(
          Boolean.parseBoolean(
              realmConfig.getUserStoreProperty(JDBCRealmConstants.TEST_WHILE_IDLE)));
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.TIME_BETWEEN_EVICTION_RUNS_MILLIS)
            != null
        && !realmConfig
            .getUserStoreProperty(JDBCRealmConstants.TIME_BETWEEN_EVICTION_RUNS_MILLIS)
            .equals("")) {
      dsConfig.setTimeBetweenEvictionRunsMillis(
          Integer.parseInt(
              realmConfig.getUserStoreProperty(
                  JDBCRealmConstants.TIME_BETWEEN_EVICTION_RUNS_MILLIS)));
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.MIN_EVIC_TABLE_IDLE_TIME_MILLIS) != null
        && !realmConfig
            .getUserStoreProperty(JDBCRealmConstants.MIN_EVIC_TABLE_IDLE_TIME_MILLIS)
            .equals("")) {
      dsConfig.setMinEvictableIdleTimeMillis(
          Integer.parseInt(
              realmConfig.getUserStoreProperty(
                  JDBCRealmConstants.MIN_EVIC_TABLE_IDLE_TIME_MILLIS)));
    }

    if (realmConfig.getUserStoreProperty(JDBCRealmConstants.VALIDATION_QUERY) != null) {
      dsConfig.setValidationQuery(
          realmConfig.getUserStoreProperty(JDBCRealmConstants.VALIDATION_QUERY));
    }
    try {
      return new RDBMSDataSource(dsConfig).getDataSource();
    } catch (DataSourceException e) {
      throw new RuntimeException("Error in creating data source: " + e.getMessage(), e);
    }
  }
  public void doUserRoleStuff() throws Exception {
    UserStoreManager admin = realm.getUserStoreManager();

    InputStream inStream =
        this.getClass()
            .getClassLoader()
            .getResource(JDBCRealmTest.JDBC_TEST_USERMGT_XML)
            .openStream();
    RealmConfigXMLProcessor realmConfigProcessor = new RealmConfigXMLProcessor();
    RealmConfiguration realmConfig = realmConfigProcessor.buildRealmConfiguration(inStream);

    admin.addRole("role2", null, null);
    admin.addRole("role3", null, null);
    admin.addRole("role4", null, null);
    assertEquals(6, admin.getRoleNames().length); // admin,everyone,role1,role2,role3,role4

    // Test delete role method
    assertTrue(admin.isExistingRole("role3"));
    admin.deleteRole("role3");
    admin.deleteRole("role4");
    assertFalse(admin.isExistingRole("role3"));
    admin.addRole("role3", null, null);
    admin.addRole("role4", null, null);

    // add users
    admin.addUser("saman", "pass1", null, null, null, false);
    admin.addUser("amara", "pass2", null, null, null, false);
    admin.addUser("sunil", "pass3", null, null, null, false);

    // update the ROLE list of USERS
    admin.updateRoleListOfUser("saman", null, new String[] {"role2"});
    admin.updateRoleListOfUser("saman", new String[] {"role2"}, new String[] {"role4", "role3"});
    try {
      admin.updateRoleListOfUser(null, null, new String[] {"role2"});
      fail("Exceptions at missing user name");
    } catch (Exception ex) {
      // expected user
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", ex);
      }
    }

    // Renaming Role
    admin.updateRoleName("role4", "role5");

    String[] rolesOfSaman = admin.getRoleListOfUser("saman");
    assertEquals(3, rolesOfSaman.length);

    String[] rolesOfisuru = admin.getRoleListOfUser("isuru");
    assertEquals(0, rolesOfisuru.length);

    admin.updateUserListOfRole("role2", new String[] {"saman"}, null);
    admin.updateUserListOfRole("role3", null, new String[] {"amara", "sunil"});

    String[] userOfRole5 = admin.getUserListOfRole("role5");
    assertEquals(1, userOfRole5.length);

    String[] userOfRole4 = admin.getUserListOfRole("role4");
    assertEquals(0, userOfRole4.length);

    try {
      admin.updateUserListOfRole("rolexx", null, new String[] {"amara", "sunil"});
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      admin.updateUserListOfRole("role2", null, new String[] {"d"});
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    try {
      admin.updateRoleListOfUser("saman", new String[] {"x"}, new String[] {"y"});
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    try {
      admin.updateUserListOfRole(
          realmConfig.getAdminRoleName(), null, new String[] {realmConfig.getAdminUserName()});
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    try {
      admin.updateRoleListOfUser(
          realmConfig.getAdminUserName(), new String[] {realmConfig.getAdminRoleName()}, null);
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    try {
      admin.updateUserListOfRole(realmConfig.getEveryOneRoleName(), new String[] {"saman"}, null);
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    try {
      admin.updateRoleListOfUser("sunil", new String[] {realmConfig.getEveryOneRoleName()}, null);
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    try {
      admin.updateRoleName("role2", "role5");
      TestCase.assertTrue(false);
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
  }
  // TODO get a factory or a stream writer - add more props
  public static OMElement serialize(RealmConfiguration realmConfig) {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMElement rootElement =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_MANAGER));
    OMElement realmElement =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_REALM));
    String realmName = realmConfig.getRealmClassName();

    OMAttribute propAttr =
        factory.createOMAttribute(
            UserCoreConstants.RealmConfig.ATTR_NAME_PROP_NAME, null, realmName);
    realmElement.addAttribute(propAttr);

    rootElement.addChild(realmElement);

    OMElement mainConfig =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_CONFIGURATION));
    realmElement.addChild(mainConfig);

    OMElement addAdmin =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADD_ADMIN));
    OMElement adminUser =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADMIN_USER));
    OMElement adminUserNameElem =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_NAME));
    adminUserNameElem.setText(realmConfig.getAdminUserName());
    OMElement adminPasswordElem =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_PASSWORD));
    addAdmin.setText(UserCoreUtil.removeDomainFromName(realmConfig.getAddAdmin()));
    adminPasswordElem.setText(realmConfig.getAdminPassword());
    adminUser.addChild(adminUserNameElem);
    adminUser.addChild(adminPasswordElem);
    mainConfig.addChild(addAdmin);
    mainConfig.addChild(adminUser);

    OMElement adminRoleNameElem =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADMIN_ROLE));
    adminRoleNameElem.setText(UserCoreUtil.removeDomainFromName(realmConfig.getAdminRoleName()));
    mainConfig.addChild(adminRoleNameElem);

    OMElement systemUserNameElem =
        factory.createOMElement(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_SYSTEM_USER_NAME));
    mainConfig.addChild(systemUserNameElem);

    // adding the anonymous user
    OMElement anonymousUserEle =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ANONYMOUS_USER));
    OMElement anonymousUserNameElem =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_NAME));
    OMElement anonymousPasswordElem =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_PASSWORD));
    anonymousUserEle.addChild(anonymousUserNameElem);
    anonymousUserEle.addChild(anonymousPasswordElem);
    mainConfig.addChild(anonymousUserEle);

    // adding the everyone role
    OMElement everyoneRoleNameElem =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_EVERYONE_ROLE));
    everyoneRoleNameElem.setText(
        UserCoreUtil.removeDomainFromName(realmConfig.getEveryOneRoleName()));
    mainConfig.addChild(everyoneRoleNameElem);

    // add the main config properties
    addPropertyElements(
        factory, mainConfig, null, realmConfig.getDescription(), realmConfig.getRealmProperties());
    // add the user store manager properties

    OMElement userStoreManagerElement =
        factory.createOMElement(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER));
    realmElement.addChild(userStoreManagerElement);
    addPropertyElements(
        factory,
        userStoreManagerElement,
        realmConfig.getUserStoreClass(),
        realmConfig.getDescription(),
        realmConfig.getUserStoreProperties());

    RealmConfiguration secondaryRealmConfiguration = null;
    secondaryRealmConfiguration = realmConfig.getSecondaryRealmConfig();
    while (secondaryRealmConfiguration != null) {
      OMElement secondaryElement =
          factory.createOMElement(
              new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER));
      realmElement.addChild(secondaryElement);
      addPropertyElements(
          factory,
          secondaryElement,
          secondaryRealmConfiguration.getUserStoreClass(),
          secondaryRealmConfiguration.getDescription(),
          secondaryRealmConfiguration.getUserStoreProperties());
      secondaryRealmConfiguration = secondaryRealmConfiguration.getSecondaryRealmConfig();
    }

    // add the user authorization properties
    OMElement authorizerManagerElement =
        factory.createOMElement(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ATHZ_MANAGER));
    realmElement.addChild(authorizerManagerElement);
    addPropertyElements(
        factory,
        authorizerManagerElement,
        realmConfig.getAuthorizationManagerClass(),
        realmConfig.getDescription(),
        realmConfig.getAuthzProperties());

    return rootElement;
  }
  public RealmConfiguration buildRealmConfiguration(OMElement realmElem, boolean supperTenant)
      throws UserStoreException {
    RealmConfiguration realmConfig = null;
    String userStoreClass = null;
    String authorizationManagerClass = null;
    String addAdmin = null;
    String adminRoleName = null;
    String adminUserName = null;
    String adminPassword = null;
    String everyOneRoleName = null;
    String realmClass = null;
    String description = null;
    Map<String, String> userStoreProperties = null;
    Map<String, String> authzProperties = null;
    Map<String, String> realmProperties = null;
    boolean passwordsExternallyManaged = false;

    realmClass =
        (String)
            realmElem.getAttributeValue(new QName(UserCoreConstants.RealmConfig.ATTR_NAME_CLASS));

    OMElement mainConfig =
        realmElem.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_CONFIGURATION));
    realmProperties = getChildPropertyElements(mainConfig, secretResolver);
    String dbUrl = constructDatabaseURL(realmProperties.get(JDBCRealmConstants.URL));
    realmProperties.put(JDBCRealmConstants.URL, dbUrl);

    if (mainConfig.getFirstChildWithName(
                new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADD_ADMIN))
            != null
        && !mainConfig
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADD_ADMIN))
            .getText()
            .trim()
            .equals("")) {
      addAdmin =
          mainConfig
              .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADD_ADMIN))
              .getText()
              .trim();
    } else {
      if (supperTenant) {
        log.error(
            "AddAdmin configuration not found or invalid in user-mgt.xml. Cannot start server!");
        throw new UserStoreException(
            "AddAdmin configuration not found or invalid user-mgt.xml. Cannot start server!");
      } else {
        log.debug("AddAdmin configuration not found");
        addAdmin = "true";
      }
    }

    OMElement reservedRolesElm =
        mainConfig.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_RESERVED_ROLE_NAMES));

    String[] reservedRoles = new String[0];

    if (reservedRolesElm != null && !reservedRolesElm.getText().trim().equals("")) {
      String rolesStr = reservedRolesElm.getText().trim();

      if (rolesStr.contains(",")) {
        reservedRoles = rolesStr.split(",");
      } else {
        reservedRoles = rolesStr.split(";");
      }
    }

    OMElement restrictedDomainsElm =
        mainConfig.getFirstChildWithName(
            new QName(
                UserCoreConstants.RealmConfig.LOCAL_NAME_RESTRICTED_DOMAINS_FOR_SELF_SIGN_UP));

    String[] restrictedDomains = new String[0];

    if (restrictedDomainsElm != null && !restrictedDomainsElm.getText().trim().equals("")) {
      String domain = restrictedDomainsElm.getText().trim();

      if (domain.contains(",")) {
        restrictedDomains = domain.split(",");
      } else {
        restrictedDomains = domain.split(";");
      }
    }

    OMElement adminUser =
        mainConfig.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADMIN_USER));
    adminUserName =
        adminUser
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_NAME))
            .getText()
            .trim();
    adminPassword =
        adminUser
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_PASSWORD))
            .getText()
            .trim();
    if (secretResolver != null
        && secretResolver.isInitialized()
        && secretResolver.isTokenProtected("UserManager.AdminUser.Password")) {
      adminPassword = secretResolver.resolve("UserManager.AdminUser.Password");
    }
    adminRoleName =
        mainConfig
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADMIN_ROLE))
            .getText()
            .trim();
    everyOneRoleName =
        mainConfig
            .getFirstChildWithName(
                new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_EVERYONE_ROLE))
            .getText()
            .trim();

    OMElement authzConfig =
        realmElem.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ATHZ_MANAGER));
    authorizationManagerClass =
        authzConfig
            .getAttributeValue(new QName(UserCoreConstants.RealmConfig.ATTR_NAME_CLASS))
            .trim();
    authzProperties = getChildPropertyElements(authzConfig, null);

    Iterator<OMElement> iterator =
        realmElem.getChildrenWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER));

    RealmConfiguration primaryConfig = null;
    RealmConfiguration tmpConfig = null;

    for (; iterator.hasNext(); ) {
      OMElement usaConfig = iterator.next();
      userStoreClass =
          usaConfig.getAttributeValue(new QName(UserCoreConstants.RealmConfig.ATTR_NAME_CLASS));
      if (usaConfig.getFirstChildWithName(
              new QName(UserCoreConstants.RealmConfig.CLASS_DESCRIPTION))
          != null) {
        description =
            usaConfig
                .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.CLASS_DESCRIPTION))
                .getText()
                .trim();
      }
      userStoreProperties = getChildPropertyElements(usaConfig, secretResolver);

      String sIsPasswordExternallyManaged =
          userStoreProperties.get(UserCoreConstants.RealmConfig.LOCAL_PASSWORDS_EXTERNALLY_MANAGED);

      Map<String, String> multipleCredentialsProperties =
          getMultipleCredentialsProperties(usaConfig);

      if (null != sIsPasswordExternallyManaged && !sIsPasswordExternallyManaged.trim().equals("")) {
        passwordsExternallyManaged = Boolean.parseBoolean(sIsPasswordExternallyManaged);
      } else {
        if (log.isDebugEnabled()) {
          log.debug("External password management is disabled.");
        }
      }

      realmConfig = new RealmConfiguration();
      realmConfig.setRealmClassName(realmClass);
      realmConfig.setUserStoreClass(userStoreClass);
      realmConfig.setDescription(description);
      realmConfig.setAuthorizationManagerClass(authorizationManagerClass);
      if (primaryConfig == null) {
        realmConfig.setPrimary(true);
        realmConfig.setAddAdmin(addAdmin);
        realmConfig.setAdminPassword(adminPassword);

        // if domain name not provided, add default primary domain name
        String domain = userStoreProperties.get(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
        if (domain == null) {
          userStoreProperties.put(
              UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME,
              UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME);
        }

        for (int i = 0; i < reservedRoles.length; i++) {
          realmConfig.addReservedRoleName(reservedRoles[i].trim().toUpperCase());
        }

        for (int i = 0; i < restrictedDomains.length; i++) {
          realmConfig.addRestrictedDomainForSelfSignUp(restrictedDomains[i].trim().toUpperCase());
        }

        if (supperTenant
            && userStoreProperties.get(UserCoreConstants.TenantMgtConfig.LOCAL_NAME_TENANT_MANAGER)
                == null) {
          log.error(
              "Required property '"
                  + UserCoreConstants.TenantMgtConfig.LOCAL_NAME_TENANT_MANAGER
                  + "' not found for the primary UserStoreManager in user_mgt.xml. Cannot start server!");
          throw new UserStoreException(
              "Required property '"
                  + UserCoreConstants.TenantMgtConfig.LOCAL_NAME_TENANT_MANAGER
                  + "' not found for the primary UserStoreManager in user_mgt.xml. Cannot start server!");
        }
      }

      // If the domain name still empty
      String domain = userStoreProperties.get(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
      if (domain == null) {
        log.warn(
            "Required property "
                + UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME
                + " missing in secondary user store. Skip adding the user store.");
        continue;
      }
      // Making user stores added using user-mgt.xml non-editable(static) at runtime
      userStoreProperties.put(UserCoreConstants.RealmConfig.STATIC_USER_STORE, "true");

      realmConfig.setEveryOneRoleName(
          UserCoreConstants.INTERNAL_DOMAIN + CarbonConstants.DOMAIN_SEPARATOR + everyOneRoleName);
      realmConfig.setAdminRoleName(adminRoleName);
      realmConfig.setAdminUserName(adminUserName);
      realmConfig.setUserStoreProperties(userStoreProperties);
      realmConfig.setAuthzProperties(authzProperties);
      realmConfig.setRealmProperties(realmProperties);
      realmConfig.setPasswordsExternallyManaged(passwordsExternallyManaged);
      realmConfig.addMultipleCredentialProperties(userStoreClass, multipleCredentialsProperties);

      if (realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)
          == null) {
        realmConfig
            .getUserStoreProperties()
            .put(
                UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST,
                UserCoreConstants.RealmConfig.PROPERTY_VALUE_DEFAULT_MAX_COUNT);
      }

      if (realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY)
          == null) {
        realmConfig
            .getUserStoreProperties()
            .put(
                UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY,
                UserCoreConstants.RealmConfig.PROPERTY_VALUE_DEFAULT_READ_ONLY);
      }

      if (primaryConfig == null) {
        primaryConfig = realmConfig;
      } else {
        tmpConfig.setSecondaryRealmConfig(realmConfig);
      }

      tmpConfig = realmConfig;
    }
    if (primaryConfig != null && primaryConfig.isPrimary()) {
      // Check if Admin user name has been provided with domain
      String primaryDomainName =
          primaryConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
      String readOnly =
          primaryConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY);
      Boolean isReadOnly = false;
      if (readOnly != null) {
        isReadOnly = Boolean.parseBoolean(readOnly);
      }
      if (primaryDomainName != null && primaryDomainName.trim().length() > 0) {
        if (adminUserName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) {
          // Using the short-circuit. User name comes with the domain name.
          String adminUserDomain =
              adminUserName.substring(0, adminUserName.indexOf(CarbonConstants.DOMAIN_SEPARATOR));
          if (!primaryDomainName.equalsIgnoreCase(adminUserDomain)) {
            throw new UserStoreException(
                "Admin User domain does not match primary user store domain.");
          }
        } else {
          primaryConfig.setAdminUserName(
              UserCoreUtil.addDomainToName(adminUserName, primaryDomainName));
        }
        if (adminRoleName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) {
          // Using the short-circuit. User name comes with the domain name.
          String adminRoleDomain =
              adminRoleName.substring(0, adminRoleName.indexOf(CarbonConstants.DOMAIN_SEPARATOR));

          if ((!primaryDomainName.equalsIgnoreCase(adminRoleDomain))
              || (isReadOnly)
                  && (!primaryDomainName.equalsIgnoreCase(UserCoreConstants.INTERNAL_DOMAIN))) {
            throw new UserStoreException(
                "Admin Role domain does not match primary user store domain.");
          }
        }
      }

      // This will be overridden inside the UserStoreManager constructor.
      primaryConfig.setAdminRoleName(
          UserCoreUtil.addDomainToName(adminRoleName, primaryDomainName));
    }
    return primaryConfig;
  }
  public RealmConfiguration buildRealmConfiguration(OMElement realmElem) {
    RealmConfiguration realmConfig = null;
    String userStoreClass = null;
    String authorizationManagerClass = null;
    String adminRoleName = null;
    String adminUserName = null;
    String adminPassword = null;
    String everyOneRoleName = null;
    String realmClass = null;
    Map<String, String> userStoreProperties = null;
    Map<String, String> authzProperties = null;
    Map<String, String> realmProperties = null;
    boolean passwordsExternallyManaged = false;

    realmClass =
        (String)
            realmElem.getAttributeValue(new QName(UserCoreConstants.RealmConfig.ATTR_NAME_CLASS));

    OMElement mainConfig =
        realmElem.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_CONFIGURATION));
    realmProperties = getChildPropertyElements(mainConfig, secretResolver);
    String dbUrl = constructDatabaseURL(realmProperties.get(JDBCRealmConstants.URL));
    realmProperties.put(JDBCRealmConstants.URL, dbUrl);

    OMElement adminUser =
        mainConfig.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADMIN_USER));
    adminUserName =
        adminUser
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_NAME))
            .getText();
    adminPassword =
        adminUser
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_PASSWORD))
            .getText();
    if (secretResolver != null
        && secretResolver.isInitialized()
        && secretResolver.isTokenProtected("UserManager.AdminUser.Password")) {
      adminPassword = secretResolver.resolve("UserManager.AdminUser.Password");
    }
    adminRoleName =
        mainConfig
            .getFirstChildWithName(new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ADMIN_ROLE))
            .getText();
    everyOneRoleName =
        mainConfig
            .getFirstChildWithName(
                new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_EVERYONE_ROLE))
            .getText();

    OMElement authzConfig =
        realmElem.getFirstChildWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_ATHZ_MANAGER));
    authorizationManagerClass =
        authzConfig.getAttributeValue(new QName(UserCoreConstants.RealmConfig.ATTR_NAME_CLASS));
    authzProperties = getChildPropertyElements(authzConfig, null);

    Iterator<OMElement> iterator =
        realmElem.getChildrenWithName(
            new QName(UserCoreConstants.RealmConfig.LOCAL_NAME_USER_STORE_MANAGER));

    RealmConfiguration primaryConfig = null;
    RealmConfiguration tmpConfig = null;

    for (; iterator.hasNext(); ) {
      OMElement usaConfig = iterator.next();
      userStoreClass =
          usaConfig.getAttributeValue(new QName(UserCoreConstants.RealmConfig.ATTR_NAME_CLASS));
      userStoreProperties = getChildPropertyElements(usaConfig, secretResolver);

      String sIsPasswordExternallyManaged =
          userStoreProperties.get(UserCoreConstants.RealmConfig.LOCAL_PASSWORDS_EXTERNALLY_MANAGED);

      Map<String, String> multipleCredentialsProperties =
          getMultipleCredentialsProperties(usaConfig);

      if (null != sIsPasswordExternallyManaged && !sIsPasswordExternallyManaged.trim().equals("")) {
        passwordsExternallyManaged = Boolean.parseBoolean(sIsPasswordExternallyManaged);
      } else {
        if (log.isDebugEnabled()) {
          log.debug("External password management is disabled.");
        }
      }

      realmConfig = new RealmConfiguration();
      realmConfig.setRealmClassName(realmClass);
      realmConfig.setUserStoreClass(userStoreClass);
      realmConfig.setAuthorizationManagerClass(authorizationManagerClass);
      realmConfig.setAdminRoleName(adminRoleName);
      realmConfig.setAdminUserName(adminUserName);
      realmConfig.setAdminPassword(adminPassword);
      realmConfig.setEveryOneRoleName(everyOneRoleName);
      realmConfig.setUserStoreProperties(userStoreProperties);
      realmConfig.setAuthzProperties(authzProperties);
      realmConfig.setRealmProperties(realmProperties);
      realmConfig.setPasswordsExternallyManaged(passwordsExternallyManaged);
      realmConfig.addMultipleCredentialProperties(userStoreClass, multipleCredentialsProperties);

      if (realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST)
          == null) {
        realmConfig
            .getUserStoreProperties()
            .put(
                UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST,
                UserCoreConstants.RealmConfig.PROPERTY_VALUE_DEFAULT_MAX_COUNT);
      }

      if (realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY)
          == null) {
        realmConfig
            .getUserStoreProperties()
            .put(
                UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY,
                UserCoreConstants.RealmConfig.PROPERTY_VALUE_DEFAULT_READ_ONLY);
      }

      if (primaryConfig == null) {
        primaryConfig = realmConfig;
      } else {
        tmpConfig.setSecondaryRealmConfig(realmConfig);
      }

      tmpConfig = realmConfig;
    }

    return primaryConfig;
  }