Example #1
0
  @Override
  protected void tearDown() throws Exception {
    super.tearDown();

    // admin user required to delete user
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());

    SiteInfo siteInfo = this.siteService.getSite(SITE_SHORT_NAME_WIKI);
    if (siteInfo != null) {
      // delete the site
      siteService.deleteSite(SITE_SHORT_NAME_WIKI);
      nodeArchiveService.purgeArchivedNode(
          nodeArchiveService.getArchivedNode(siteInfo.getNodeRef()));
    }

    // delete the users
    if (personService.personExists(USER_ONE)) {
      personService.deletePerson(USER_ONE);
    }
    if (this.authenticationService.authenticationExists(USER_ONE)) {
      this.authenticationService.deleteAuthentication(USER_ONE);
    }

    if (personService.personExists(USER_TWO)) {
      personService.deletePerson(USER_TWO);
    }
    if (this.authenticationService.authenticationExists(USER_TWO)) {
      this.authenticationService.deleteAuthentication(USER_TWO);
    }
  }
  @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);
  }
 /**
  * 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 {
    // get all users in the system
    List<PersonInfo> personInfos =
        _personService
            .getPeople(null, null, null, new PagingRequest(Integer.MAX_VALUE, null))
            .getPage();

    Set<NodeRef> people = new HashSet<NodeRef>(personInfos.size());

    for (PersonInfo personInfo : personInfos) {
      people.add(personInfo.getNodeRef());
    }

    int count = 0;

    // iterate through all the users
    for (final NodeRef person : people) {
      // get the username from the node
      final Serializable username = nodeService.getProperty(person, ContentModel.PROP_USERNAME);

      // if no username, continue
      if (username == null) {
        continue;
      }

      // if it's the guest or admin, skip as well
      if (username.toString().equals("guest") || username.toString().equals("admin")) {
        continue;
      }

      // list all sites that the user is excplicit member in
      final List<SiteInfo> sites = _siteService.listSites(username.toString());

      // the user is member of 1 site or more, continue
      if (sites.size() > 0) {
        continue;
      }

      // if this point is reached, the user is not a member of any site, so it
      // should be deleted
      LOG.error("Deleting user '" + username + "', user is not a member of any site");

      _personService.deletePerson(username.toString());

      count++;
    }

    LOG.error(
        "Deleted " + count + " of " + people.size() + " users that wasn't a member in any sites.");

    return I18NUtil.getMessage(MSG_SUCCESS);
  }
  /**
   * @param ref The node representing the current document ref
   * @return Model map for email templates
   */
  @SuppressWarnings("unchecked")
  private Map<String, Object> createEmailTemplateModel(NodeRef ref, Action ruleAction) {
    Map<String, Object> model = new HashMap<String, Object>();

    NodeRef person = personService.getPerson(authService.getCurrentUserName());
    model.put("person", new TemplateNode(person, serviceRegistry, null));
    model.put("document", new TemplateNode(ref, serviceRegistry, null));
    NodeRef parent = serviceRegistry.getNodeService().getPrimaryParent(ref).getParentRef();
    model.put("space", new TemplateNode(parent, serviceRegistry, null));

    // current date/time is useful to have and isn't supplied by FreeMarker
    // by default
    model.put("date", new Date());

    // add custom method objects
    model.put("hasAspect", new HasAspectMethod());
    model.put("message", new I18NMessageMethod());
    model.put("dateCompare", new DateCompareMethod());
    model.put("url", new URLHelper(repoRemoteUrl));

    Map<String, Object> additionalParams =
        (Map<String, Object>) ruleAction.getParameterValue(PARAM_ADDITIONAL_INFO);

    if (additionalParams != null) {
      model.putAll(additionalParams);
    }

    return model;
  }
