/**
   * Deploys a .gar archive to the Registry path in REGISTRY_GADGET_STORAGE_PATH
   *
   * @param deploymentFileData - info about the deployed file
   * @throws DeploymentException - error while deploying .gar archive
   */
  public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
    try {

      //            int tenantId;
      //            try {
      //                tenantId =
      // MultitenantUtils.getTenantId(DashboardContext.getConfigContext());
      //            } catch (Exception e) {
      //                throw new DeploymentException(e);
      //            }

      UserRegistry registry = getRegistry(tenantID);

      // Extracting archive
      String extractedArchiveDir = extractGarArchive(deploymentFileData.getAbsolutePath());

      // Set permission for anonymous read. We do it here because it should happen always in order
      // to support mounting a remote registry.

      if (registry != null) {
        AuthorizationManager accessControlAdmin = registry.getUserRealm().getAuthorizationManager();

        if (!accessControlAdmin.isRoleAuthorized(
            CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
            RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
            ActionConstants.GET)) {
          accessControlAdmin.authorizeRole(
              CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
              RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
              ActionConstants.GET);
        }

        File gadgetsDir = new File(extractedArchiveDir);
        if (gadgetsDir.exists()) {
          beginFileTansfer(gadgetsDir, tenantID);

          log.info(
              "Successfully populated gadgets from archive ."
                  + deploymentFileData.getAbsolutePath()
                  + " to the registry.");
        } else {
          log.info("Couldn't find contents at '" + extractedArchiveDir + "'. Giving up.");
        }
      }

    } catch (RegistryException e) {
      throw new DeploymentException("An error occured while deploying gadget archive", e);
    } catch (CarbonException e) {
      throw new DeploymentException("An error occured while deploying gadget archive", e);
    } catch (UserStoreException e) {
      throw new DeploymentException("An error occured while deploying gadget archive", e);
    }
  }
  public void doAuthorizationStuff() throws Exception {
    AuthorizationManager authMan = realm.getAuthorizationManager();
    UserStoreManager usWriter = realm.getUserStoreManager();

    usWriter.addRole("rolex", new String[] {"saman", "amara"}, null);
    usWriter.addRole("roley", null, null);
    authMan.authorizeRole("rolex", "wall", "write");
    authMan.authorizeRole("roley", "table", "write");
    authMan.authorizeUser("sunil", "wall", "read");

    assertTrue(authMan.isUserAuthorized("saman", "wall", "write"));
    assertTrue(authMan.isUserAuthorized("sunil", "wall", "read"));
    assertTrue(authMan.isRoleAuthorized("roley", "table", "write"));
    assertFalse(authMan.isUserAuthorized("saman", "wall", "read"));
    assertFalse(authMan.isUserAuthorized("sunil", "wall", "write"));

    authMan.clearUserAuthorization("sunil", "wall", "read");
    authMan.clearRoleAuthorization("roley", "table", "write");
    authMan.clearResourceAuthorizations("wall");

    assertFalse(authMan.isUserAuthorized("saman", "wall", "write"));
    assertFalse(authMan.isUserAuthorized("sunil", "wall", "read"));
    assertFalse(authMan.isRoleAuthorized("roley", "table", "write"));
  }
  private static void transferDirectoryContentToRegistry(
      File rootDirectory, Registry registry, String rootPath, int tenantId) throws Exception {

    try {

      File[] filesAndDirs = rootDirectory.listFiles();
      List<File> filesDirs = Arrays.asList(filesAndDirs);

      for (File file : filesDirs) {

        if (!file.isFile()) {
          // This is a Directory add a new collection
          // This path is used to store the file resource under registry
          String directoryRegistryPath =
              REGISTRY_GADGET_STORAGE_PATH
                  + file.getAbsolutePath().substring(rootPath.length()).replaceAll("[/\\\\]+", "/");

          // If the collection exists no need to create it. If not, create.
          if (!registry.resourceExists(directoryRegistryPath)) {
            Collection newCollection = registry.newCollection();
            registry.put(directoryRegistryPath, newCollection);
          }

          // Set permission for anonymous read. We do it here because it should happen always in
          // order
          // to support mounting a remote registry.
          UserRegistry userRegistry = getRegistry(tenantId);
          AuthorizationManager accessControlAdmin =
              userRegistry.getUserRealm().getAuthorizationManager();

          if (!accessControlAdmin.isRoleAuthorized(
              CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
              RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
              ActionConstants.GET)) {
            accessControlAdmin.authorizeRole(
                CarbonConstants.REGISTRY_ANONNYMOUS_ROLE_NAME,
                RegistryConstants.CONFIG_REGISTRY_BASE_PATH + REGISTRY_GADGET_STORAGE_PATH,
                ActionConstants.GET);
          }

          // recurse
          transferDirectoryContentToRegistry(file, registry, rootPath, tenantId);
        } else {
          // Adding gadget to the gadget browser: gadget conf.xml need to be present
          if (file.getName().equals(GADGET_CONF_FILE)) {
            FileInputStream fis = new FileInputStream(file);
            XMLInputFactory xif = XMLInputFactory.newInstance();
            XMLStreamReader reader = xif.createXMLStreamReader(fis);

            StAXOMBuilder builder = new StAXOMBuilder(reader);
            OMElement omEle = builder.getDocumentElement();

            String gadgetName = omEle.getFirstChildWithName(new QName("name")).getText();
            String gadgetPath = omEle.getFirstChildWithName(new QName("path")).getText();
            String gadgetDesc = omEle.getFirstChildWithName(new QName("description")).getText();

            Resource res = registry.newResource();
            res.setProperty(DashboardConstants.GADGET_NAME, gadgetName);
            res.setProperty(DashboardConstants.GADGET_DESC, gadgetDesc);
            res.setProperty(DashboardConstants.GADGET_URL, gadgetPath);

            registry.put(
                DashboardConstants.SYSTEM_GADGETREPO_REGISTRY_ROOT
                    + DashboardConstants.GADGETS_COL
                    + "/"
                    + gadgetName,
                res);

          } else {
            // Add this to registry
            addToRegistry(rootPath, file, tenantId);
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      throw new Exception(e);
    }
  }
  public void doAuthorizationStuff() throws Exception {
    AuthorizationManager authMan = realm.getAuthorizationManager();
    UserStoreManager usWriter = realm.getUserStoreManager();

    usWriter.addRole("rolex", new String[] {"saman", "amara"}, null);
    usWriter.addRole("roley", null, null);
    authMan.authorizeRole("rolex", "wall", "write");
    authMan.authorizeRole("roley", "table", "write");

    try {
      authMan.authorizeRole(null, "wall", "write");
      fail("Exception at authorizing a role with Null role");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.authorizeRole("rollee", null, "write");
      fail("Exception at authorizing a role with Null resourceID");
    } catch (Exception e) {
      // exptected error in negative testing
    }
    try {
      authMan.authorizeRole("rollee", "wall", null);
      fail("Exception at authorizing a role with Null action");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.authorizeRole("rolleex", "wall", "run");
      fail("Exception at authorizing a role with Invalid action");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    // ***authorize user
    authMan.authorizeUser("sunil", "wall", "read");
    try {
      authMan.authorizeUser(null, "wall", "read");
      fail("Exception at authorizing a user with Null name");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.authorizeUser("isuru", null, "read");
      fail("Exception at authorizing a user with Null resourceID");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.authorizeUser("isuru", "wall", null);
      fail("Exception at authorizing a user with Null action");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.authorizeUser("isuru", "wall", "run");
      fail("Exception at authorizing a user with Invalid action");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    assertTrue(authMan.isUserAuthorized("saman", "wall", "write"));
    assertTrue(authMan.isUserAuthorized("sunil", "wall", "read"));
    assertTrue(authMan.isRoleAuthorized("primary/roley", "table", "write"));
    assertFalse(authMan.isRoleAuthorized("roley", "chair", "write"));
    assertFalse(authMan.isUserAuthorized("saman", "wall", "read"));
    assertFalse(authMan.isUserAuthorized("sunil", "wall", "write"));
    assertFalse(authMan.isUserAuthorized("isuru", "wall", "write"));
    try {
      boolean b = authMan.isUserAuthorized("isuru", "wall", "run");
      fail("Exception at check authorization of a user with Invalid action");
    } catch (Exception e) {
      // exptected error in negative testing
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    String[] AllowedRolesForResource = authMan.getAllowedRolesForResource("wall", "write");
    assertEquals(1, AllowedRolesForResource.length);
    // assertEquals(2,authMan.getAllowedUsersForResource("wall", "write").length);
    // String[] AllowedUsersForResource = authMan.getAllowedUsersForResource("wall", "read");
    // assertEquals(1, AllowedUsersForResource.length);

    authMan.clearUserAuthorization("sunil", "wall", "read");
    try {
      authMan.clearUserAuthorization("isuru", "wall", "run");
      fail("Exception at clear user authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.clearUserAuthorization(null, "wall", "run");
      fail("Exception at clear user authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.clearUserAuthorization("isuru", null, "run");
      fail("Exception at clear user authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.clearUserAuthorization("isuru", "wall", null);
      fail("Exception at clear user authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    authMan.clearRoleAuthorization("roley", "table", "write");
    try {
      authMan.clearRoleAuthorization(null, "table", "write");
      fail("Exception at clear role authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.clearRoleAuthorization("roleee", null, "write");
      fail("Exception at clear role authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }
    try {
      authMan.clearRoleAuthorization("roleee", "table", null);
      fail("Exception at clear role authorization");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    authMan.clearResourceAuthorizations("wall");
    try {
      authMan.clearResourceAuthorizations(null);
      fail("Exception at clear Resource Authorizations");
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug("Expected error, hence ignored", e);
      }
    }

    assertFalse(authMan.isUserAuthorized("saman", "wall", "write"));
    assertFalse(authMan.isUserAuthorized("sunil", "wall", "read"));
    assertFalse(authMan.isRoleAuthorized("roley", "table", "write"));
  }