@Test
  public void testWriteBinaryFile() throws InterruptedException {
    final String str = "some binary text";
    final String fileName = "file.bn";

    // set object in PentahoSystem
    mp.defineInstance(IUnifiedRepository.class, repo);

    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1,
        "admin",
        "password",
        "",
        new String[] {adminAuthorityName, authenticatedAuthorityName});
    try {
      login(sysAdminUserName, systemTenant, new String[] {adminAuthorityName});
      login("admin", mainTenant_1, new String[] {adminAuthorityName, authenticatedAuthorityName});

      WebResource webResource = resource();
      final byte[] blob = str.getBytes();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFileBinary(publicFolderPath.replaceAll("/", ":") + ":" + fileName, blob);

      // the file might not actually be ready.. wait a second
      Thread.sleep(20000);

      ClientResponse response =
          webResource
              .path("repo/files/:public:file.bn")
              .accept(APPLICATION_OCTET_STREAM)
              .get(ClientResponse.class);
      assertResponse(response, Status.OK, APPLICATION_OCTET_STREAM);

      byte[] data = response.getEntity(byte[].class);
      assertEquals("contents of file incorrect/missing", str, new String(data));
    } catch (Exception ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Ignore
  public void testGetFileText() throws Exception {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "file.txt", "abcdefg");

    WebResource webResource = resource();

    ClientResponse r1 =
        webResource
            .path("repos/:public:file.txt/content")
            .accept(TEXT_PLAIN)
            .get(ClientResponse.class);
    assertResponse(r1, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r1.getEntity(String.class));

    // check again but with no Accept header
    ClientResponse r2 =
        webResource.path("repos/:public:file.txt/content").get(ClientResponse.class);
    assertResponse(r2, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r2.getEntity(String.class));

    // check again but with */*
    ClientResponse r3 =
        webResource
            .path("repos/:public:file.txt/content")
            .accept(TEXT_PLAIN)
            .accept(MediaType.WILDCARD)
            .get(ClientResponse.class);
    assertResponse(r3, Status.OK, MediaType.TEXT_PLAIN);
    assertEquals("abcdefg", r3.getEntity(String.class));

    cleanupUserAndRoles(mainTenant_1);
    cleanupUserAndRoles(systemTenant);
  }
  @Test
  public void testDeleteFiles() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      String testFile1Id = "abc.txt";
      String testFile2Id = "def.txt";

      // set object in PentahoSystem
      mp.defineInstance(IUnifiedRepository.class, repo);

      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + testFile1Id, "abcdefg");
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + testFile2Id, "abcdefg");
      createTestFolder(":home:admin");

      RepositoryFile file1 = repo.getFile(publicFolderPath + "/" + testFile1Id);
      RepositoryFile file2 = repo.getFile(publicFolderPath + "/" + testFile2Id);
      WebResource webResource = resource();
      webResource.path("repo/files/delete").entity(file1.getId() + "," + file2.getId()).put();

      RepositoryFileDto[] deletedFiles =
          webResource
              .path("repo/files/deleted")
              .accept(APPLICATION_XML)
              .get(RepositoryFileDto[].class);
      assertEquals(2, deletedFiles.length);

      webResource.path("repo/files/deletepermanent").entity(file2.getId()).put();
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Test
  public void testWriteTextFile() throws Exception {
    final String text = "sometext";

    mp.defineInstance(IUnifiedRepository.class, repo);
    final String fileName = "file.txt";

    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login(
          sysAdminUserName,
          systemTenant,
          new String[] {adminAuthorityName, authenticatedAuthorityName});

      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      WebResource webResource = resource();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + fileName, text);

      ClientResponse response =
          webResource
              .path("repo/files/:public:" + fileName)
              .accept(TEXT_PLAIN)
              .get(ClientResponse.class);
      assertResponse(response, Status.OK, TEXT_PLAIN);
      assertEquals("contents of file incorrect/missing", text, response.getEntity(String.class));

    } catch (Throwable th) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Test
  public void testCopyFiles() throws Exception {
    mp.defineInstance(IUnifiedRepository.class, repo);
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {adminAuthorityName, authenticatedAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

    try {
      final String destFolderPath = "public:folder3:folder4";
      final String fileName = "file.txt";

      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + fileName, "abcdefg");
      WebResource webResource = resource();
      RepositoryFile file =
          repo.getFile(ClientRepositoryPaths.getPublicFolderPath() + "/" + fileName);
      ClientResponse r =
          webResource
              .path("repo/files/" + destFolderPath + "/children")
              .accept(TEXT_PLAIN)
              .put(ClientResponse.class, file.getId());
      assertResponse(r, Status.OK);
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Test
  public void testDoNewTenant() throws Exception {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1,
        "admin",
        "password",
        "",
        new String[] {adminAuthorityName, tenantAuthenticatedAuthorityName});
    login(
        "admin", mainTenant_1, new String[] {adminAuthorityName, tenantAuthenticatedAuthorityName});
    JcrRepositoryDumpToFile dumpToFile =
        new JcrRepositoryDumpToFile(
            testJcrTemplate,
            jcrTransactionTemplate,
            repositoryAdminUsername,
            "c:/build/testrepo_3",
            Mode.CUSTOM);
    dumpToFile.execute();
    metadataRepositoryLifecycleManager.newTenant(mainTenant_1);
    String metadataPath = ClientRepositoryPaths.getEtcFolderPath() + "/metadata";
    RepositoryFile metadataRepositoryPath = repo.getFile(metadataPath);
    assertTrue(metadataRepositoryPath.getPath() != null);

    // Nothing should change if we run it again
    metadataRepositoryLifecycleManager.newTenant(mainTenant_1);
    metadataPath = ClientRepositoryPaths.getEtcFolderPath() + "/metadata";
    metadataRepositoryPath = repo.getFile(metadataPath);
    assertTrue(metadataRepositoryPath.getPath() != null);
    cleanupUserAndRoles(mainTenant_1);
    cleanupUserAndRoles(systemTenant);
  }
 public Node getRuntimeRolesFolderNode(final Session session, ITenant tenant)
     throws RepositoryException {
   Node tenantRootFolderNode = null;
   try {
     tenantRootFolderNode =
         (Node) session.getItem(ServerRepositoryPaths.getTenantRootFolderPath(tenant));
   } catch (PathNotFoundException e) {
     throw new RepositoryException(
         "Error retrieving RuntimeRoles for folder, folder not found", e);
     // Assert.state(false, Messages.getInstance().getString(
     // "JcrRoleAuthorizationPolicyRoleBindingDao.ERROR_0002_REPO_NOT_INITIALIZED")); //$NON-NLS-1$
   }
   Node authzFolderNode = tenantRootFolderNode.getNode(FOLDER_NAME_AUTHZ);
   Node roleBasedFolderNode = authzFolderNode.getNode(FOLDER_NAME_ROLEBASED);
   return roleBasedFolderNode.getNode(FOLDER_NAME_RUNTIMEROLES);
 }
  @Ignore
  public void a2_HappyPath() {
    loginAsRepositoryAdmin();

    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.xjunit", "abcdefg");
    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "js/test.js", "js content");
    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.css", "css content");

    WebResource webResource = resource();

    // load the css
    ClientResponse response =
        webResource.path("repos/:public:test.xjunit/test.css").get(ClientResponse.class);
    assertResponse(response, ClientResponse.Status.OK, "text/css");
    assertEquals(
        "contents of file incorrect/missing", "css content", response.getEntity(String.class));

    // load the js
    response = webResource.path("repos/:public:test.xjunit/js/test.js").get(ClientResponse.class);
    assertResponse(response, ClientResponse.Status.OK, "text/javascript");
    assertEquals(
        "contents of file incorrect/missing", "js content", response.getEntity(String.class));
  }
  // We should be testing the underlying class functionality in unit tests
  @Test
  public void testGetDirChildren() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      // set object in PentahoSystem
      mp.defineInstance(IUnifiedRepository.class, repo);
      final String fileName = "file.txt";
      createTestFile("/public".replaceAll("/", ":") + ":" + fileName, "abcdefg");
      WebResource webResource = resource();
      ClientResponse response =
          webResource
              .path("repo/files/public/children")
              .accept(APPLICATION_XML)
              .get(ClientResponse.class);

      assertResponse(response, Status.OK, APPLICATION_XML);

      String xml = response.getEntity(String.class);
      assertTrue(xml.startsWith("<?"));
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Ignore
  public void a3_HappyPath_POST() {
    loginAsRepositoryAdmin();

    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.xjunit", "abcdefg");

    WebResource webResource = resource();

    // get the output of the .junit file (should invoke the content generator)
    MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
    formData.add("testParam", "testParamValue");

    ClientResponse response =
        webResource
            .path("repos/:public:test.xjunit/viewer")
            .type(APPLICATION_FORM_URLENCODED)
            .post(ClientResponse.class, formData);
    assertResponse(response, Status.OK);
    assertEquals(
        "Content generator failed to provide correct output",
        "hello viewer content generator",
        response.getEntity(String.class));
  }
 /**
  * Creates and/or returns an internal folder called {@code .trash} located just below the user's
  * home folder.
  */
 private Node getOrCreateTrashInternalFolderNode(
     final Session session, final PentahoJcrConstants pentahoJcrConstants)
     throws RepositoryException {
   IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
   String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY);
   Node userHomeFolderNode =
       (Node)
           session.getItem(
               ServerRepositoryPaths.getUserHomeFolderPath(
                   new Tenant(tenantId, true),
                   JcrStringHelper.fileNameEncode(PentahoSessionHolder.getSession().getName())));
   if (userHomeFolderNode.hasNode(FOLDER_NAME_TRASH)) {
     return userHomeFolderNode.getNode(FOLDER_NAME_TRASH);
   } else {
     return userHomeFolderNode.addNode(
         FOLDER_NAME_TRASH, pentahoJcrConstants.getPHO_NT_INTERNALFOLDER());
   }
 }
  @Test
  public void testFileCreator() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});

      // set object in PentahoSystem
      mp.defineInstance(IUnifiedRepository.class, repo);

      WebResource webResource = resource();
      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "file1.txt", "abcdefg");
      RepositoryFile file1 = repo.getFile(publicFolderPath + "/" + "file1.txt");
      RepositoryFileDto file2 = new RepositoryFileDto();
      file2.setId(file1.getId().toString());
      webResource.path("repo/files/public:file1.txt/creator").entity(file2).put();
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
      logout();
    }
  }
  @After
  public void afterTest() throws Exception {
    // null out fields to get back memory
    loginAsRepositoryAdmin();
    SimpleJcrTestUtils.deleteItem(
        testJcrTemplate, ServerRepositoryPaths.getPentahoRootFolderPath());
    logout();

    repositoryAdminUsername = null;
    adminAuthorityName = null;
    tenantAuthenticatedAuthorityName = null;
    authorizationPolicy = null;
    testJcrTemplate = null;
    if (startupCalled) {
      manager.shutdown();
    }

    // null out fields to get back memory
    repo = null;
  }
  @Ignore
  public void a3_dotUrl() {
    loginAsRepositoryAdmin();

    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    final String text = "URL=http://google.com";
    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.url", text);

    WebResource webResource = resource();

    String response = webResource.path("repos/:public:test.url/content").get(String.class);
    assertEquals("contents of file incorrect/missing", text, response);

    ClientResponse getResponse =
        webResource.path("repos/:public:test.url/generatedContent").get(ClientResponse.class);
    assertEquals(ClientResponse.Status.OK, getResponse.getClientResponseStatus());
  }
  @Ignore
  public void a3_HappyPath_GET() {
    loginAsRepositoryAdmin();

    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    mp.defineInstance(IUnifiedRepository.class, repo);

    login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
    String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();

    createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "test.xjunit", "abcdefg");

    WebResource webResource = resource();

    // get the output of the .xjunit file (should invoke the content generator)
    String textResponse = webResource.path("repos/:public:test.xjunit/viewer").get(String.class);
    assertEquals(
        "Content generator failed to provide correct output",
        "hello viewer content generator",
        textResponse);
  }
 @Override
 public synchronized void startup() {
   ITenant defaultTenant = null;
   loginAsRepositoryAdmin();
   ITenantManager tenantMgr = getTenantManager();
   ITenant systemTenant =
       tenantMgr.createTenant(
           null,
           ServerRepositoryPaths.getPentahoRootFolderName(),
           tenantAdminRoleName,
           tenantAuthenticatedRoleName,
           "Anonymous");
   if (systemTenant != null) {
     userRoleDao.createUser(
         systemTenant,
         systemTenantAdminUserName,
         "password",
         "",
         new String[] {tenantAdminRoleName, tenantAuthenticatedRoleName});
     defaultTenant = tenantMgr.getTenant(JcrTenantUtils.getDefaultTenant().getId());
     if (defaultTenant == null) {
       // We'll create the default tenant here... maybe this isn't the best place.
       defaultTenant =
           tenantMgr.createTenant(
               systemTenant,
               TenantUtils.TENANTID_SINGLE_TENANT,
               tenantAdminRoleName,
               tenantAuthenticatedRoleName,
               "Anonymous");
       userRoleDao.createUser(
           defaultTenant,
           singleTenantAdminUserName,
           "password",
           "",
           new String[] {tenantAdminRoleName});
     }
   }
 }
  @Test
  public void testGetAllAuthorities() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoRole pentahoRole =
        userRoleDao.createRole(mainTenant_1, ROLE_1, ROLE_DESCRIPTION_1, null);
    pentahoRole = userRoleDao.createRole(mainTenant_1, ROLE_2, ROLE_DESCRIPTION_2, null);
    pentahoRole = userRoleDao.createRole(mainTenant_1, ROLE_3, ROLE_DESCRIPTION_3, null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_4, ROLE_DESCRIPTION_4, null);
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_5, ROLE_DESCRIPTION_5, null);
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_6, ROLE_DESCRIPTION_6, null);
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_7, ROLE_DESCRIPTION_7, null);

    List<String> systemRoles = Arrays.asList(new String[] {"Admin"});
    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);
    userDetailsService.setUserRoleDao(userRoleDao);
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});

    List<String> allRolesForDefaultTenant = service.getAllRoles();
    List<String> allRolesForTenant = service.getAllRoles(mainTenant_2);
    assertTrue(allRolesForDefaultTenant.size() == 3 + DEFAULT_ROLE_COUNT);
    assertTrue(allRolesForTenant.size() == 2);

    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    allRolesForDefaultTenant = service.getAllRoles();
    allRolesForTenant = service.getAllRoles(mainTenant_1);
    assertTrue(allRolesForDefaultTenant.size() == 4 + DEFAULT_ROLE_COUNT);
    assertTrue(allRolesForTenant.size() == 2);

    allRolesForTenant = service.getAllRoles(mainTenant_2);
    assertTrue(allRolesForTenant.size() == 4 + DEFAULT_ROLE_COUNT);

    allRolesForTenant = service.getAllRoles(mainTenant_1);
    assertTrue(allRolesForTenant.size() == 2);

    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});

    allRolesForTenant = service.getAllRoles(mainTenant_1);
    assertTrue(allRolesForTenant.size() == 3 + DEFAULT_ROLE_COUNT);

    allRolesForTenant = service.getAllRoles(mainTenant_2);
    assertTrue(allRolesForTenant.size() == 2);

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
    // tenantManager.deleteTenant(mainTenant_1);
    // tenantManager.deleteTenant(mainTenant_2);
    // tenantManager.deleteTenant(systemTenant);
  }
  @Test
  public void testFileAcls() throws InterruptedException {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName});
      mp.defineInstance(IUnifiedRepository.class, repo);

      String publicFolderPath = ClientRepositoryPaths.getPublicFolderPath();
      createTestFile(publicFolderPath.replaceAll("/", ":") + ":" + "aclFile.txt", "abcdefg");

      WebResource webResource = resource();
      RepositoryFileAclDto fileAcls =
          webResource
              .path("repo/files/public:aclFile.txt/acl")
              .accept(APPLICATION_XML)
              .get(RepositoryFileAclDto.class);
      List<RepositoryFileAclAceDto> aces = fileAcls.getAces();
      assertEquals(2, aces.size());
      RepositoryFileAclAceDto ace = aces.get(0);
      assertEquals(authenticatedAuthorityName, ace.getRecipient());
      List<Integer> permissions = ace.getPermissions();
      assertEquals(1, permissions.size());
      Assert.assertTrue(permissions.contains(new Integer(0)));

      String authenticated = authenticatedAuthorityName;

      aces = new ArrayList<RepositoryFileAclAceDto>();
      ace = new RepositoryFileAclAceDto();
      ace.setRecipient(authenticated);
      ace.setRecipientType(1);
      permissions = new ArrayList<Integer>();
      permissions.add(2);
      ace.setPermissions(permissions);
      aces.add(ace);
      fileAcls.setAces(aces);

      ClientResponse putResponse2 =
          webResource
              .path("repo/files/public:aclFile.txt/acl")
              .type(APPLICATION_XML)
              .put(ClientResponse.class, fileAcls);
      assertResponse(putResponse2, Status.OK);
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Test
  public void testGetAllUsernames() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoUser pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_3, PASSWORD_3, USER_DESCRIPTION_3, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_4),
            PASSWORD_4,
            USER_DESCRIPTION_4,
            null);
    pentahoUser = userRoleDao.createUser(null, USER_5, PASSWORD_5, USER_DESCRIPTION_5, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_6),
            PASSWORD_6,
            USER_DESCRIPTION_6,
            null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_7, PASSWORD_7, USER_DESCRIPTION_7, null);
    pentahoUser = userRoleDao.createUser(null, USER_8, PASSWORD_8, USER_DESCRIPTION_8, null);
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);

    List<String> systemRoles = Arrays.asList(new String[] {"Admin"});
    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);
    service.setUserRoleDao(userRoleDao);
    service.setUserDetailsService(userDetailsService);

    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    List<String> allUserForDefaultTenant = service.getAllUsers();
    List<String> allUserForTenant = service.getAllUsers(mainTenant_2);

    assertTrue(allUserForDefaultTenant.size() == 5 + DEFAULT_USER_COUNT);
    assertTrue(allUserForTenant.size() == 0);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    allUserForDefaultTenant = service.getAllUsers();
    allUserForTenant = service.getAllUsers(mainTenant_1);

    assertTrue(allUserForDefaultTenant.size() == 2 + DEFAULT_USER_COUNT);
    assertTrue(allUserForTenant.size() == 0);

    allUserForTenant = service.getAllUsers(mainTenant_1);

    assertTrue(allUserForTenant.size() == 0);
    allUserForTenant = service.getAllUsers(mainTenant_2);
    assertTrue(allUserForTenant.size() == 2 + DEFAULT_USER_COUNT);
    logout();

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    allUserForTenant = service.getAllUsers(mainTenant_1);
    assertTrue(allUserForTenant.size() == 5 + DEFAULT_USER_COUNT);

    allUserForTenant = service.getAllUsers(mainTenant_2);
    assertTrue(allUserForTenant.size() == 0);

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
  }
  // This is testing the Rest end points, we should instead be testing the underlying functionality
  // in unit tests
  @Test
  public void testBrowserDownload() {
    final String text = "abcdefg";

    // mock converters map
    StreamConverter streamConverter = new StreamConverter(repo);
    Map<String, Converter> converterMap = new HashMap<String, Converter>();
    converterMap.put("txt", streamConverter);

    // stub DefaultExportProcessor
    DefaultExportHandler defaultExportHandler = new DefaultExportHandler();
    defaultExportHandler.setConverters(converterMap);
    defaultExportHandler.setRepository(repo);

    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {adminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {adminAuthorityName, authenticatedAuthorityName});

    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            adminAuthorityName,
            authenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {adminAuthorityName});
    try {
      login("admin", mainTenant_1, new String[] {authenticatedAuthorityName, adminAuthorityName});

      mp.defineInstance(IUnifiedRepository.class, repo);
      mp.defineInstance(DefaultExportHandler.class, defaultExportHandler);

      final String fileName = "file.txt";
      createTestFile("/public".replaceAll("/", ":") + ":" + fileName, text);

      // test download of file
      WebResource webResource = resource();
      webResource.path("repo/files/public:file.txt/download").get(ClientResponse.class);

      // test download of dir as a zip file
      ClientResponse r2 =
          webResource.path("repo/files/public:file.txt/download").get(ClientResponse.class);
      assertResponse(r2, Status.OK);
      JerseyTestUtil.assertResponseIsZip(r2);
    } catch (Throwable ex) {
      TestCase.fail();
    } finally {
      cleanupUserAndRoles(mainTenant_1);
      cleanupUserAndRoles(systemTenant);
    }
  }
  @Test
  public void testGetAuthoritiesForUser() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoUser pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_3),
            PASSWORD_3,
            USER_DESCRIPTION_3,
            null);
    pentahoUser = userRoleDao.createUser(null, USER_4, PASSWORD_4, USER_DESCRIPTION_4, null);
    logout();

    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_5, PASSWORD_5, USER_DESCRIPTION_5, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_2, USER_6),
            PASSWORD_6,
            USER_DESCRIPTION_6,
            null);

    logout();

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoRole pentahoRole =
        userRoleDao.createRole(mainTenant_1, ROLE_1, ROLE_DESCRIPTION_1, null);
    pentahoRole =
        userRoleDao.createRole(
            null,
            tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_2),
            ROLE_DESCRIPTION_2,
            null);
    pentahoRole = userRoleDao.createRole(null, ROLE_3, ROLE_DESCRIPTION_3, null);
    logout();

    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_4, ROLE_DESCRIPTION_4, null);
    userRoleDao.setUserRoles(null, USER_5, new String[] {ROLE_4});
    userRoleDao.setUserRoles(
        null, tenantedUserNameUtils.getPrincipleId(mainTenant_2, USER_6), new String[] {ROLE_4});
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    userRoleDao.setUserRoles(mainTenant_1, USER_2, new String[] {ROLE_1, ROLE_2, ROLE_3});

    List<String> systemRoles = Arrays.asList(new String[] {"Admin"});

    try {
      userRoleDao.setUserRoles(mainTenant_1, USER_3, new String[] {ROLE_2, ROLE_3, ROLE_4});
      fail("Exception should be thrown");
    } catch (Throwable th) {
      assertNotNull(th);
    }

    try {
      userRoleDao.setUserRoles(mainTenant_1, USER_4, new String[] {ROLE_2, ROLE_4});
      fail("Exception should be thrown");
    } catch (Throwable th) {
      assertNotNull(th);
    }
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);
    userDetailsService.setDefaultRole(tenantAuthenticatedAuthorityName);

    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);
    service.setUserDetailsService(userDetailsService);

    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    List<String> rolesForUser_2 = service.getRolesForUser(mainTenant_1, USER_2);
    List<String> rolesForUser_2_1 = service.getRolesForUser(null, USER_2);
    List<String> rolesForUser_2_1_1 =
        service.getRolesForUser(null, tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_2));
    List<String> rolesForUser_3 = service.getRolesForUser(mainTenant_1, USER_3);
    List<String> rolesForUser_4 = service.getRolesForUser(mainTenant_1, USER_4);

    assertTrue(rolesForUser_2.size() == 4);
    assertTrue(rolesForUser_2_1.size() == 4);
    assertTrue(rolesForUser_2_1_1.size() == 4);
    assertTrue(rolesForUser_3.size() == 3);
    assertTrue(rolesForUser_4.size() == 2);

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
  }
  @Test
  public void testGetUsernamesInRole() {
    loginAsRepositoryAdmin();
    ITenant systemTenant =
        tenantManager.createTenant(
            null,
            ServerRepositoryPaths.getPentahoRootFolderName(),
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        systemTenant, sysAdminUserName, "password", "", new String[] {tenantAdminAuthorityName});
    login(
        sysAdminUserName,
        systemTenant,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    ITenant mainTenant_1 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_1,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_1, "admin", "password", "", new String[] {tenantAdminAuthorityName});
    ITenant mainTenant_2 =
        tenantManager.createTenant(
            systemTenant,
            MAIN_TENANT_2,
            tenantAdminAuthorityName,
            tenantAuthenticatedAuthorityName,
            "Anonymous");
    userRoleDao.createUser(
        mainTenant_2, "admin", "password", "", new String[] {tenantAdminAuthorityName});

    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoUser pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
    pentahoUser = userRoleDao.createUser(null, USER_3, PASSWORD_3, USER_DESCRIPTION_3, null);
    pentahoUser =
        userRoleDao.createUser(
            null,
            tenantedUserNameUtils.getPrincipleId(mainTenant_1, USER_4),
            PASSWORD_4,
            USER_DESCRIPTION_4,
            null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_5, PASSWORD_5, USER_DESCRIPTION_5, null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_1, USER_6, PASSWORD_6, USER_DESCRIPTION_6, null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_7, PASSWORD_7, USER_DESCRIPTION_7, null);
    pentahoUser =
        userRoleDao.createUser(mainTenant_2, USER_8, PASSWORD_8, USER_DESCRIPTION_8, null);
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    IPentahoRole pentahoRole =
        userRoleDao.createRole(mainTenant_1, ROLE_1, ROLE_DESCRIPTION_1, null);
    pentahoRole = userRoleDao.createRole(null, ROLE_2, ROLE_DESCRIPTION_2, null);
    pentahoRole =
        userRoleDao.createRole(
            null,
            tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_3),
            ROLE_DESCRIPTION_3,
            null);
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    pentahoRole = userRoleDao.createRole(mainTenant_2, ROLE_4, ROLE_DESCRIPTION_4, null);
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    userRoleDao.setRoleMembers(null, ROLE_1, new String[] {USER_2, USER_3, USER_4});
    userRoleDao.setRoleMembers(mainTenant_1, ROLE_2, new String[] {USER_5, USER_6, USER_7});
    userRoleDao.setRoleMembers(
        null,
        tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_3),
        new String[] {USER_2, USER_4, USER_6});
    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    userRoleDao.setRoleMembers(null, ROLE_4, new String[] {USER_3, USER_5, USER_7});
    logout();
    login(
        "admin",
        mainTenant_1,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});
    UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
    userDetailsService.setUserRoleDao(userRoleDao);
    userDetailsService.setDefaultRole(tenantAuthenticatedAuthorityName);
    List<String> systemRoles = new ArrayList<String>();
    systemRoles.add("Admin");

    List<String> extraRoles = Arrays.asList(new String[] {"Authenticated", "Anonymous"});
    String adminRole = "Admin";

    UserRoleDaoUserRoleListService service =
        new UserRoleDaoUserRoleListService(
            userRoleDao,
            userDetailsService,
            tenantedUserNameUtils,
            systemRoles,
            extraRoles,
            adminRole);

    List<String> usersInRole_1 = service.getUsersInRole(mainTenant_1, ROLE_1);
    List<String> usersInRole_2 = service.getUsersInRole(null, ROLE_2);
    List<String> usersInRole_3 =
        service.getUsersInRole(null, tenantedRoleNameUtils.getPrincipleId(mainTenant_1, ROLE_3));

    logout();
    login(
        "admin",
        mainTenant_2,
        new String[] {tenantAdminAuthorityName, tenantAuthenticatedAuthorityName});

    List<String> usersInRole_4 = service.getUsersInRole(mainTenant_2, ROLE_4);

    assertTrue(usersInRole_1.size() == 3);
    assertTrue(usersInRole_2.size() == 2);
    assertTrue(usersInRole_3.size() == 3);
    assertTrue(usersInRole_4.size() == 1);

    logout();

    cleanupUserAndRoles("admin", mainTenant_1);
    cleanupUserAndRoles("admin", mainTenant_2);
    cleanupUserAndRoles(sysAdminUserName, systemTenant);
  }
  /** {@inheritDoc} */
  public void permanentlyDeleteFile(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId)
      throws RepositoryException {
    Assert.notNull(fileId);
    Node fileNode = session.getNodeByIdentifier(fileId.toString());
    // guard against using a file retrieved from a more lenient session inside a more strict session
    Assert.notNull(fileNode);

    // see if anything is referencing this node; if yes, then we cannot delete it as a
    // ReferentialIntegrityException
    // will result
    Set<RepositoryFile> referrers = new HashSet<RepositoryFile>();
    PropertyIterator refIter = fileNode.getReferences();
    if (refIter.hasNext()) {
      while (refIter.hasNext()) {
        // for each referrer property, march up the tree until we find the file node to which the
        // property belongs
        RepositoryFile referrer =
            getReferrerFile(session, pentahoJcrConstants, refIter.nextProperty());
        if (referrer != null) {
          referrers.add(referrer);
        }
      }
      if (!referrers.isEmpty()) {
        RepositoryFile referee =
            JcrRepositoryFileUtils.nodeToFile(
                session, pentahoJcrConstants, pathConversionHelper, lockHelper, fileNode);
        throw new RepositoryFileDaoReferentialIntegrityException(referee, referrers);
      }
    }

    // technically, the node can be deleted while it is locked; however, we want to avoid an
    // orphaned lock token;
    // delete
    // it first
    if (fileNode.isLocked()) {
      Lock lock = session.getWorkspace().getLockManager().getLock(fileNode.getPath());
      // don't need lock token anymore
      lockHelper.removeLockToken(session, pentahoJcrConstants, lock);
    }

    // if this file was non-permanently deleted, delete its containing folder too
    IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
    String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY);
    String trashFolder =
        ServerRepositoryPaths.getUserHomeFolderPath(
                new Tenant(tenantId, true), PentahoSessionHolder.getSession().getName())
            + RepositoryFile.SEPARATOR
            + FOLDER_NAME_TRASH;
    Node parent = fileNode.getParent();

    purgeHistory(fileNode, session, pentahoJcrConstants);

    if (fileNode.getPath().startsWith(trashFolder)) {
      // Remove the file and then the wrapper foler
      fileNode.remove();
      parent.remove();
    } else {
      fileNode.remove();
    }
  }
  private RepositoryFile createUserHomeFolder(ITenant theTenant, String username, Session session)
      throws RepositoryException {
    Builder aclsForUserHomeFolder = null;
    Builder aclsForTenantHomeFolder = null;

    if (theTenant == null) {
      theTenant = JcrTenantUtils.getTenant(username, true);
      username = JcrTenantUtils.getPrincipalName(username, true);
    }
    if (theTenant == null || theTenant.getId() == null) {
      theTenant = JcrTenantUtils.getCurrentTenant();
    }
    if (theTenant == null || theTenant.getId() == null) {
      theTenant = JcrTenantUtils.getDefaultTenant();
    }
    RepositoryFile userHomeFolder = null;
    String userId = tenantedUserNameUtils.getPrincipleId(theTenant, username);
    final RepositoryFileSid userSid = new RepositoryFileSid(userId);
    RepositoryFile tenantHomeFolder = null;
    RepositoryFile tenantRootFolder = null;
    RepositoryFileSid ownerSid = null;
    // Get the Tenant Root folder. If the Tenant Root folder does not exist then exit.
    tenantRootFolder =
        JcrRepositoryFileUtils.getFileByAbsolutePath(
            session,
            ServerRepositoryPaths.getTenantRootFolderPath(theTenant),
            pathConversionHelper,
            lockHelper,
            false,
            null);
    if (tenantRootFolder != null) {
      // Try to see if Tenant Home folder exist
      tenantHomeFolder =
          JcrRepositoryFileUtils.getFileByAbsolutePath(
              session,
              ServerRepositoryPaths.getTenantHomeFolderPath(theTenant),
              pathConversionHelper,
              lockHelper,
              false,
              null);

      if (tenantHomeFolder == null) {
        String ownerId = tenantedUserNameUtils.getPrincipleId(theTenant, username);
        ownerSid = new RepositoryFileSid(ownerId, Type.USER);

        String tenantAuthenticatedRoleId =
            tenantedRoleNameUtils.getPrincipleId(theTenant, authenticatedRoleName);
        RepositoryFileSid tenantAuthenticatedRoleSid =
            new RepositoryFileSid(tenantAuthenticatedRoleId, Type.ROLE);

        aclsForTenantHomeFolder =
            new RepositoryFileAcl.Builder(userSid)
                .ace(tenantAuthenticatedRoleSid, EnumSet.of(RepositoryFilePermission.READ));

        aclsForUserHomeFolder =
            new RepositoryFileAcl.Builder(userSid)
                .ace(ownerSid, EnumSet.of(RepositoryFilePermission.ALL));
        tenantHomeFolder =
            internalCreateFolder(
                session,
                tenantRootFolder.getId(),
                new RepositoryFile.Builder(ServerRepositoryPaths.getTenantHomeFolderName())
                    .folder(true)
                    .title(
                        Messages.getInstance()
                            .getString("AbstractJcrBackedUserRoleDao.usersFolderDisplayName"))
                    .build(),
                aclsForTenantHomeFolder.build(),
                "tenant home folder"); //$NON-NLS-1$
      } else {
        String ownerId = tenantedUserNameUtils.getPrincipleId(theTenant, username);
        ownerSid = new RepositoryFileSid(ownerId, Type.USER);
        aclsForUserHomeFolder =
            new RepositoryFileAcl.Builder(userSid)
                .ace(ownerSid, EnumSet.of(RepositoryFilePermission.ALL));
      }

      // now check if user's home folder exist
      userHomeFolder =
          JcrRepositoryFileUtils.getFileByAbsolutePath(
              session,
              ServerRepositoryPaths.getUserHomeFolderPath(theTenant, username),
              pathConversionHelper,
              lockHelper,
              false,
              null);
      if (userHomeFolder == null) {
        userHomeFolder =
            internalCreateFolder(
                session,
                tenantHomeFolder.getId(),
                new RepositoryFile.Builder(username).folder(true).build(),
                aclsForUserHomeFolder.build(),
                "user home folder"); //$NON-NLS-1$
      }
    }
    return userHomeFolder;
  }