/** {@inheritDoc} */
  @Override
  public void addTopic(String topicName) throws EventBrokerException {
    if (!validateTopicName(topicName)) {
      throw new EventBrokerException(
          "Topic name "
              + topicName
              + " is not a valid topic name. "
              + "Only alphanumeric characters, hyphens (-), stars(*),"
              + " hash(#) ,dot(.),question mark(?)"
              + " and underscores (_) are allowed.");
    }

    String loggedInUser = CarbonContext.getThreadLocalCarbonContext().getUsername();

    try {
      UserRegistry userRegistry =
          this.registryService.getGovernanceSystemRegistry(
              EventBrokerHolder.getInstance().getTenantId());
      String resourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);

      // we add the topic only if it does not exits. if the topic exists then
      // we don't do any thing.
      if (!userRegistry.resourceExists(resourcePath)) {
        Collection collection = userRegistry.newCollection();
        userRegistry.put(resourcePath, collection);

        // Grant this user (owner) rights to update permission on newly created topic
        UserRealm userRealm =
            EventBrokerHolder.getInstance()
                .getRealmService()
                .getTenantUserRealm(CarbonContext.getThreadLocalCarbonContext().getTenantId());

        userRealm
            .getAuthorizationManager()
            .authorizeUser(
                loggedInUser, resourcePath, EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION);
        userRealm
            .getAuthorizationManager()
            .authorizeUser(loggedInUser, resourcePath, EventBrokerConstants.EB_PERMISSION_PUBLISH);
        userRealm
            .getAuthorizationManager()
            .authorizeUser(
                loggedInUser, resourcePath, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE);
      }
    } catch (RegistryException e) {
      throw new EventBrokerException("Cannot access the config registry", e);
    } catch (UserStoreException e) {
      throw new EventBrokerException(
          "Error while granting user "
              + loggedInUser
              + ", permission "
              + EventBrokerConstants.EB_PERMISSION_CHANGE_PERMISSION
              + ", on topic "
              + topicName,
          e);
    }
  }
  /** {@inheritDoc} */
  @Override
  public String[] getBackendRoles() throws EventBrokerException {
    UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
    String[] cleanedRoles = new String[0];
    try {
      String adminRole =
          EventBrokerHolder.getInstance()
              .getRealmService()
              .getBootstrapRealmConfiguration()
              .getAdminRoleName();
      String[] allRoles = userRealm.getUserStoreManager().getRoleNames();
      // check if there is only admin role exists.
      if (allRoles != null && allRoles.length > 1) {
        // check if more roles available than admin role and anonymous role
        List<String> allRolesArrayList = new ArrayList<>();
        Collections.addAll(allRolesArrayList, allRoles);

        Iterator<String> it = allRolesArrayList.iterator();
        while (it.hasNext()) {
          String nextRole = it.next();
          if (nextRole.equals(adminRole)
              || nextRole.equals(CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME)) {
            it.remove();
          }
        }

        cleanedRoles = allRolesArrayList.toArray(new String[allRolesArrayList.size()]);
      }

    } catch (UserStoreException e) {
      throw new EventBrokerException("Unable to get Roles from user store", e);
    }

    return cleanedRoles;
  }
 /** {@inheritDoc} */
 @Override
 public boolean isTopicExists(String topicName) throws EventBrokerException {
   try {
     UserRegistry userRegistry =
         this.registryService.getGovernanceSystemRegistry(
             EventBrokerHolder.getInstance().getTenantId());
     String resourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);
     return userRegistry.resourceExists(resourcePath);
   } catch (RegistryException e) {
     throw new EventBrokerException("Cannot access the config registry");
   }
 }
  /**
   * Adds a subscriptions to a list using the resource path provided
   *
   * @param resourcePath the topic nam
   * @param subscriptions a list of subscriptions for the topic
   * @param pathsQueue the topic folder
   * @param withChildren to add subscriptions to children. i.e subtopics
   * @throws EventBrokerException
   */
  private void addSubscriptions(
      String resourcePath,
      List<Subscription> subscriptions,
      Queue<String> pathsQueue,
      boolean withChildren)
      throws EventBrokerException {

    try {
      UserRegistry userRegistry =
          this.registryService.getGovernanceSystemRegistry(
              EventBrokerHolder.getInstance().getTenantId());
      String subscriptionsPath = getSubscriptionsPath(resourcePath);

      // first if there are subscriptions for this topic add them. else go to the other folders.
      if (userRegistry.resourceExists(subscriptionsPath)) {
        Collection collection = (Collection) userRegistry.get(subscriptionsPath);
        for (String subscriptionPath : collection.getChildren()) {
          Resource subscriptionResource = userRegistry.get(subscriptionPath);
          Subscription subscription = JavaUtil.getSubscription(subscriptionResource);
          subscription.setTopicName(removeResourcePath(resourcePath));

          if (subscriptionPath.endsWith("/")) {
            subscriptionPath = subscriptionsPath.substring(0, subscriptionPath.lastIndexOf("/"));
          }
          subscription.setId(subscriptionPath.substring(subscriptionPath.lastIndexOf("/") + 1));
          subscriptions.add(subscription);
        }
      }

      // add child subscriptions only for resource collections
      if (withChildren) {
        Resource resource = userRegistry.get(resourcePath);
        if (resource instanceof Collection) {
          Collection childResources = (Collection) resource;
          for (String childResourcePath : childResources.getChildren()) {
            if ((!EventBrokerConstants.EB_CONF_WS_SUBSCRIPTION_COLLECTION_NAME.contains(
                    childResourcePath))
                && (!EventBrokerConstants.EB_CONF_JMS_SUBSCRIPTION_COLLECTION_NAME.contains(
                    childResourcePath))) {
              // i.e. this folder is a topic folder
              pathsQueue.add(childResourcePath);
            }
          }
        }
      }

    } catch (RegistryException e) {
      throw new EventBrokerException("Cannot access the registry", e);
    }
  }
 /** {@inheritDoc} */
 @Override
 public TopicNode getTopicTree() throws EventBrokerException {
   try {
     UserRegistry userRegistry =
         this.registryService.getGovernanceSystemRegistry(
             EventBrokerHolder.getInstance().getTenantId());
     if (!userRegistry.resourceExists(topicStoragePath)) {
       userRegistry.put(topicStoragePath, userRegistry.newCollection());
     }
     Resource root = userRegistry.get(this.topicStoragePath);
     TopicNode rootTopic = new TopicNode("/", "/");
     buildTopicTree(rootTopic, (Collection) root, userRegistry);
     return rootTopic;
   } catch (RegistryException e) {
     throw new EventBrokerException(e.getMessage(), e);
   }
 }
  /** {@inheritDoc} */
  @Override
  public boolean removeTopic(String topicName) throws EventBrokerException {

    try {
      UserRegistry userRegistry =
          this.registryService.getGovernanceSystemRegistry(
              EventBrokerHolder.getInstance().getTenantId());
      String resourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);

      removeRoleCreateForLoggedInUser(topicName);

      if (userRegistry.resourceExists(resourcePath)) {
        userRegistry.delete(resourcePath);
        return true;
      } else {
        return false;
      }
    } catch (RegistryException e) {
      throw new EventBrokerException("Cannot access the config registry", e);
    }
  }
  /** {@inheritDoc} */
  @Override
  public Subscription[] getJMSSubscriptions(String topicName) throws EventBrokerException {
    try {
      Subscription[] subscriptionsArray = new Subscription[0];

      UserRegistry userRegistry =
          this.registryService.getGovernanceSystemRegistry(
              EventBrokerHolder.getInstance().getTenantId());
      String resourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);
      if (!resourcePath.endsWith("/")) {
        resourcePath = resourcePath + "/";
      }
      resourcePath = resourcePath + EventBrokerConstants.EB_CONF_JMS_SUBSCRIPTION_COLLECTION_NAME;

      // Get subscriptions
      if (userRegistry.resourceExists(resourcePath)) {
        Collection subscriptionCollection = (Collection) userRegistry.get(resourcePath);
        subscriptionsArray = new Subscription[subscriptionCollection.getChildCount()];

        int index = 0;
        for (String subs : subscriptionCollection.getChildren()) {
          Collection subscription = (Collection) userRegistry.get(subs);

          Subscription subscriptionDetails = new Subscription();
          subscriptionDetails.setId(subscription.getProperty("Name"));
          subscriptionDetails.setOwner(subscription.getProperty("Owner"));
          subscriptionDetails.setCreatedTime(
              ConverterUtil.convertToDate(subscription.getProperty("createdTime")));

          subscriptionsArray[index++] = subscriptionDetails;
        }
      }

      return subscriptionsArray;
    } catch (RegistryException e) {
      throw new EventBrokerException("Cannot read the registry resources ", e);
    }
  }
 /** {@inheritDoc} */
 @Override
 public TopicRolePermission[] getTopicRolePermission(String topicName)
     throws EventBrokerException {
   String topicResourcePath = JavaUtil.getResourcePath(topicName, this.topicStoragePath);
   List<TopicRolePermission> topicRolePermissions = new ArrayList<TopicRolePermission>();
   UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
   String adminRole =
       EventBrokerHolder.getInstance()
           .getRealmService()
           .getBootstrapRealmConfiguration()
           .getAdminRoleName();
   TopicRolePermission topicRolePermission;
   try {
     for (String role : userRealm.getUserStoreManager().getRoleNames()) {
       // remove admin role and anonymous role related permissions
       if (!(role.equals(adminRole)
           || CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME.equals(role))) {
         topicRolePermission = new TopicRolePermission();
         topicRolePermission.setRoleName(role);
         topicRolePermission.setAllowedToSubscribe(
             userRealm
                 .getAuthorizationManager()
                 .isRoleAuthorized(
                     role, topicResourcePath, EventBrokerConstants.EB_PERMISSION_SUBSCRIBE));
         topicRolePermission.setAllowedToPublish(
             userRealm
                 .getAuthorizationManager()
                 .isRoleAuthorized(
                     role, topicResourcePath, EventBrokerConstants.EB_PERMISSION_PUBLISH));
         topicRolePermissions.add(topicRolePermission);
       }
     }
     return topicRolePermissions.toArray(new TopicRolePermission[topicRolePermissions.size()]);
   } catch (UserStoreException e) {
     throw new EventBrokerException("Cannot access the UserStore manager ", e);
   }
 }
 /**
  * Initializes Registry Topic Manager
  *
  * @param topicStoragePath the topic registry path
  */
 public RegistryTopicManager(String topicStoragePath) {
   this.topicStoragePath = topicStoragePath;
   this.registryService = EventBrokerHolder.getInstance().getRegistryService();
 }