Example #6
0
 /**
  * Sends an invitation email.
  *
  * @param properties A Map containing the properties needed to send the email.
  */
 public void sendMail(Map<String, String> properties) {
   checkProperties(properties);
   ParameterCheck.mandatory("Properties", properties);
   NodeRef inviter = personService.getPerson(properties.get(wfVarInviterUserName));
   String inviteeName = properties.get(wfVarInviteeUserName);
   NodeRef invitee = personService.getPerson(inviteeName);
   Action mail = actionService.createAction(MailActionExecuter.NAME);
   mail.setParameterValue(MailActionExecuter.PARAM_FROM, getEmail(inviter));
   mail.setParameterValue(MailActionExecuter.PARAM_TO, getEmail(invitee));
   mail.setParameterValue(MailActionExecuter.PARAM_SUBJECT, buildSubject(properties));
   mail.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, getEmailTemplateNodeRef());
   mail.setParameterValue(
       MailActionExecuter.PARAM_TEMPLATE_MODEL,
       (Serializable) buildMailTextModel(properties, inviter, invitee));
   mail.setParameterValue(MailActionExecuter.PARAM_IGNORE_SEND_FAILURE, true);
   actionService.executeAction(mail, getWorkflowPackage(properties));
 }
Example #7
0
  private NodeRef createPerson(String userName) {
    // if user with given user name doesn't already exist then create user
    if (this.authenticationService.authenticationExists(userName) == false) {
      // create user
      this.authenticationService.createAuthentication(userName, "password".toCharArray());
    }

    // if person node with given user name doesn't already exist then create
    // person
    if (this.personService.personExists(userName) == false) {
      // create person properties
      PropertyMap personProps = new PropertyMap();
      personProps.put(ContentModel.PROP_USERNAME, userName);

      // create person node for user
      return personService.createPerson(personProps);
    }
    return personService.getPerson(userName);
  }
  private JSONObject getPreferencesObject(String userName) throws JSONException {
    JSONObject jsonPrefs = null;

    // Get the user node reference
    NodeRef personNodeRef = this.personService.getPerson(userName);
    if (personNodeRef == null) {
      throw new AlfrescoRuntimeException(
          "Cannot get preferences for " + userName + " because he/she does not exist.");
    }

    String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
    boolean isSystem =
        AuthenticationUtil.isRunAsUserTheSystemUser()
            || authenticationContext.isSystemUserName(currentUserName);
    if (isSystem
        || userName.equals(currentUserName)
        || personService
            .getUserIdentifier(userName)
            .equals(personService.getUserIdentifier(currentUserName))
        || authorityService.isAdminAuthority(currentUserName)) {
      // Check for preferences aspect
      if (this.nodeService.hasAspect(personNodeRef, ContentModel.ASPECT_PREFERENCES) == true) {
        // Get the preferences for this user
        ContentReader reader =
            this.contentService.getReader(personNodeRef, ContentModel.PROP_PREFERENCE_VALUES);
        if (reader != null) {
          jsonPrefs = new JSONObject(reader.getContentString());
        }
      }
    } else {
      // The current user does not have sufficient permissions to get
      // the preferences for this user
      throw new AccessDeniedException(
          "The current user "
              + currentUserName
              + " does not have sufficient permissions to get the preferences of the user "
              + userName);
    }

    return jsonPrefs;
  }
  /**
   * Send an email message
   *
   * @throws AlfrescoRuntimeExeption
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void executeImpl(final Action ruleAction, final NodeRef actionedUponNodeRef) {
    try {
      MimeMessage message = javaMailSender.createMimeMessage();
      // use the true flag to indicate you need a multipart message
      MimeMessageHelper helper = new MimeMessageHelper(message, true);

      // set recipient
      String to = (String) ruleAction.getParameterValue(PARAM_TO);
      if (to != null && to.length() != 0) {
        helper.setTo(to);
      } else {
        // see if multiple recipients have been supplied - as a list of
        // authorities
        Serializable toManyMails = ruleAction.getParameterValue(PARAM_TO_MANY);
        List<String> recipients = new ArrayList<String>();
        if (toManyMails instanceof List) {
          for (String mailAdress : (List<String>) toManyMails) {
            if (validateAddress(mailAdress)) {
              recipients.add(mailAdress);
            }
          }
        } else if (toManyMails instanceof String) {
          if (validateAddress((String) toManyMails)) {
            recipients.add((String) toManyMails);
          }
        }
        if (recipients != null && recipients.size() > 0) {
          helper.setTo(recipients.toArray(new String[recipients.size()]));
        } else {
          // No recipients have been specified
          logger.error("No recipient has been specified for the mail action");
        }
      }

      // set subject line
      helper.setSubject((String) ruleAction.getParameterValue(PARAM_SUBJECT));

      // See if an email template has been specified
      String text = null;
      NodeRef templateRef = (NodeRef) ruleAction.getParameterValue(PARAM_TEMPLATE);
      if (templateRef != null) {
        // build the email template model
        Map<String, Object> model = createEmailTemplateModel(actionedUponNodeRef, ruleAction);

        // process the template against the model
        text = templateService.processTemplate("freemarker", templateRef.toString(), model);
      }

      // set the text body of the message
      if (text == null) {
        text = (String) ruleAction.getParameterValue(PARAM_TEXT);
      }
      // adding the boolean true to send as HTML
      helper.setText(text, true);
      FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
      /* add inline images.
       * "action.parameters.images is a ,-delimited string, containing a map of images and resources, from this example:
      message.setText("my text <img src='cid:myLogo'>", true);
      message.addInline("myLogo", new ClassPathResource("img/mylogo.gif"));
      so the "images" param can look like this: headerLogo|images/headerLogoNodeRef,footerLogo|footerLogoNodeRef
       */
      String imageList = (String) ruleAction.getParameterValue(PARAM_IMAGES);
      System.out.println(imageList);
      String[] imageMap = imageList.split(","); // comma no spaces
      Map<String, String> images = new HashMap<String, String>();
      for (String image : imageMap) {
        System.out.println(image);
        String map[] = image.split("\\|");
        for (String key : map) {
          System.out.println(key);
        }

        System.out.println(map.length);

        images.put(map[0].trim(), map[1].trim());
        System.out.println(images.size());
        System.out.println("-" + map[0] + " " + map[1] + "-");
      }
      NodeRef imagesFolderNodeRef = (NodeRef) ruleAction.getParameterValue(PARAM_IMAGES_FOLDER);
      if (null != imagesFolderNodeRef) {
        ContentService contentService = serviceRegistry.getContentService();
        System.out.println("mapping");
        for (Map.Entry<String, String> entry : images.entrySet()) {
          System.out.println(
              entry.getKey()
                  + " "
                  + entry.getValue()
                  + " "
                  + ruleAction.getParameterValue(PARAM_IMAGES_FOLDER));
          NodeRef imageFile = fileFolderService.searchSimple(imagesFolderNodeRef, entry.getValue());
          if (null != imageFile) {
            ContentReader reader = contentService.getReader(imageFile, ContentModel.PROP_CONTENT);
            ByteArrayResource resource =
                new ByteArrayResource(IOUtils.toByteArray(reader.getContentInputStream()));
            helper.addInline(entry.getKey(), resource, reader.getMimetype());

          } else {
            logger.error("No image for " + entry.getKey());
          }
        }
      } else {
        logger.error("No images folder");
      }

      // set the from address
      NodeRef person = personService.getPerson(authService.getCurrentUserName());

      String fromActualUser = null;
      if (person != null) {
        fromActualUser = (String) nodeService.getProperty(person, ContentModel.PROP_EMAIL);
      }
      if (fromActualUser != null && fromActualUser.length() != 0) {
        helper.setFrom(fromActualUser);
      } else {
        String from = (String) ruleAction.getParameterValue(PARAM_FROM);
        if (from == null || from.length() == 0) {
          helper.setFrom(fromAddress);
        } else {
          helper.setFrom(from);
        }
      }
      NodeRef attachmentsFolder = (NodeRef) ruleAction.getParameterValue(PARAM_ATTCHMENTS_FOLDER);
      if (attachmentsFolder != null) {

        List<FileInfo> attachFiles = fileFolderService.listFiles(attachmentsFolder);
        if (attachFiles != null && attachFiles.size() > 0) {
          for (FileInfo attachFile : attachFiles) {
            ContentReader contentReader = fileFolderService.getReader(attachFile.getNodeRef());
            ByteArrayResource resource =
                new ByteArrayResource(IOUtils.toByteArray(contentReader.getContentInputStream()));
            helper.addAttachment(attachFile.getName(), resource, contentReader.getMimetype());
          }
        }
      }

      // Send the message unless we are in "testMode"
      javaMailSender.send(message);
    } catch (Exception e) {
      String toUser = (String) ruleAction.getParameterValue(PARAM_TO);
      if (toUser == null) {
        Object obj = ruleAction.getParameterValue(PARAM_TO_MANY);
        if (obj != null) {
          toUser = obj.toString();
        }
      }

      logger.error("Failed to send email to " + toUser, e);

      throw new AlfrescoRuntimeException("Failed to send email to:" + toUser, e);
    }
  }
