protected String generateCacheKey() {
   boolean isVisitor = true;
   String role = "V";
   String principalName = ctx.getPrincipal().getName();
   try {
     if (getPage().isAdministrator(principalName)) {
       role = "A";
     } else if (getPage().isContributor(principalName)) {
       role = "C";
     }
   } catch (ClientException e) {
     LOG.warn(
         "Unable to get site adapter while generating cache key so cached page is used: "
             + e.getMessage());
   }
   if (isVisitor) {
     String dateStr = "";
     try {
       dateStr =
           Long.toString(
               ((Calendar) getDocument().getPropertyValue("dc:modified")).getTime().getTime());
     } catch (PropertyException e) {
       LOG.warn("Unable to get property 'dc:modified': " + e.getMessage());
     } catch (ClientException e) {
       LOG.warn("Unable to get property 'dc:modified': " + e.getMessage());
     }
     return generateCacheName() + "-" + getPath() + "-" + role + "-" + dateStr;
   } else {
     return CacheBlock.NO_CACHE_KEY;
   }
 }
  public static Map<String, Object> getSuggestedUsers(String pattern) {
    Map<String, Object> params = new HashMap<String, Object>();
    List<GroupUserSuggest> suggests;
    try {
      suggests = GroupsUsersSuggestHelper.getSuggestions(pattern);
      params.put("suggests", suggests);
    } catch (SizeLimitExceededException e) {
      params.put("errorMessage", "Trop de resultats, veuillez affiner votre recherche.");
    } catch (ClientException e) {
      params.put("errorMessage", e.getMessage());
    }

    return params;
  }
  protected List<DocumentModel> computeCurrentPage() {
    if (pageUsers == null) {
      error = null;
      errorMessage = null;
      pageUsers = new ArrayList<>();

      List<DocumentModel> users = new ArrayList<DocumentModel>();
      try {
        UserManager userManager = Framework.getLocalService(UserManager.class);
        String userListingMode = getUserListingMode();
        if (ALL_MODE.equals(userListingMode)) {
          users = searchAllUsers(userManager);
        } else if (SEARCH_ONLY_MODE.equals(userListingMode)) {
          users = searchUsers(userManager);
        } else if (TABBED_MODE.equals(userListingMode)) {
          users = searchUsersFromCatalog(userManager);
        }
      } catch (SizeLimitExceededException slee) {
        error = slee;
        errorMessage = SEARCH_OVERFLOW_ERROR_MESSAGE;
        log.warn(slee.getMessage(), slee);
      } catch (ClientException e) {
        error = e;
        errorMessage = e.getMessage();
        log.warn(e.getMessage(), e);
      }

      if (!hasError()) {
        long resultsCount = users.size();
        setResultsCount(resultsCount);
        // post-filter the results "by hand" to handle pagination
        long pageSize = getMinMaxPageSize();
        if (pageSize == 0) {
          pageUsers.addAll(users);
        } else {
          // handle offset
          long offset = getCurrentPageOffset();
          if (offset <= resultsCount) {
            for (int i = Long.valueOf(offset).intValue();
                i < resultsCount && i < offset + pageSize;
                i++) {
              pageUsers.add(users.get(i));
            }
          }
        }
      }
    }
    return pageUsers;
  }
  /** Retrieves the available locations. */
  @Factory("availableCoreRepositories")
  public List<Repository> getAvailableRepositories() throws ClientException {
    try {
      if (availableRepositories == null) {
        availableRepositories = getRepositoryManager().getRepositories();
      }
      List<Repository> result = new ArrayList<Repository>();
      result.addAll(availableRepositories);
      return result;

    } catch (Throwable t) {
      throw ClientException.wrap(t);
    }
  }
  public String selectRepository(String repositoryName) throws ClientException {
    try {
      Repository selectedRepository = null;

      for (Repository repo : getRepositoryManager().getRepositories()) {
        if (repo.getName().equals(repositoryName)) {
          selectedRepository = repo;
          break;
        }
      }
      log.debug("Selected core name: " + repositoryName);
      if (selectedRepository != null) {
        RepositoryLocation selectedLocation = new RepositoryLocation(selectedRepository.getName());
        navigationContext.setCurrentServerLocation(selectedLocation);
        return DEFAULT_VIEW;
      } else {
        return null;
      }
    } catch (Throwable t) {
      throw ClientException.wrap(t);
    }
  }
  @Test
  public void testIntegrationTestsSetupAndTearDown() throws Exception {

    // ---------------------------------------------------------
    // Setup the integration tests environment as Administrator
    // ---------------------------------------------------------
    Blob testUserCredentialsBlob =
        (Blob)
            clientSession
                .newRequest(NuxeoDriveSetupIntegrationTests.ID)
                .set("userNames", "joe,jack")
                .execute();
    assertNotNull(testUserCredentialsBlob);

    // Check test users
    String testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8");
    assertNotNull(testUserCredentials);
    String[] testUserCrendentialsArray = StringUtils.split(testUserCredentials, ",");
    assertEquals(2, testUserCrendentialsArray.length);
    assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_joe:"));
    assertTrue(testUserCrendentialsArray[1].startsWith("nuxeoDriveTestUser_jack:"));

    // useMembersGroup is false by default
    NuxeoPrincipal joePrincipal = userManager.getPrincipal("nuxeoDriveTestUser_joe");
    assertNotNull(joePrincipal);
    assertFalse(joePrincipal.getGroups().contains("members"));
    NuxeoPrincipal jackPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_jack");
    assertNotNull(jackPrincipal);
    assertFalse(jackPrincipal.getGroups().contains("members"));

    // Check test workspace
    DocumentRef testWorkspaceRef = new PathRef(TEST_WORKSPACE_PATH);
    DocumentModel testWorkspace = session.getDocument(testWorkspaceRef);
    assertEquals("Workspace", testWorkspace.getType());
    assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle());
    assertTrue(session.hasPermission(joePrincipal, testWorkspaceRef, SecurityConstants.WRITE));
    assertTrue(session.hasPermission(jackPrincipal, testWorkspaceRef, SecurityConstants.WRITE));

    // Create test users' personal workspaces for cleanup check
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_joe", session.getRootDocument());
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_jack", session.getRootDocument());
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe")));
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack")));

    // ----------------------------------------------------------------------
    // Setup the integration tests environment with other user names without
    // having teared it down previously => should start by cleaning it up
    // ----------------------------------------------------------------------
    testUserCredentialsBlob =
        (Blob)
            clientSession
                .newRequest(NuxeoDriveSetupIntegrationTests.ID)
                .set("userNames", "sarah")
                .set("useMembersGroup", true)
                .execute();
    assertNotNull(testUserCredentialsBlob);

    // Check cleanup
    assertNull(userManager.getPrincipal("nuxeoDriveTestUser_joe"));
    assertNull(userManager.getPrincipal("nuxeoDriveTestUser_jack"));
    // Invalid VCS cache
    session.save();
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe",
          e.getMessage());
    }
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack",
          e.getMessage());
    }

    // Check test users
    testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8");
    assertNotNull(testUserCredentials);
    testUserCrendentialsArray = StringUtils.split(testUserCredentials, ",");
    assertEquals(1, testUserCrendentialsArray.length);
    assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_sarah:"));

    NuxeoPrincipal sarahPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_sarah");
    assertNotNull(sarahPrincipal);
    assertTrue(sarahPrincipal.getGroups().contains("members"));

    // Check test workspace
    testWorkspace = session.getDocument(testWorkspaceRef);
    assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle());
    assertTrue(session.hasPermission(sarahPrincipal, testWorkspaceRef, SecurityConstants.WRITE));

    // Create test users' personal workspaces for cleanup check
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_sarah", session.getRootDocument());
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah")));

    // ----------------------------------------------------------------------
    // Try to setup the integration tests environment as an unauthorized
    // user => should fail
    // ----------------------------------------------------------------------
    Session unauthorizedSession =
        automationClient.getSession("nuxeoDriveTestUser_sarah", testUserCrendentialsArray[0]);
    try {
      unauthorizedSession
          .newRequest(NuxeoDriveSetupIntegrationTests.ID)
          .set("userNames", "john,bob")
          .execute();
      fail(
          "NuxeoDrive.SetupIntegrationTests operation should not be callable by a non administrator.");
    } catch (Exception e) {
      // Expected
    }

    // ----------------------------------------------------------------------
    // Try to tear down the integration tests environment as an unauthorized
    // user => should fail
    // ----------------------------------------------------------------------
    try {
      unauthorizedSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute();
      fail(
          "NuxeoDrive.TearDownIntegrationTests operation should not be callable by a non administrator.");
    } catch (Exception e) {
      // Expected
    }

    // ----------------------------------------------------------------------
    // Tear down the integration tests environment as Administrator
    // ----------------------------------------------------------------------
    clientSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute();
    assertTrue(userManager.searchUsers("nuxeoDriveTestUser_").isEmpty());
    // Invalid VCS cache
    session.save();
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah",
          e.getMessage());
    }
    assertFalse(session.exists(testWorkspaceRef));
  }