private NodeRef createFolderWithPermission(NodeRef parent, String username, String permission) {
    // Authenticate as system user because the current user should not be node owner
    AuthenticationComponent authenticationComponent =
        (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();

    // Create the folder
    NodeRef folder =
        nodeService
            .createNode(
                parent,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("TestFolder" + GUID.generate()),
                ContentModel.TYPE_CONTENT)
            .getChildRef();

    // Apply permissions to folder
    permissionService.deletePermissions(folder);
    permissionService.setInheritParentPermissions(folder, false);
    permissionService.setPermission(folder, userName, permission, true);

    // Authenticate test user
    TestWithUserUtils.authenticateUser(
        this.userName, PWD, this.rootNodeRef, this.authenticationService);

    return folder;
  }
예제 #2
0
  /**
   * Reset any permissions that have been set on the node.
   *
   * <p>All permissions will be deleted and the node set to inherit permissions.
   *
   * @param node node
   */
  public void resetAllPermissions(ScriptNode node) {
    final NodeRef nodeRef = node.getNodeRef();

    // ensure the user has permission to Change Permissions
    final PermissionService permissionService = serviceRegistry.getPermissionService();
    if (permissionService
        .hasPermission(nodeRef, PermissionService.CHANGE_PERMISSIONS)
        .equals(AccessStatus.ALLOWED)) {
      AuthenticationUtil.runAs(
          new RunAsWork<Void>() {
            public Void doWork() throws Exception {
              // Ensure node isn't inheriting permissions from an ancestor before deleting
              if (!permissionService.getInheritParentPermissions(nodeRef)) {
                permissionService.deletePermissions(nodeRef);
                permissionService.setInheritParentPermissions(nodeRef, true);
              }
              return null;
            }
          },
          AuthenticationUtil.SYSTEM_USER_NAME);
    } else {
      throw new AlfrescoRuntimeException(
          "You do not have the authority to update permissions on this node.");
    }
  }
예제 #3
0
  /**
   * Apply a set of permissions to the node.
   *
   * @param node node
   * @param permissions permissions
   */
  public void setPermissions(final ScriptNode node, final Object permissions) {
    final NodeRef nodeRef = node.getNodeRef();

    if (permissions != null && permissions instanceof ScriptableObject) {
      final PermissionService permissionService = this.serviceRegistry.getPermissionService();
      // ensure the user has permission to Change Permissions
      if (permissionService
          .hasPermission(nodeRef, PermissionService.CHANGE_PERMISSIONS)
          .equals(AccessStatus.ALLOWED)) {
        AuthenticationUtil.runAs(
            new RunAsWork<Void>() {
              public Void doWork() throws Exception {
                if (!permissionService.getInheritParentPermissions(nodeRef)) {
                  // remove existing permissions
                  permissionService.deletePermissions(nodeRef);
                }

                // Assign the correct permissions
                ScriptableObject scriptable = (ScriptableObject) permissions;
                Object[] propIds = scriptable.getIds();
                for (int i = 0; i < propIds.length; i++) {
                  // Work on each key in turn
                  Object propId = propIds[i];

                  // Only interested in keys that are formed of Strings
                  if (propId instanceof String) {
                    // Get the value out for the specified key - it must be String
                    final String key = (String) propId;
                    final Object value = scriptable.get(key, scriptable);
                    if (value instanceof String) {
                      // Set the permission on the node
                      permissionService.setPermission(nodeRef, key, (String) value, true);
                    }
                  }
                }

                // always add the site managers group with SiteManager permission
                String managers =
                    siteService.getSiteRoleGroup(getShortName(), SiteModel.SITE_MANAGER);
                permissionService.setPermission(nodeRef, managers, SiteModel.SITE_MANAGER, true);

                // now turn off inherit to finalize our permission changes
                permissionService.setInheritParentPermissions(nodeRef, false);
                return null;
              }
            },
            AuthenticationUtil.SYSTEM_USER_NAME);
      }
    } else {
      // No permissions passed-in
      this.resetAllPermissions(node);
    }
  }
  public void testSetFlags() throws Exception {
    NavigableMap<Long, FileInfo> fis =
        imapService.getFolderStatus(
                authenticationService.getCurrentUserName(),
                testImapFolderNodeRef,
                ImapViewMode.ARCHIVE)
            .search;
    if (fis != null && fis.size() > 0) {
      FileInfo messageFileInfo = fis.firstEntry().getValue();
      try {
        setFlags(messageFileInfo);
        fail("Can't set flags");
      } catch (Exception e) {
        if (e instanceof AccessDeniedException) {
          // expected
        } else {
          throw e;
        }
      }

      reauthenticate(USER_NAME, USER_PASSWORD);

      permissionService.setPermission(
          testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);

      reauthenticate(anotherUserName, anotherUserName);

      setFlags(messageFileInfo);
    }
  }
  @Override
  public List<AclReaders> getAclsReaders(List<Long> aclIds) {
    if (enabled) {
      // We don't want the caches to lie and we may not be part of the cluster
      aclDAO.setCheckAclConsistency();

      /*
       * This is an N+1 query that should, in theory, make use of cached ACL readers data.
       */

      Map<Long, String> aclChangeSetTenant = new HashMap<Long, String>(aclIds.size());

      List<AclReaders> aclsReaders = new ArrayList<AclReaders>(aclIds.size() * 10);
      for (Long aclId : aclIds) {
        AclReaders readers = new AclReaders();
        readers.setAclId(aclId);
        Set<String> readersSet = permissionService.getReaders(aclId);
        readers.setReaders(readersSet);
        Set<String> deniedSet = permissionService.getReadersDenied(aclId);
        readers.setDenied(deniedSet);

        Long aclChangeSetId =
            aclDAO.getAccessControlList(aclId).getProperties().getAclChangeSetId();
        readers.setAclChangeSetId(aclChangeSetId);

        if (AuthenticationUtil.isMtEnabled()) {
          // MT - for now, derive the tenant for acl (via acl change set)
          String tenantDomain = aclChangeSetTenant.get(aclChangeSetId);
          if (tenantDomain == null) {
            tenantDomain = getTenant(aclId, aclChangeSetId);
            if (tenantDomain == null) {
              // skip this acl !
              continue;
            }
            aclChangeSetTenant.put(aclChangeSetId, tenantDomain);
          }
          readers.setTenantDomain(tenantDomain);
        }

        aclsReaders.add(readers);
      }

      return aclsReaders;
    } else {
      return Collections.<AclReaders>emptyList();
    }
  }
  /**
   * @see org.alfresco.web.action.ActionEvaluator#evaluate(org.alfresco.web.bean.repository.Node)
   */
  public boolean evaluate(final Node node) {
    // is the authenticated user permitted to execute the regenerate renditions action
    // against at least one web project
    boolean isUserAllowed = false;

    final FacesContext fc = FacesContext.getCurrentInstance();
    final ServiceRegistry services = Repository.getServiceRegistry(fc);
    final PermissionService permissionService = services.getPermissionService();
    final WebProjectService webProjectService = services.getWebProjectService();
    final NavigationBean navigator =
        (NavigationBean) FacesHelper.getManagedBean(fc, NavigationBean.BEAN_NAME);

    // check that the authenticated user has CONTENT MANAGER permissions for at least one web
    // project
    // this will ensure that the action appears only if the user is able to regenerate renditions
    // for at least one web project
    List<WebProjectInfo> wpInfos = webProjectService.listWebProjects();
    for (WebProjectInfo wpInfo : wpInfos) {
      if (permissionService.hasPermission(
              wpInfo.getNodeRef(), PermissionService.WCM_CONTENT_MANAGER)
          == AccessStatus.ALLOWED) {
        isUserAllowed = true;
        break;
      }
    }

    // TODO improve how we determine whether the form supports the ability to regenerate renditions
    // or not

    // get the path to the current name - compare each path element with the Web Forms folder name
    final Path path = navigator.getCurrentNode().getNodePath();

    boolean isWebFormsPath = false;
    Iterator<Path.Element> itr = path.iterator();
    while (itr.hasNext()) {
      Path.Element element = (Path.Element) itr.next();
      String pathElement = element.getPrefixedString(services.getNamespaceService());
      if (Application.getWebContentFormsFolderName(fc).equals(pathElement)) {
        isWebFormsPath = true;
        break;
      }
    }

    return (node.hasAspect(WCMAppModel.ASPECT_RENDERING_ENGINE_TEMPLATE) || isWebFormsPath)
        && isUserAllowed;
  }
 /**
  * Helper to encapsulate the test for whether the currently authenticated user can write to the
  * preferences objects for the given username and person node reference.
  *
  * @param userName Username owner of the preferences object for modification test
  * @param personNodeRef Non-null person representing the given username
  * @return true if they are allowed to write to the user preferences, false otherwise
  */
 private boolean userCanWritePreferences(final String userName, final NodeRef personNodeRef) {
   final String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
   return (userName.equals(currentUserName)
       || personService
           .getUserIdentifier(userName)
           .equals(personService.getUserIdentifier(currentUserName))
       || authenticationContext.isSystemUserName(currentUserName)
       || permissionService.hasPermission(personNodeRef, PermissionService.WRITE)
           == AccessStatus.ALLOWED);
 }
  @Override
  protected String applyInternal() throws Exception {
    String guestId = AuthenticationUtil.getGuestUserName();
    if (personService.personExists(guestId)) {
      NodeRef personRef = personService.getPerson(guestId);
      permissionService.setInheritParentPermissions(personRef, true);
    }

    return I18NUtil.getMessage(MSG_SUCCESS);
  }
  private NodeRef createNodeWithPermission(NodeRef parent, String username, String permission) {
    // Authenticate as system user because the current user should not be node owner
    AuthenticationComponent authenticationComponent =
        (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();

    // Create the node as a copy of prepared
    NodeRef node =
        copyService.copy(nodeRef, parent, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_CONTENT);

    // Apply permissions to node
    permissionService.deletePermissions(node);
    permissionService.setInheritParentPermissions(node, false);
    permissionService.setPermission(node, userName, permission, true);

    // Authenticate test user
    TestWithUserUtils.authenticateUser(
        this.userName, PWD, this.rootNodeRef, this.authenticationService);

    return node;
  }
  /*
   * Extract favourite nodes of the given type from the comma-separated list in "nodes".
   */
  private Map<PersonFavouriteKey, PersonFavourite> extractFavouriteNodes(
      String userName, Type type, String nodes) {
    PrefKeys prefKeys = getPrefKeys(type);
    Map<PersonFavouriteKey, PersonFavourite> favouriteNodes =
        new HashMap<PersonFavouriteKey, PersonFavourite>();

    StringTokenizer st = new StringTokenizer(nodes, ",");
    while (st.hasMoreTokens()) {
      String nodeRefStr = st.nextToken();
      nodeRefStr = nodeRefStr.trim();
      if (!NodeRef.isNodeRef((String) nodeRefStr)) {
        continue;
      }

      NodeRef nodeRef = new NodeRef((String) nodeRefStr);

      if (!nodeService.exists(nodeRef)) {
        continue;
      }

      if (permissionService.hasPermission(nodeRef, PermissionService.READ_PROPERTIES)
          == AccessStatus.DENIED) {
        continue;
      }

      // get createdAt for this favourited node
      // use ISO8601
      StringBuilder builder = new StringBuilder(prefKeys.getAlfrescoPrefKey());
      builder.append(nodeRef.toString());
      builder.append(".createdAt");
      String prefKey = builder.toString();
      String createdAtStr = (String) preferenceService.getPreference(userName, prefKey);
      Date createdAt = (createdAtStr != null ? ISO8601DateFormat.parse(createdAtStr) : null);

      String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

      PersonFavourite personFavourite =
          new PersonFavourite(userName, nodeRef, type, name, createdAt);
      PersonFavouriteKey key = personFavourite.getKey();
      favouriteNodes.put(key, personFavourite);
    }

    return favouriteNodes;
  }
예제 #11
0
 /* (non-Javadoc)
  * @see org.alfresco.service.cmr.view.Exporter#startACL(org.alfresco.service.cmr.repository.NodeRef)
  */
 public void startACL(NodeRef nodeRef) {
   try {
     AttributesImpl attrs = new AttributesImpl();
     boolean inherit = permissionService.getInheritParentPermissions(nodeRef);
     if (!inherit) {
       attrs.addAttribute(
           NamespaceService.REPOSITORY_VIEW_1_0_URI,
           INHERITPERMISSIONS_LOCALNAME,
           INHERITPERMISSIONS_QNAME.toPrefixString(),
           null,
           "false");
     }
     contentHandler.startElement(
         ACL_QNAME.getNamespaceURI(), ACL_QNAME.getLocalName(), toPrefixString(ACL_QNAME), attrs);
   } catch (SAXException e) {
     throw new ExporterException(
         "Failed to process start ACL event - node ref " + nodeRef.toString());
   }
 }
  public void testGetFlags() throws Exception {
    NavigableMap<Long, FileInfo> fis =
        imapService.getFolderStatus(
                authenticationService.getCurrentUserName(),
                testImapFolderNodeRef,
                ImapViewMode.ARCHIVE)
            .search;
    if (fis != null && fis.size() > 0) {
      FileInfo messageFileInfo = fis.firstEntry().getValue();

      reauthenticate(USER_NAME, USER_PASSWORD);

      permissionService.setPermission(
          testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);

      imapService.setFlags(messageFileInfo, flags, true);

      reauthenticate(anotherUserName, anotherUserName);

      Flags fl = imapService.getFlags(messageFileInfo);
      assertTrue(fl.contains(flags));
    }
  }
  public void testSetFlag() throws Exception {
    NavigableMap<Long, FileInfo> fis =
        imapService.getFolderStatus(
                authenticationService.getCurrentUserName(),
                testImapFolderNodeRef,
                ImapViewMode.ARCHIVE)
            .search;
    if (fis != null && fis.size() > 0) {
      FileInfo messageFileInfo = fis.firstEntry().getValue();

      reauthenticate(USER_NAME, USER_PASSWORD);

      permissionService.setPermission(
          testImapFolderNodeRef, anotherUserName, PermissionService.WRITE, true);

      reauthenticate(anotherUserName, anotherUserName);

      imapService.setFlag(messageFileInfo, Flags.Flag.RECENT, true);

      Serializable prop =
          nodeService.getProperty(messageFileInfo.getNodeRef(), ImapModel.PROP_FLAG_RECENT);
      assertNotNull("Can't set RECENT flag", prop);
    }
  }
예제 #14
0
  @Override
  public void setUp() throws Exception {
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    authenticationService = serviceRegistry.getAuthenticationService();
    imapService = serviceRegistry.getImapService();
    importerService = serviceRegistry.getImporterService();
    NodeService nodeService = serviceRegistry.getNodeService();
    SearchService searchService = serviceRegistry.getSearchService();
    NamespaceService namespaceService = serviceRegistry.getNamespaceService();
    PersonService personService = serviceRegistry.getPersonService();
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    TransactionService transactionService = serviceRegistry.getTransactionService();
    PermissionService permissionService = serviceRegistry.getPermissionService();

    // start the transaction
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();

    authenticationService.authenticate(USER_NAME, USER_PASSWORD.toCharArray());

    anotherUserName = "******";

    NodeRef person = personService.getPerson(anotherUserName);

    if (person != null) {
      personService.deletePerson(anotherUserName);
      PropertyMap testUser = new PropertyMap();
      testUser.put(ContentModel.PROP_USERNAME, anotherUserName);
      testUser.put(ContentModel.PROP_FIRSTNAME, anotherUserName);
      testUser.put(ContentModel.PROP_LASTNAME, anotherUserName);
      testUser.put(ContentModel.PROP_EMAIL, anotherUserName + "@alfresco.com");
      testUser.put(ContentModel.PROP_JOBTITLE, "jobTitle");
      personService.createPerson(testUser);
    }
    if (authenticationService.authenticationExists(anotherUserName)) {
      authenticationService.deleteAuthentication(anotherUserName);
    }
    authenticationService.createAuthentication(anotherUserName, anotherUserName.toCharArray());

    user =
        new AlfrescoImapUser(anotherUserName + "@alfresco.com", anotherUserName, anotherUserName);

    String storePath = "workspace://SpacesStore";
    String companyHomePathInStore = "/app:company_home";

    StoreRef storeRef = new StoreRef(storePath);
    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);

    List<NodeRef> nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef, companyHomePathInStore, null, namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);

    ChildApplicationContextFactory imap = (ChildApplicationContextFactory) ctx.getBean("imap");
    ApplicationContext imapCtx = imap.getApplicationContext();
    ImapServiceImpl imapServiceImpl = (ImapServiceImpl) imapCtx.getBean("imapService");

    // Delete test folder
    nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef,
            companyHomePathInStore
                + "/"
                + NamespaceService.CONTENT_MODEL_PREFIX
                + ":"
                + TEST_IMAP_ROOT_FOLDER_NAME,
            null,
            namespaceService,
            false);
    if (nodeRefs.size() == 1) {
      NodeRef ch = nodeRefs.get(0);
      nodeService.deleteNode(ch);
    }

    // Creating IMAP test folder for IMAP root
    LinkedList<String> folders = new LinkedList<String>();
    folders.add(TEST_IMAP_ROOT_FOLDER_NAME);
    FileFolderServiceImpl.makeFolders(
        fileFolderService, companyHomeNodeRef, folders, ContentModel.TYPE_FOLDER);

    // Setting IMAP root
    RepositoryFolderConfigBean imapHome = new RepositoryFolderConfigBean();
    imapHome.setStore(storePath);
    imapHome.setRootPath(companyHomePathInStore);
    imapHome.setFolderPath(TEST_IMAP_ROOT_FOLDER_NAME);
    imapServiceImpl.setImapHome(imapHome);

    // Starting IMAP
    imapServiceImpl.startupInTxn(true);

    nodeRefs =
        searchService.selectNodes(
            storeRootNodeRef,
            companyHomePathInStore
                + "/"
                + NamespaceService.CONTENT_MODEL_PREFIX
                + ":"
                + TEST_IMAP_ROOT_FOLDER_NAME,
            null,
            namespaceService,
            false);

    // Used to create User's folder
    NodeRef userFolderRef = imapService.getUserImapHomeRef(anotherUserName);
    permissionService.setPermission(
        userFolderRef, anotherUserName, PermissionService.ALL_PERMISSIONS, true);

    importTestData("imap/load_test_data.acp", userFolderRef);

    reauthenticate(anotherUserName, anotherUserName);

    AlfrescoImapFolder testDataFolder =
        imapService.getOrCreateMailbox(user, TEST_DATA_FOLDER_NAME, true, false);

    SimpleStoredMessage m = testDataFolder.getMessages().get(0);
    m = testDataFolder.getMessage(m.getUid());

    AlfrescoImapFolder folder = imapService.getOrCreateMailbox(user, TEST_FOLDER_NAME, false, true);

    logger.info("Creating folders...");
    long t = System.currentTimeMillis();

    try {
      for (int i = 0; i < MESSAGE_QUANTITY; i++) {
        System.out.println("i = " + i);
        folder.appendMessage(m.getMimeMessage(), new Flags(), new Date());
      }
    } catch (Exception e) {
      logger.error(e, e);
    }

    t = System.currentTimeMillis() - t;
    logger.info("Create time: " + t + " ms (" + t / 1000 + " s (" + t / 60000 + " min))");

    txn.commit();
  }
  /** On setup in transaction implementation */
  @Override
  protected void onSetUpInTransaction() throws Exception {
    // Set the services
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.cociService =
        (CheckOutCheckInService) this.applicationContext.getBean("checkOutCheckInService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.versionService = (VersionService) this.applicationContext.getBean("versionService");
    this.authenticationService =
        (MutableAuthenticationService) this.applicationContext.getBean("authenticationService");
    this.lockService = (LockService) this.applicationContext.getBean("lockService");
    this.transactionService =
        (TransactionService) this.applicationContext.getBean("transactionComponent");
    this.permissionService =
        (PermissionService) this.applicationContext.getBean("permissionService");
    this.copyService = (CopyService) this.applicationContext.getBean("copyService");

    // Authenticate as system to create initial test data set
    AuthenticationComponent authenticationComponent =
        (AuthenticationComponent) this.applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();

    // Create the store and get the root node reference
    this.storeRef =
        nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
    this.rootNodeRef = nodeService.getRootNode(storeRef);

    // Create the node used for tests
    ChildAssociationRef childAssocRef =
        nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("test"),
            ContentModel.TYPE_CONTENT);
    this.nodeRef = childAssocRef.getChildRef();
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_TITLED, null);
    nodeService.setProperty(this.nodeRef, ContentModel.PROP_NAME, TEST_VALUE_NAME);
    nodeService.setProperty(this.nodeRef, PROP2_QNAME, TEST_VALUE_2);

    // Add the initial content to the node
    ContentWriter contentWriter =
        this.contentService.getWriter(this.nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);

    // Add the lock and version aspects to the created node
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    nodeService.addAspect(this.nodeRef, ContentModel.ASPECT_LOCKABLE, null);

    // Create and authenticate the user
    this.userName = "******" + GUID.generate();
    TestWithUserUtils.createUser(
        this.userName, PWD, this.rootNodeRef, this.nodeService, this.authenticationService);
    TestWithUserUtils.authenticateUser(
        this.userName, PWD, this.rootNodeRef, this.authenticationService);
    this.userNodeRef = TestWithUserUtils.getCurrentUser(this.authenticationService);

    permissionService.setPermission(
        this.rootNodeRef, this.userName, PermissionService.ALL_PERMISSIONS, true);
    permissionService.setPermission(
        this.nodeRef, this.userName, PermissionService.ALL_PERMISSIONS, true);

    folderNodeRef =
        nodeService
            .createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName("test"),
                ContentModel.TYPE_FOLDER,
                Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "folder"))
            .getChildRef();
    fileNodeRef =
        nodeService
            .createNode(
                folderNodeRef,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName("test"),
                ContentModel.TYPE_CONTENT,
                Collections.<QName, Serializable>singletonMap(ContentModel.PROP_NAME, "file"))
            .getChildRef();
    contentWriter = this.contentService.getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(CONTENT_1);
  }
  /** Dedicated permissions and paging tests */
  @Test
  public void testListingPermissionsAndPaging() throws Exception {
    PagingResults<String> systems = null;
    PagingResults<? extends BaseCredentialsInfo> creds = null;

    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    // Initially both should be empty empty
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(
        "No systems should be found, got " + systems.getPage(), 0, systems.getPage().size());
    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(
        "No systems should be found, got " + systems.getPage(), 0, systems.getPage().size());

    // Create some credentials as the first user, for systems One and Two
    PasswordCredentialsInfoImpl pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_ONE);
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, pwCred);

    pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, pwCred);

    pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_TWO, pwCred);

    pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
    REMOTE_CREDENTIALS_SERVICE.createPersonCredentials(TEST_REMOTE_SYSTEM_TWO, pwCred);

    // Switch to the second user, create some credentials on Two and Three
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);

    pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_TWO, pwCred);

    pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_THREE);
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_THREE, pwCred);

    pwCred = new PasswordCredentialsInfoImpl();
    pwCred.setRemoteUsername(TEST_REMOTE_USERNAME_THREE);
    REMOTE_CREDENTIALS_SERVICE.createPersonCredentials(TEST_REMOTE_SYSTEM_THREE, pwCred);

    // Check the listings of remote systems for each user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());
    assertEquals(TEST_REMOTE_SYSTEM_TWO, systems.getPage().get(0));

    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());
    assertEquals(TEST_REMOTE_SYSTEM_THREE, systems.getPage().get(0));

    // Check the listings of remote systems that are shared - shouldn't matter which user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(3, systems.getPage().size());

    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(3, systems.getPage().size());

    // Check the listings of the credentials by user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listPersonCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(0, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listPersonCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());
    assertEquals(TEST_REMOTE_SYSTEM_TWO, creds.getPage().get(0).getRemoteSystemName());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listPersonCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(0, creds.getPage().size());

    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listPersonCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(0, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listPersonCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(0, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listPersonCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());
    assertEquals(TEST_REMOTE_SYSTEM_THREE, creds.getPage().get(0).getRemoteSystemName());

    // Check the shared listing of credentials, same for both users
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());

    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());

    // Check the paging of remote systems
    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(3, systems.getPage().size());
    assertEquals(false, systems.hasMoreItems());
    assertEquals(3, systems.getTotalResultCount().getFirst().intValue());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(1));
    assertEquals(1, systems.getPage().size());
    assertEquals(true, systems.hasMoreItems());
    assertEquals(3, systems.getTotalResultCount().getFirst().intValue());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(1, 2));
    assertEquals(2, systems.getPage().size());
    assertEquals(false, systems.hasMoreItems());
    assertEquals(3, systems.getTotalResultCount().getFirst().intValue());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(2, 2));
    assertEquals(1, systems.getPage().size());
    assertEquals(false, systems.hasMoreItems());
    assertEquals(3, systems.getTotalResultCount().getFirst().intValue());

    // Check the paging of credentials
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    assertEquals(false, creds.hasMoreItems());
    assertEquals(2, creds.getTotalResultCount().getFirst().intValue());

    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(1));
    assertEquals(1, creds.getPage().size());
    assertEquals(true, creds.hasMoreItems());
    assertEquals(2, creds.getTotalResultCount().getFirst().intValue());

    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(1, 1));
    assertEquals(1, creds.getPage().size());
    assertEquals(false, creds.hasMoreItems());
    assertEquals(2, creds.getTotalResultCount().getFirst().intValue());

    // Tweak shared permissions
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());

    // Systems One and Two were created by users one
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(1));
    NodeRef sharedS1 = creds.getPage().get(0).getRemoteSystemContainerNodeRef();
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(1));
    NodeRef sharedS2 = creds.getPage().get(0).getRemoteSystemContainerNodeRef();

    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    PERMISSION_SERVICE.setInheritParentPermissions(sharedS1, false);
    PERMISSION_SERVICE.setInheritParentPermissions(sharedS2, false);

    // Should then only be able to see Three, the one they created
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(0, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(0, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());

    // User One won't be able to see User Two's shared credentials under S2 under the new
    // permissions
    // They can still see their own credentials for S1 and S2, plus all in S3 (permissions
    // unchanged)
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_ONE, null, new PagingRequest(10));
    assertEquals(2, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_TWO, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());
    creds =
        REMOTE_CREDENTIALS_SERVICE.listSharedCredentials(
            TEST_REMOTE_SYSTEM_THREE, null, new PagingRequest(10));
    assertEquals(1, creds.getPage().size());
  }
  /** Test for MNT-11725 */
  public void testDowngradePermissions() throws Exception {
    NodeRef rootNodeRef = this.nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    NodeRef folderRef =
        nodeService
            .createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName(NamespaceService.ALFRESCO_URI, "testFolder"),
                ContentModel.TYPE_FOLDER)
            .getChildRef();
    permissionService.setPermission(folderRef, USER_ONE, PermissionService.COORDINATOR, true);
    permissionService.setInheritParentPermissions(folderRef, false);

    authenticationComponent.setCurrentUser(USER_ONE);

    // JSON fromat
    //  {"permissions":
    //  [{"authority":"userA",
    //  "role":"Consumer"},
    //  {"authority":"userA",
    //  "role":"Coordinator",
    //  "remove":true}],
    //  "isInherited":true}

    /*  negative test, we are first deleting the coordinator role and then try to add consumer */
    JSONObject changePermission = new JSONObject();
    JSONArray permissions = new JSONArray();
    // First delete permission, then add
    JSONObject addPermission = new JSONObject();
    addPermission.put("authority", USER_ONE);
    addPermission.put("role", PermissionService.CONSUMER);
    JSONObject removePermission = new JSONObject();
    removePermission.put("authority", USER_ONE);
    removePermission.put("role", PermissionService.COORDINATOR);
    removePermission.put("remove", "true");
    permissions.put(removePermission);
    permissions.put(addPermission);
    changePermission.put("permissions", permissions);
    changePermission.put("isInherited", "true");

    sendRequest(
        new PostRequest(
            URL_DOCLIB_PERMISSIONS
                + "/"
                + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getProtocol()
                + "/"
                + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier()
                + "/"
                + folderRef.getId(),
            changePermission.toString(),
            "application/json"),
        Status.STATUS_INTERNAL_SERVER_ERROR);

    /*  positive test  */
    changePermission = new JSONObject();
    permissions = new JSONArray();
    // First add permission, then delete
    addPermission = new JSONObject();
    addPermission.put("authority", USER_ONE);
    addPermission.put("role", PermissionService.CONSUMER);
    removePermission = new JSONObject();
    removePermission.put("authority", USER_ONE);
    removePermission.put("role", PermissionService.COORDINATOR);
    removePermission.put("remove", "true");
    permissions.put(addPermission);
    permissions.put(removePermission);
    changePermission.put("permissions", permissions);
    changePermission.put("isInherited", "true");

    sendRequest(
        new PostRequest(
            URL_DOCLIB_PERMISSIONS
                + "/"
                + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getProtocol()
                + "/"
                + StoreRef.STORE_REF_WORKSPACE_SPACESSTORE.getIdentifier()
                + "/"
                + folderRef.getId(),
            changePermission.toString(),
            "application/json"),
        Status.STATUS_OK);

    AccessStatus accessStatus =
        permissionService.hasPermission(folderRef, PermissionService.CONSUMER);
    assertTrue("The permission was not set correctly", accessStatus == AccessStatus.ALLOWED);

    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    nodeService.deleteNode(folderRef);
  }
  public ResultSet executeQuery(final SearchParameters searchParameters, String language) {
    if (repositoryState.isBootstrapping()) {
      throw new AlfrescoRuntimeException(
          "SOLR queries can not be executed while the repository is bootstrapping");
    }

    try {
      StoreRef store = extractStoreRef(searchParameters);
      SolrStoreMappingWrapper mapping = extractMapping(store);
      Locale locale = extractLocale(searchParameters);

      URLCodec encoder = new URLCodec();
      StringBuilder url = new StringBuilder();

      Pair<HttpClient, String> httpClientAndBaseUrl = mapping.getHttpClientAndBaseUrl();
      HttpClient httpClient = httpClientAndBaseUrl.getFirst();

      url.append(httpClientAndBaseUrl.getSecond());

      String languageUrlFragment = extractLanguageFragment(language);
      url.append("/").append(languageUrlFragment);

      // Send the query in JSON only
      // url.append("?q=");
      // url.append(encoder.encode(searchParameters.getQuery(), "UTF-8"));
      url.append("?wt=").append(encoder.encode("json", "UTF-8"));
      url.append("&fl=").append(encoder.encode("DBID,score", "UTF-8"));

      if ((searchParameters.getStores().size() > 1) || (mapping.isSharded())) {
        boolean requiresSeparator = false;
        url.append("&shards=");
        for (StoreRef storeRef : searchParameters.getStores()) {
          SolrStoreMappingWrapper storeMapping = extractMapping(storeRef);

          if (requiresSeparator) {
            url.append(',');
          } else {
            requiresSeparator = true;
          }

          url.append(storeMapping.getShards());
        }
      }

      // Emulate old limiting behaviour and metadata
      final LimitBy limitBy;
      int maxResults = -1;
      if (searchParameters.getMaxItems() >= 0) {
        maxResults = searchParameters.getMaxItems();
        limitBy = LimitBy.FINAL_SIZE;
      } else if (searchParameters.getLimitBy() == LimitBy.FINAL_SIZE
          && searchParameters.getLimit() >= 0) {
        maxResults = searchParameters.getLimit();
        limitBy = LimitBy.FINAL_SIZE;
      } else {
        maxResults = searchParameters.getMaxPermissionChecks();
        if (maxResults < 0) {
          maxResults = maximumResultsFromUnlimitedQuery;
        }
        limitBy = LimitBy.NUMBER_OF_PERMISSION_EVALUATIONS;
      }
      url.append("&rows=").append(String.valueOf(maxResults));

      url.append("&df=").append(encoder.encode(searchParameters.getDefaultFieldName(), "UTF-8"));
      url.append("&start=").append(encoder.encode("" + searchParameters.getSkipCount(), "UTF-8"));

      url.append("&locale=");
      url.append(encoder.encode(locale.toString(), "UTF-8"));
      url.append("&")
          .append(SearchParameters.ALTERNATIVE_DICTIONARY)
          .append("=")
          .append(alternativeDictionary);
      for (String paramName : searchParameters.getExtraParameters().keySet()) {
        url.append("&")
            .append(paramName)
            .append("=")
            .append(searchParameters.getExtraParameters().get(paramName));
      }
      StringBuffer sortBuffer = buildSortParameters(searchParameters, encoder);
      url.append(sortBuffer);

      if (searchParameters.getPermissionEvaluation() != PermissionEvaluationMode.NONE) {
        url.append("&fq=").append(encoder.encode("{!afts}AUTHORITY_FILTER_FROM_JSON", "UTF-8"));
      }

      if (searchParameters.getExcludeTenantFilter() == false) {
        url.append("&fq=").append(encoder.encode("{!afts}TENANT_FILTER_FROM_JSON", "UTF-8"));
      }

      if (searchParameters.getFieldFacets().size() > 0) {
        url.append("&facet=").append(encoder.encode("true", "UTF-8"));
        for (FieldFacet facet : searchParameters.getFieldFacets()) {
          url.append("&facet.field=").append(encoder.encode(facet.getField(), "UTF-8"));
          if (facet.getEnumMethodCacheMinDF() != 0) {
            url.append("&")
                .append(
                    encoder.encode("f." + facet.getField() + ".facet.enum.cache.minDf", "UTF-8"))
                .append("=")
                .append(encoder.encode("" + facet.getEnumMethodCacheMinDF(), "UTF-8"));
          }
          url.append("&")
              .append(encoder.encode("f." + facet.getField() + ".facet.limit", "UTF-8"))
              .append("=")
              .append(encoder.encode("" + facet.getLimit(), "UTF-8"));
          if (facet.getMethod() != null) {
            url.append("&")
                .append(encoder.encode("f." + facet.getField() + ".facet.method", "UTF-8"))
                .append("=")
                .append(
                    encoder.encode(
                        facet.getMethod() == FieldFacetMethod.ENUM ? "enum" : "fc", "UTF-8"));
          }
          if (facet.getMinCount() != 0) {
            url.append("&")
                .append(encoder.encode("f." + facet.getField() + ".facet.mincount", "UTF-8"))
                .append("=")
                .append(encoder.encode("" + facet.getMinCount(), "UTF-8"));
          }
          if (facet.getOffset() != 0) {
            url.append("&")
                .append(encoder.encode("f." + facet.getField() + ".facet.offset", "UTF-8"))
                .append("=")
                .append(encoder.encode("" + facet.getOffset(), "UTF-8"));
          }
          if (facet.getPrefix() != null) {
            url.append("&")
                .append(encoder.encode("f." + facet.getField() + ".facet.prefix", "UTF-8"))
                .append("=")
                .append(encoder.encode("" + facet.getPrefix(), "UTF-8"));
          }
          if (facet.getSort() != null) {
            url.append("&")
                .append(encoder.encode("f." + facet.getField() + ".facet.sort", "UTF-8"))
                .append("=")
                .append(
                    encoder.encode(
                        facet.getSort() == FieldFacetSort.COUNT ? "count" : "index", "UTF-8"));
          }
        }
        for (String facetQuery : searchParameters.getFacetQueries()) {
          url.append("&facet.query=").append(encoder.encode("{!afts}" + facetQuery, "UTF-8"));
        }
      }
      // end of field facets

      final String searchTerm = searchParameters.getSearchTerm();
      String spellCheckQueryStr = null;
      if (searchTerm != null && searchParameters.isSpellCheck()) {
        StringBuilder builder = new StringBuilder();
        builder.append("&spellcheck.q=").append(encoder.encode(searchTerm, "UTF-8"));
        builder.append("&spellcheck=").append(encoder.encode("true", "UTF-8"));
        spellCheckQueryStr = builder.toString();
        url.append(spellCheckQueryStr);
      }

      JSONObject body = new JSONObject();
      body.put("query", searchParameters.getQuery());

      // Authorities go over as is - and tenant mangling and query building takes place on the SOLR
      // side

      Set<String> allAuthorisations = permissionService.getAuthorisations();
      boolean includeGroups =
          includeGroupsForRoleAdmin
              ? true
              : !allAuthorisations.contains(PermissionService.ADMINISTRATOR_AUTHORITY);

      JSONArray authorities = new JSONArray();
      for (String authority : allAuthorisations) {
        if (includeGroups) {
          authorities.put(authority);
        } else {
          if (AuthorityType.getAuthorityType(authority) != AuthorityType.GROUP) {
            authorities.put(authority);
          }
        }
      }
      body.put("authorities", authorities);
      body.put("anyDenyDenies", anyDenyDenies);

      JSONArray tenants = new JSONArray();
      tenants.put(tenantService.getCurrentUserDomain());
      body.put("tenants", tenants);

      JSONArray locales = new JSONArray();
      for (Locale currentLocale : searchParameters.getLocales()) {
        locales.put(DefaultTypeConverter.INSTANCE.convert(String.class, currentLocale));
      }
      if (locales.length() == 0) {
        locales.put(I18NUtil.getLocale());
      }
      body.put("locales", locales);

      JSONArray templates = new JSONArray();
      for (String templateName : searchParameters.getQueryTemplates().keySet()) {
        JSONObject template = new JSONObject();
        template.put("name", templateName);
        template.put("template", searchParameters.getQueryTemplates().get(templateName));
        templates.put(template);
      }
      body.put("templates", templates);

      JSONArray allAttributes = new JSONArray();
      for (String attribute : searchParameters.getAllAttributes()) {
        allAttributes.put(attribute);
      }
      body.put("allAttributes", allAttributes);

      body.put("defaultFTSOperator", searchParameters.getDefaultFTSOperator());
      body.put("defaultFTSFieldOperator", searchParameters.getDefaultFTSFieldOperator());
      body.put("queryConsistency", searchParameters.getQueryConsistency());
      if (searchParameters.getMlAnalaysisMode() != null) {
        body.put("mlAnalaysisMode", searchParameters.getMlAnalaysisMode().toString());
      }
      body.put("defaultNamespace", searchParameters.getNamespace());

      JSONArray textAttributes = new JSONArray();
      for (String attribute : searchParameters.getTextAttributes()) {
        textAttributes.put(attribute);
      }
      body.put("textAttributes", textAttributes);

      final int maximumResults = maxResults; // just needed for the final parameter

      return (ResultSet)
          postSolrQuery(
              httpClient,
              url.toString(),
              body,
              new SolrJsonProcessor<SolrJSONResultSet>() {

                @Override
                public SolrJSONResultSet getResult(JSONObject json) {
                  return new SolrJSONResultSet(
                      json, searchParameters, nodeService, nodeDAO, limitBy, maximumResults);
                }
              },
              spellCheckQueryStr);
    } catch (UnsupportedEncodingException e) {
      throw new LuceneQueryParserException("", e);
    } catch (HttpException e) {
      throw new LuceneQueryParserException("", e);
    } catch (IOException e) {
      throw new LuceneQueryParserException("", e);
    } catch (JSONException e) {
      throw new LuceneQueryParserException("", e);
    }
  }
  @Override
  public PagingResults<PersonFavourite> getPagedFavourites(
      String userName,
      Set<Type> types,
      List<Pair<FavouritesService.SortFields, Boolean>> sortProps,
      PagingRequest pagingRequest) {
    // Get the user node reference
    final NodeRef personNodeRef = personService.getPerson(userName);
    if (personNodeRef == null) {
      throw new AlfrescoRuntimeException(
          "Can not get preferences for " + userName + " because he/she does not exist.");
    }

    boolean includeFiles = types.contains(Type.FILE);
    boolean includeFolders = types.contains(Type.FOLDER);
    boolean includeSites = types.contains(Type.SITE);

    String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
    if (authenticationContext.isSystemUserName(currentUserName) == true
        || permissionService.hasPermission(personNodeRef, PermissionService.WRITE)
            == AccessStatus.ALLOWED
        || userName.equals(currentUserName) == true) {
      // we may have more than one favourite that is considered the same w.r.t. the PersonFavourite
      // comparator
      final Map<PersonFavouriteKey, PersonFavourite> sortedFavouriteNodes =
          new TreeMap<PersonFavouriteKey, PersonFavourite>(getComparator(sortProps));

      PrefKeys sitePrefKeys = getPrefKeys(Type.SITE);
      PrefKeys documentsPrefKeys = getPrefKeys(Type.FILE);
      PrefKeys foldersPrefKeys = getPrefKeys(Type.FOLDER);

      Map<String, Serializable> preferences = preferenceService.getPreferences(userName);
      for (String key : preferences.keySet()) {
        if (includeFiles && key.startsWith(documentsPrefKeys.sharePrefKey)) {
          String nodes = (String) preferences.get(key);
          if (nodes != null) {
            sortedFavouriteNodes.putAll(extractFavouriteNodes(userName, Type.FILE, nodes));
          }
        } else if (includeFolders && key.startsWith(foldersPrefKeys.sharePrefKey)) {
          String nodes = (String) preferences.get(key);
          if (nodes != null) {
            sortedFavouriteNodes.putAll(extractFavouriteNodes(userName, Type.FOLDER, nodes));
          }
        } else if (includeSites
            && key.startsWith(sitePrefKeys.getSharePrefKey())
            && !key.endsWith(".createdAt")) {
          // key is either of the form org.alfresco.share.sites.favourites.<siteId>.favourited or
          // org.alfresco.share.sites.favourites.<siteId>
          extractFavouriteSite(userName, Type.SITE, sortedFavouriteNodes, preferences, key);
        }
      }

      int totalSize = sortedFavouriteNodes.size();
      final PageDetails pageDetails = PageDetails.getPageDetails(pagingRequest, totalSize);

      final List<PersonFavourite> page = new ArrayList<PersonFavourite>(pageDetails.getPageSize());
      Iterator<PersonFavourite> it = sortedFavouriteNodes.values().iterator();
      for (int counter = 0; counter < pageDetails.getEnd() && it.hasNext(); counter++) {
        PersonFavourite favouriteNode = it.next();

        if (counter < pageDetails.getSkipCount()) {
          continue;
        }

        if (counter > pageDetails.getEnd() - 1) {
          break;
        }

        page.add(favouriteNode);
      }

      return new PagingResults<PersonFavourite>() {
        @Override
        public List<PersonFavourite> getPage() {
          return page;
        }

        @Override
        public boolean hasMoreItems() {
          return pageDetails.hasMoreItems();
        }

        @Override
        public Pair<Integer, Integer> getTotalResultCount() {
          Integer total = Integer.valueOf(sortedFavouriteNodes.size());
          return new Pair<Integer, Integer>(total, total);
        }

        @Override
        public String getQueryExecutionId() {
          return null;
        }
      };
    } else {
      // The current user does not have sufficient permissions to update the preferences for this
      // user
      throw new AccessDeniedException(
          "The current user "
              + currentUserName
              + " does not have sufficient permissions to get the favourites of the user "
              + userName);
    }
  }