Example #10
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();
  }
  @Override
  public void setUp() throws Exception {
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();
    importerService = serviceRegistry.getImporterService();
    personService = serviceRegistry.getPersonService();
    authenticationService = serviceRegistry.getAuthenticationService();
    permissionService = serviceRegistry.getPermissionService();
    imapService = serviceRegistry.getImapService();
    searchService = serviceRegistry.getSearchService();
    namespaceService = serviceRegistry.getNamespaceService();
    fileFolderService = serviceRegistry.getFileFolderService();

    flags = new Flags();
    flags.add(Flags.Flag.SEEN);
    flags.add(Flags.Flag.FLAGGED);
    flags.add(Flags.Flag.ANSWERED);
    flags.add(Flags.Flag.DELETED);

    // start the transaction
    txn = transactionService.getUserTransaction();
    txn.begin();
    authenticationService.authenticate(USER_NAME, USER_PASSWORD.toCharArray());

    // downgrade integrity
    IntegrityChecker.setWarnInTransaction();

    anotherUserName = "******" + System.currentTimeMillis();

    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);

    // create the ACEGI Authentication instance for the new user
    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");

    // Creating IMAP test folder for IMAP root
    LinkedList<String> folders = new LinkedList<String>();
    folders.add(TEST_IMAP_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_FOLDER_NAME);
    imapServiceImpl.setImapHome(imapHome);

    // Starting IMAP
    imapServiceImpl.startup();

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

    /*
     * Importing test folders:
     *
     * Test folder contains: "___-___folder_a"
     *
     * "___-___folder_a" contains: "___-___folder_a_a",
     *                             "___-___file_a",
     *                             "Message_485.eml" (this is IMAP Message)
     *
     * "___-___folder_a_a" contains: "____-____file_a_a"
     *
     */
    importInternal("imap/imapservice_test_folder_a.acp", testImapFolderNodeRef);

    reauthenticate(anotherUserName, anotherUserName);
  }
  @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);
    }
  }
