/**
   * Tests that read only methods don't create the shared credentials container, but that write ones
   * will do.
   */
  @Test
  public void testSharedCredentialsContainer() throws Exception {
    // Run as a test user
    AuthenticationUtil.setFullyAuthenticatedUser(TEST_USER_ONE);

    // To start with, the container shouldn't be there
    NodeRef container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    if (container != null) {
      // Tidy up
      AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

      // Zap the container
      PUBLIC_NODE_SERVICE.deleteNode(container);
    }

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

    // Ask for the list of shared remote systems
    REMOTE_CREDENTIALS_SERVICE.listSharedRemoteSystems(new PagingRequest(10));

    // Won't have been created by a read
    container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    assertEquals(null, container);

    // Try to store some credentials
    PasswordCredentialsInfo credentials = new PasswordCredentialsInfoImpl();
    REMOTE_CREDENTIALS_SERVICE.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, credentials);

    // It will now exist
    container =
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getSharedContainerNodeRef(false);
    assertNotNull(container);

    // Should have a marker aspect, and the specified name
    Set<QName> cAspects = PUBLIC_NODE_SERVICE.getAspects(container);
    assertEquals(
        "Aspect missing, found " + cAspects,
        true,
        cAspects.contains(RemoteCredentialsModel.ASPECT_REMOTE_CREDENTIALS_SYSTEM_CONTAINER));
    assertEquals(
        SHARED_SYSTEM_CONTAINER_NAME,
        PUBLIC_NODE_SERVICE.getProperty(container, ContentModel.PROP_NAME));

    // Should have single node in it
    assertEquals(1, PUBLIC_NODE_SERVICE.getChildAssocs(container).size());

    // Tidy up
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

    // Zap the container
    PUBLIC_NODE_SERVICE.deleteNode(container);
  }
  /**
   * Most of the shared credentials container tests work on the test one, so that things are in a
   * known and empty state. We have this one test that uses the real shared container, just to check
   * that it's correctly setup and available
   */
  @Test
  public void testRealSharedCredentialsContainer() throws Exception {
    // Create a new instance, using the real container
    RemoteCredentialsServiceImpl realService = new RemoteCredentialsServiceImpl();
    realService.setDictionaryService(DICTIONARY_SERVICE);
    realService.setNamespaceService(NAMESPACE_SERVICE);
    realService.setNodeService(PUBLIC_NODE_SERVICE);
    realService.setRepositoryHelper(REPOSITORY_HELPER);

    for (Entry<QName, RemoteCredentialsInfoFactory> e :
        ((RemoteCredentialsServiceImpl) PRIVATE_REMOTE_CREDENTIALS_SERVICE)
            .getCredentialsFactories()
            .entrySet()) {
      realService.registerCredentialsFactory(e.getKey(), e.getValue());
    }

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

    // Do a create / fetch / delete step
    PasswordCredentialsInfoImpl pwCredI = new PasswordCredentialsInfoImpl();
    pwCredI.setRemoteUsername(TEST_REMOTE_USERNAME_ONE);
    pwCredI.setRemotePassword(TEST_USER_THREE);
    BaseCredentialsInfo credentials = null;

    try {
      // Create
      credentials = realService.createSharedCredentials(TEST_REMOTE_SYSTEM_ONE, pwCredI);
      assertEquals(TEST_REMOTE_USERNAME_ONE, credentials.getRemoteUsername());

      // Update
      ((PasswordCredentialsInfoImpl) credentials).setRemoteUsername(TEST_REMOTE_USERNAME_TWO);
      ((PasswordCredentialsInfoImpl) credentials).setRemotePassword(TEST_USER_ONE);
      credentials = realService.updateCredentials(credentials);
      assertEquals(TEST_REMOTE_USERNAME_TWO, credentials.getRemoteUsername());

      // Delete
      realService.deleteCredentials(credentials);

      // Tidy, and zap the test parent
      PUBLIC_NODE_SERVICE.deleteNode(credentials.getRemoteSystemContainerNodeRef());
      credentials = null;
    } finally {
      // Tidy up if needed
      if (credentials != null) {
        AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();

        // Zap the credentials themselves
        PUBLIC_NODE_SERVICE.deleteNode(credentials.getNodeRef());

        // And their test parent
        PUBLIC_NODE_SERVICE.deleteNode(credentials.getRemoteSystemContainerNodeRef());
      }
    }
  }
  /**
   * Removes unwanted aspects
   *
   * @param nodeService
   * @param nodeRef
   */
  protected void cleanDisposableItem(NodeService nodeService, NodeRef nodeRef) {
    // Remove unwanted aspects
    for (QName aspect : unwantedAspects) {
      if (nodeService.hasAspect(nodeRef, aspect)) {
        nodeService.removeAspect(nodeRef, aspect);
      }
    }

    // remove the current disposition action (if there is one)
    DispositionAction dispositionAction = dispositionService.getNextDispositionAction(nodeRef);
    if (dispositionAction != null) {
      nodeService.deleteNode(dispositionAction.getNodeRef());
    }
  }
  /** Test the deleting a wokring copy node removed the lock on the original node */
  public void testAutoCancelCheckOut() {
    NodeRef workingCopy = checkout();
    assertNotNull(workingCopy);

    try {
      this.lockService.checkForLock(this.nodeRef);
      fail("The original should be locked now.");
    } catch (Throwable exception) {
      // Good the original is locked
    }

    // Delete the working copy
    nodeService.deleteNode(workingCopy);

    // The original should no longer be locked
    this.lockService.checkForLock(this.nodeRef);
  }
  @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();
  }
  /** 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);
  }
  /**
   * Delete the download node identified by nodeRef
   *
   * @param nodeRef
   */
  public void delete(NodeRef nodeRef) {
    validateNode(nodeRef);

    nodeService.deleteNode(nodeRef);
  }