예제 #20
0
  /**
   * Helper method to extract file info from a specific node.
   *
   * <p>This method goes direct to the repo for all information and no data is cached here.
   *
   * @param nodeRef the node
   * @param readOnly, should the file be shown as "read only", regardless of its permissions?
   * @param lockedFilesAsOffline should a locked file be marked as offline
   * @return Returns the file information pertinent to the node
   * @throws FileNotFoundException if the path refers to a non-existent file
   */
  private ContentFileInfo getFileInformationImpl(
      NodeRef nodeRef, boolean readOnly, boolean lockedFilesAsOffline)
      throws FileNotFoundException {
    // get the file info
    org.alfresco.service.cmr.model.FileInfo fileFolderInfo = fileFolderService.getFileInfo(nodeRef);

    // retrieve required properties and create new JLAN file info
    ContentFileInfo fileInfo = new ContentFileInfo(nodeRef);

    // Set the file id from the node's DBID
    long id =
        DefaultTypeConverter.INSTANCE.convert(
            Long.class, nodeService.getProperty(nodeRef, ContentModel.PROP_NODE_DBID));
    fileInfo.setFileId((int) (id & 0xFFFFFFFFL));

    // unset all attribute flags
    int fileAttributes = 0;
    fileInfo.setFileAttributes(fileAttributes);

    if (fileFolderInfo.isFolder()) {
      // add directory attribute
      fileAttributes |= FileAttribute.Directory;
      fileInfo.setFileAttributes(fileAttributes);
      fileInfo.setFileType(FileType.Directory);
    } else {
      Map<QName, Serializable> nodeProperties = fileFolderInfo.getProperties();

      // Get the file size from the content

      ContentData contentData = (ContentData) nodeProperties.get(ContentModel.PROP_CONTENT);
      long size = 0L;
      if (contentData != null) {
        size = contentData.getSize();
      }
      fileInfo.setSize(size);

      // Set the allocation size by rounding up the size to a 512 byte block boundary

      if (size > 0) {
        fileInfo.setAllocationSize((size + 512L) & 0xFFFFFFFFFFFFFE00L);
      }

      // Check whether the file is locked

      if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE)) {
        LockType lockType = lockService.getLockType(nodeRef);

        int attr = fileInfo.getFileAttributes();

        if (lockType != null) {
          switch (lockType) {
            case NODE_LOCK:
              if ((attr & FileAttribute.ReadOnly) == 0) attr += FileAttribute.ReadOnly;
              break;
            case WRITE_LOCK:
              LockStatus lockStatus = lockService.getLockStatus(nodeRef);
              if (lockStatus == LockStatus.LOCK_OWNER) {
              } else {
                if ((attr & FileAttribute.ReadOnly) == 0) {
                  attr += FileAttribute.ReadOnly;
                }

                if (lockedFilesAsOffline) {
                  attr += FileAttribute.NTOffline;
                }
              }
              break;
            case READ_ONLY_LOCK:
              if ((attr & FileAttribute.ReadOnly) == 0) {
                attr += FileAttribute.ReadOnly;
              }

              if (lockedFilesAsOffline) {
                attr += FileAttribute.NTOffline;
              }
              break;
          }

          fileInfo.setFileAttributes(attr);
        }
      }

      // Check if it is a link node

      if (fileFolderInfo.isLink()) {
        fileInfo.setLinkNodeRef(fileFolderInfo.getLinkNodeRef());
      }
    }

    // created
    Date createdDate = fileFolderInfo.getCreatedDate();
    if (createdDate != null) {
      long created = DefaultTypeConverter.INSTANCE.longValue(createdDate);
      fileInfo.setCreationDateTime(created);
    }
    // modified
    Date modifiedDate = fileFolderInfo.getModifiedDate();
    if (modifiedDate != null) {
      long modified = DefaultTypeConverter.INSTANCE.longValue(modifiedDate);
      fileInfo.setModifyDateTime(modified);
      fileInfo.setAccessDateTime(modified);
      fileInfo.setChangeDateTime(modified);
    }
    // name
    String name = fileFolderInfo.getName();
    if (name != null) {
      fileInfo.setFileName(name);

      // Check for file names that should be hidden
      if (hiddenAspect.getVisibility(Client.cifs, fileInfo.getNodeRef())
          == Visibility.HiddenAttribute) {
        // Add the hidden file attribute
        int attr = fileInfo.getFileAttributes();
        if ((attr & FileAttribute.Hidden) == 0) {
          attr += FileAttribute.Hidden;
          fileInfo.setFileAttributes(attr);
        }
      }
    }

    // Read/write access

    if (!fileFolderInfo.isFolder() || isReadOnlyFlagOnFolders) {
      boolean deniedPermission =
          permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED;
      if (readOnly || deniedPermission) {
        int attr = fileInfo.getFileAttributes();
        if ((attr & FileAttribute.ReadOnly) == 0) {
          attr += FileAttribute.ReadOnly;
          fileInfo.setFileAttributes(attr);
        }
      }
    }

    // Set the normal file attribute if no other attributes are set

    if (fileInfo.getFileAttributes() == 0) fileInfo.setFileAttributes(FileAttribute.NTNormal);

    // Debug

    if (logger.isDebugEnabled()) {
      logger.debug("Fetched file info: \n" + "   info: " + fileInfo);
    }

    // Return the file information

    return fileInfo;
  }
  /**
   * Creating shared and personal credentials, then checking how this affects the listing of Remote
   * Systems
   */
  @Test
  public void testCreateCredentialsAndSystemListing() throws Exception {
    PagingResults<String> systems = null;

    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    // Initially both should be empty
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(
        "No systems should be found, got " + systems.getPage(), 0, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(
        "No systems should be found, got " + systems.getPage(), 0, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(
        "No systems should be found, got " + systems.getPage(), 0, systems.getPage().size());

    // Create one for the person
    PasswordCredentialsInfoImpl credentials = new PasswordCredentialsInfoImpl();
    credentials.setRemoteUsername(TEST_REMOTE_USERNAME_ONE);
    REMOTE_CREDENTIALS_SERVICE.createPersonCredentials(TEST_REMOTE_SYSTEM_ONE, credentials);

    // Check it shows up
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals("Unexpected systems " + systems.getPage(), 1, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals("Unexpected systems " + systems.getPage(), 0, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals("Unexpected systems " + systems.getPage(), 1, systems.getPage().size());

    // Switch to another user, check it doesn't
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);

    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(0, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(0, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(0, systems.getPage().size());

    // Create both personal and shared ones as the current user
    credentials = new PasswordCredentialsInfoImpl();
    credentials.setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
    REMOTE_CREDENTIALS_SERVICE.createPersonCredentials(TEST_REMOTE_SYSTEM_TWO, credentials);

    credentials = new PasswordCredentialsInfoImpl();
    credentials.setRemoteUsername(TEST_REMOTE_USERNAME_THREE);
    REMOTE_CREDENTIALS_SERVICE.createPersonCredentials(TEST_REMOTE_SYSTEM_THREE, credentials);

    credentials = new PasswordCredentialsInfoImpl();
    credentials.setRemoteUsername(TEST_REMOTE_USERNAME_THREE);
    BaseCredentialsInfo cc =
        REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_THREE, credentials);

    // Check as the user who created these
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());

    // Check as the first user, they should see the shared one
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());

    // Change the shared permissions, see it goes away
    AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER);
    PERMISSION_SERVICE.setInheritParentPermissions(cc.getRemoteSystemContainerNodeRef(), false);

    // Check as the owning user, will still see all of them
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());

    // Check as the other user, shared will have gone as we lost read permissions
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(0, systems.getPage().size());

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());

    // Finally, check the listings have the correct things in them
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_TWO);
    systems = REMOTE_CREDENTIALS_SERVICE.listPersonRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());
    assertEquals(true, systems.getPage().contains(TEST_REMOTE_SYSTEM_TWO));
    assertEquals(true, systems.getPage().contains(TEST_REMOTE_SYSTEM_THREE));

    systems = REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));
    assertEquals(1, systems.getPage().size());
    assertEquals(true, systems.getPage().contains(TEST_REMOTE_SYSTEM_THREE));

    systems = REMOTE_CREDENTIALS_SERVICE.listAllRemoteSystems(new PagingRequest(10));
    assertEquals(2, systems.getPage().size());
    assertEquals(true, systems.getPage().contains(TEST_REMOTE_SYSTEM_TWO));
    assertEquals(true, systems.getPage().contains(TEST_REMOTE_SYSTEM_THREE));
  }