Example #13
0
  public void test_MNT11595() throws Exception {
    final String user = "******";

    try {
      // admin authentication
      this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());

      MutableAuthenticationService mas =
          (MutableAuthenticationService)
              getServer().getApplicationContext().getBean("authenticationService");

      // create user
      createUser(user, SiteModel.SITE_MANAGER);

      assertTrue(personService.personExists(user));

      // invite user to a site with 'Manager' role
      siteService.setMembership(SITE_SHORT_NAME_WIKI, user, SiteRole.SiteManager.toString());

      // user authentication
      this.authenticationComponent.setCurrentUser(user);

      // create wiki page by user ('Manager' role)
      WikiPageInfo wikiPage =
          this.wikiService.createWikiPage(
              SITE_SHORT_NAME_WIKI,
              "test wiki page",
              "I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as equals. Sir Winston Churchill");

      String uri =
          "/slingshot/wiki/page/"
              + SITE_SHORT_NAME_WIKI
              + "/Main_Page?alf_ticket="
              + mas.getCurrentTicket()
              + "application/json";

      Response responseManagerRole = sendRequest(new GetRequest(uri), 404);
      JSONObject resultManagerRole = new JSONObject(responseManagerRole.getContentAsString());
      JSONObject permissionsManagerRole = resultManagerRole.getJSONObject("permissions");
      assertTrue(permissionsManagerRole.getBoolean("create"));
      assertTrue(permissionsManagerRole.getBoolean("edit"));

      // admin authentication
      this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());

      // change user role - 'Consumer' role
      siteService.setMembership(SITE_SHORT_NAME_WIKI, user, SiteRole.SiteConsumer.toString());

      // user authentication
      this.authenticationComponent.setCurrentUser(user);

      Response responseConsumerRole = sendRequest(new GetRequest(uri), 404);
      JSONObject resultConsumerRole = new JSONObject(responseConsumerRole.getContentAsString());
      JSONObject permissionsConsumerRole = resultConsumerRole.getJSONObject("permissions");
      assertFalse(permissionsConsumerRole.getBoolean("create"));
      assertFalse(permissionsConsumerRole.getBoolean("edit"));
    } finally {
      this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());

      if (personService.personExists(user)) {
        personService.deletePerson(user);
      }

      if (this.authenticationService.authenticationExists(user)) {
        this.authenticationService.deleteAuthentication(user);
      }
    }
  }
Example #14
0
  /** Listing */
  public void testOverallListing() throws Exception {
    JSONObject pages;
    JSONArray entries;

    // Initially, there are no events
    pages = getPages(null, null);
    assertEquals("Incorrect JSON: " + pages.toString(), true, pages.has("totalPages"));
    assertEquals(0, pages.getInt("totalPages"));

    // Add two links to get started with
    createOrUpdatePage(PAGE_TITLE_ONE, PAGE_CONTENTS_ONE, null, Status.STATUS_OK);
    createOrUpdatePage(PAGE_TITLE_TWO, PAGE_CONTENTS_TWO, null, Status.STATUS_OK);

    // Check again
    pages = getPages(null, null);

    // Should have two links
    assertEquals("Incorrect JSON: " + pages.toString(), true, pages.has("totalPages"));
    assertEquals(2, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(2, entries.length());
    // Sorted by newest created first
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(1).getString("title"));

    // Add a third, which is internal, and created by the other user
    this.authenticationComponent.setCurrentUser(USER_TWO);
    JSONObject page3 =
        createOrUpdatePage(PAGE_TITLE_THREE, PAGE_CONTENTS_THREE, null, Status.STATUS_OK);
    String name3 = PAGE_TITLE_THREE.replace(' ', '_');
    createOrUpdatePage(PAGE_TITLE_THREE, "UD" + PAGE_CONTENTS_THREE, null, Status.STATUS_OK);
    this.authenticationComponent.setCurrentUser(USER_ONE);

    // Check now, should have three links
    pages = getPages(null, null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Ask for filtering by user
    pages = getPages(null, USER_ONE);
    assertEquals(2, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(2, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(1).getString("title"));

    pages = getPages(null, USER_TWO);
    assertEquals(1, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(1, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));

    // Ask for filtering by recently added docs
    pages = getPages("recentlyAdded", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Push one back into the past
    pushPageCreatedDateBack(name3, 10);

    pages = getPages("recentlyAdded", null);
    assertEquals(2, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(2, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(1).getString("title"));

    // Now for recently modified ones
    pages = getPages("recentlyModified", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));
    //       assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(2).getString("title"));

    // Change the owner+creator of one of the pages to System, ensure that
    //  this doesn't break anything in the process
    String pageTwoName = entries.getJSONObject(1).getString("name");
    WikiPageInfo pageTwo = wikiService.getWikiPage(SITE_SHORT_NAME_WIKI, pageTwoName);
    nodeService.setProperty(
        pageTwo.getNodeRef(), ContentModel.PROP_OWNER, AuthenticationUtil.SYSTEM_USER_NAME);
    nodeService.setProperty(
        pageTwo.getNodeRef(), ContentModel.PROP_CREATOR, AuthenticationUtil.SYSTEM_USER_NAME);
    nodeService.setProperty(
        pageTwo.getNodeRef(), ContentModel.PROP_MODIFIER, AuthenticationUtil.SYSTEM_USER_NAME);

    // Check the listing still works (note - order will have changed)
    pages = getPages("recentlyModified", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Delete User Two, who owns the 3rd page, and ensure that this
    //  doesn't break anything
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    personService.deletePerson(USER_TWO);
    this.authenticationComponent.setCurrentUser(USER_ONE);

    // Check the listing still works
    pages = getPages("recentlyModified", null);
    assertEquals(3, pages.getInt("totalPages"));

    entries = pages.getJSONArray("pages");
    assertEquals(3, entries.length());
    assertEquals(PAGE_TITLE_TWO, entries.getJSONObject(0).getString("title"));
    assertEquals(PAGE_TITLE_THREE, entries.getJSONObject(1).getString("title"));
    assertEquals(PAGE_TITLE_ONE, entries.getJSONObject(2).getString("title"));

    // Now hide the site, and remove the user from it, won't be allowed to see it
    this.authenticationComponent.setCurrentUser(AuthenticationUtil.getAdminUserName());
    SiteInfo site = siteService.getSite(SITE_SHORT_NAME_WIKI);
    site.setVisibility(SiteVisibility.PRIVATE);
    siteService.updateSite(site);
    siteService.removeMembership(SITE_SHORT_NAME_WIKI, USER_ONE);
    this.authenticationComponent.setCurrentUser(USER_ONE);

    sendRequest(new GetRequest(URL_WIKI_LIST), Status.STATUS_NOT_FOUND);
  }
  public List<TopItem> listTopItems(int count, String type, int date, SiteInfo site) {

    ActivityScoreQuery activityScoreQuery = new ActivityScoreQuery();

    TopQuery topQuery = activityScoreQuery;

    // Site
    topQuery.setSite(site.getShortName());

    // Date
    DateMidnight dm = new DateMidnight();
    dm = dm.minusDays(date);
    topQuery.setDate(dm.toDate());

    // Criteria
    Map<String, TopCriterion> activityCriterionMap = typeActivityCriteriaMap.get(type);
    if (activityCriterionMap == null) {
      throw new IllegalArgumentException("Unknown top type '" + type + "'");
    }
    List<TopCriterion> criteria = new ArrayList<TopCriterion>(activityCriterionMap.values());

    topQuery.setCriteria(criteria);

    List<UserScore> topResults = topActivityDAO.executeTopQuery(topQuery);

    int topSize = Math.min(topResults.size(), count);
    List<TopItem> topItems = new ArrayList<TopItem>(topSize);

    if (topSize > 0) {

      Map<String, TopItem> topItemsMap = new HashMap<String, TopItem>(topSize);
      List<String> userIds = new ArrayList<String>(topSize);
      int position = 1;
      for (UserScore topUser : topResults) {

        String userName = topUser.getUserId();

        NodeRef node = personService.getPerson(userName);

        int score = topUser.getScore();

        TopItem topItem = new TopItem(position, score, node);
        topItems.add(topItem);

        topItemsMap.put(userName, topItem);

        userIds.add(userName);

        position++;

        if (position > count) {
          break;
        }
      }

      activityScoreQuery.setUserIds(userIds);

      List<UserActivityScore> activityScoreResults =
          topActivityDAO.executeActivityScoreQuery(activityScoreQuery);

      for (UserActivityScore userActivityScore : activityScoreResults) {

        String activity = userActivityScore.getActivity();
        TopCriterion criterion = activityCriterionMap.get(activity);
        userActivityScore.setCriterion(criterion);

        String userName = userActivityScore.getUserId();
        TopItem topItem = topItemsMap.get(userName);
        Score score = topItem.getScore();
        score.getCriterionScores().add(userActivityScore);
      }
    }

    if (logger.isDebugEnabled()) {
      XStream xstream = new XStream();
      logger.debug("listTopItems()=" + xstream.toXML(topItems));
    }

    return topItems;
  }