private PersonFavourite addFavouriteSite(String userName, NodeRef nodeRef) {
    PersonFavourite favourite = null;

    SiteInfo siteInfo = siteService.getSite(nodeRef);
    if (siteInfo != null) {
      favourite = getFavouriteSite(userName, siteInfo);
      if (favourite == null) {
        Map<String, Serializable> preferences = new HashMap<String, Serializable>(1);

        String siteFavouritedKey = siteFavouritedKey(siteInfo);
        preferences.put(siteFavouritedKey, Boolean.TRUE);

        // ISO8601 string format: PreferenceService works with strings only for dates it seems
        String siteCreatedAtKey = siteCreatedAtKey(siteInfo);
        Date createdAt = new Date();
        String createdAtStr = ISO8601DateFormat.format(createdAt);
        preferences.put(siteCreatedAtKey, createdAtStr);

        preferenceService.setPreferences(userName, preferences);

        favourite =
            new PersonFavourite(
                userName, siteInfo.getNodeRef(), Type.SITE, siteInfo.getTitle(), createdAt);

        QName nodeClass = nodeService.getType(nodeRef);
        OnAddFavouritePolicy policy = onAddFavouriteDelegate.get(nodeRef, nodeClass);
        policy.onAddFavourite(userName, nodeRef);
      }
    } else {
      // shouldn't happen, getType recognizes it as a site or subtype
      logger.warn("Unable to get site for " + nodeRef);
    }

    return favourite;
  }
  private PersonFavourite getFavouriteSite(String userName, SiteInfo siteInfo) {
    PersonFavourite favourite = null;

    String siteFavouritedKey = siteFavouritedKey(siteInfo);
    String siteCreatedAtKey = siteCreatedAtKey(siteInfo);

    Boolean isFavourited = false;
    Serializable s = preferenceService.getPreference(userName, siteFavouritedKey);
    if (s != null) {
      if (s instanceof String) {
        isFavourited = Boolean.valueOf((String) s);
      } else if (s instanceof Boolean) {
        isFavourited = (Boolean) s;
      } else {
        throw new AlfrescoRuntimeException("Unexpected favourites preference value");
      }
    }

    if (isFavourited) {
      String createdAtStr = (String) preferenceService.getPreference(userName, siteCreatedAtKey);
      Date createdAt = (createdAtStr == null ? null : ISO8601DateFormat.parse(createdAtStr));

      favourite =
          new PersonFavourite(
              userName, siteInfo.getNodeRef(), Type.SITE, siteInfo.getTitle(), createdAt);
    }

    return favourite;
  }
Exemplo n.º 3
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);
    }
  }
Exemplo n.º 4
0
  private String getSiteName(Map<String, String> properties) {
    String siteFullName = properties.get(wfVarResourceName);
    SiteInfo site = siteService.getSite(siteFullName);
    if (site == null)
      throw new InvitationException("The site " + siteFullName + " could not be found.");

    String siteName = site.getShortName();
    String siteTitle = site.getTitle();
    if (siteTitle != null && siteTitle.length() > 0) {
      siteName = siteTitle;
    }
    return siteName;
  }
Exemplo n.º 5
0
  /**
   * Get a map of the sites custom properties
   *
   * @return map of names and values
   */
  public ScriptableQNameMap<String, CustomProperty> getCustomProperties() {
    if (this.customProperties == null) {
      // create the custom properties map
      ScriptNode siteNode = new ScriptNode(this.siteInfo.getNodeRef(), this.serviceRegistry);
      // set the scope, for use when converting props to javascript objects
      siteNode.setScope(scope);
      this.customProperties =
          new ContentAwareScriptableQNameMap<String, CustomProperty>(
              siteNode, this.serviceRegistry);

      Map<QName, Serializable> props = siteInfo.getCustomProperties();
      for (QName qname : props.keySet()) {
        // get the property value
        Serializable propValue = props.get(qname);

        // convert the value
        NodeValueConverter valueConverter = siteNode.new NodeValueConverter();
        Serializable value = valueConverter.convertValueForScript(qname, propValue);

        // get the type and label information from the dictionary
        String title = null;
        String type = null;
        PropertyDefinition propDef = this.serviceRegistry.getDictionaryService().getProperty(qname);
        if (propDef != null) {
          type = propDef.getDataType().getName().toString();
          title = propDef.getTitle(this.serviceRegistry.getDictionaryService());
        }

        // create the custom property and add to the map
        CustomProperty customProp = new CustomProperty(qname.toString(), value, type, title);
        this.customProperties.put(qname.toString(), customProp);
      }
    }
    return this.customProperties;
  }
Exemplo n.º 6
0
  public void testRenamePageWithEmptyTitle() throws Exception {
    JSONObject page;
    String name = System.currentTimeMillis() + "";
    String name2 = System.currentTimeMillis() + 1 + "";

    // Create a page
    page = createOrUpdatePage(name, name, null, Status.STATUS_OK);
    assertEquals("Incorrect JSON: " + page.toString(), true, page.has("title"));

    // Fetch it and check
    page = getPage(name, Status.STATUS_OK);
    assertEquals(name, page.getString("name"));
    assertEquals(name, page.getString("title"));

    // update title
    SiteInfo site = siteService.getSite(SITE_SHORT_NAME_WIKI);
    WikiPageInfo pageInfo = wikiService.getWikiPage(site.getShortName(), name);
    NodeRef pageRef = pageInfo.getNodeRef();
    nodeService.setProperty(pageRef, ContentModel.PROP_TITLE, "");

    // Fetch it and check
    page = getPage(name, Status.STATUS_OK);
    JSONArray versions = page.getJSONArray("versionhistory");

    int maxVersionIndex = versions.length() - 1;
    double vNum = Double.parseDouble(versions.getJSONObject(maxVersionIndex).getString("version"));
    String newTitle = versions.getJSONObject(maxVersionIndex).getString("title");
    for (int i = versions.length() - 2; i >= 0; i--) {
      JSONObject version = versions.getJSONObject(i);
      String ver = version.getString("version");
      if (Double.parseDouble(ver) > vNum) {
        maxVersionIndex = i;
        vNum = Double.parseDouble(ver);
        newTitle = versions.getJSONObject(maxVersionIndex).getString("title");
      }
    }
    assertEquals(name, page.getString("name"));
    assertEquals("", newTitle);

    renamePage(name, name2, Status.STATUS_OK);

    // Fetch it at the new address
    page = getPage(name2, Status.STATUS_OK);
    assertEquals(name2, page.getString("name"));
    assertEquals(name2, page.getString("title"));
  }
  private String siteFavouritedKey(SiteInfo siteInfo) {
    PrefKeys prefKeys = getPrefKeys(Type.SITE);

    StringBuilder sitePrefKeyBuilder = new StringBuilder(prefKeys.getSharePrefKey());
    sitePrefKeyBuilder.append(siteInfo.getShortName());
    String sitePrefKey = sitePrefKeyBuilder.toString();

    String favouritedKey = sitePrefKey;
    return favouritedKey;
  }
  private boolean removeFavouriteSite(String userName, NodeRef nodeRef) {
    PrefKeys prefKeys = getPrefKeys(Type.SITE);
    boolean exists = false;

    SiteInfo siteInfo = siteService.getSite(nodeRef);
    if (siteInfo != null) {
      StringBuilder sitePrefKeyBuilder = new StringBuilder(prefKeys.getSharePrefKey());
      sitePrefKeyBuilder.append(siteInfo.getShortName());
      String sitePrefKey = sitePrefKeyBuilder.toString();

      String siteFavouritedKey = siteFavouritedKey(siteInfo);

      exists = preferenceService.getPreference(userName, siteFavouritedKey) != null;
      preferenceService.clearPreferences(userName, sitePrefKey);
    } else {
      throw new IllegalArgumentException("NodeRef " + nodeRef + " is not a site");
    }

    return exists;
  }
  private String siteCreatedAtKey(SiteInfo siteInfo) {
    PrefKeys prefKeys = getPrefKeys(Type.SITE);

    StringBuilder sitePrefKeyBuilder = new StringBuilder(prefKeys.getAlfrescoPrefKey());
    sitePrefKeyBuilder.append(siteInfo.getShortName());
    String sitePrefKey = sitePrefKeyBuilder.toString();

    StringBuilder createdAtKeyBuilder = new StringBuilder(sitePrefKey);
    createdAtKeyBuilder.append(".createdAt");
    String createdAtKey = createdAtKeyBuilder.toString();
    return createdAtKey;
  }
  private void extractFavouriteSite(
      String userName,
      Type type,
      Map<PersonFavouriteKey, PersonFavourite> sortedFavouriteNodes,
      Map<String, Serializable> preferences,
      String key) {
    // preference value indicates whether the site has been favourited
    Serializable pref = preferences.get(key);
    Boolean isFavourite = (Boolean) pref;
    if (isFavourite) {
      PrefKeys sitePrefKeys = getPrefKeys(Type.SITE);
      int length = sitePrefKeys.getSharePrefKey().length();
      String siteId = key.substring(length);

      try {
        SiteInfo siteInfo = siteService.getSite(siteId);
        if (siteInfo != null) {
          StringBuilder builder = new StringBuilder(sitePrefKeys.getAlfrescoPrefKey());
          builder.append(siteId);
          builder.append(".createdAt");
          String createdAtPrefKey = builder.toString();
          String createdAtStr = (String) preferences.get(createdAtPrefKey);
          Date createdAt = null;
          if (createdAtStr != null) {
            createdAt = (createdAtStr != null ? ISO8601DateFormat.parse(createdAtStr) : null);
          }
          PersonFavourite personFavourite =
              new PersonFavourite(userName, siteInfo.getNodeRef(), Type.SITE, siteId, createdAt);
          sortedFavouriteNodes.put(personFavourite.getKey(), personFavourite);
        }
      } catch (AccessDeniedException ex) {
        // the user no longer has access to this site, skip over the favourite
        // TODO remove the favourite preference
        return;
      }
    }
  }
Exemplo n.º 11
0
  @Override
  protected Map<String, Object> executeImpl(
      SiteInfo site,
      String linkName,
      WebScriptRequest req,
      JSONObject json,
      Status status,
      Cache cache) {
    Map<String, Object> model = new HashMap<String, Object>();

    // Try to find the link
    LinkInfo link = linksService.getLink(site.getShortName(), linkName);
    if (link == null) {
      String message = "No link found with that name";

      status.setCode(Status.STATUS_NOT_FOUND);
      status.setMessage(message);
      model.put(PARAM_MESSAGE, message);
      return model;
    }

    // Get the new link details from the JSON
    // Update the main properties
    link.setTitle(getOrNull(json, "title"));
    link.setDescription(getOrNull(json, "description"));
    link.setURL(getOrNull(json, "url"));

    // Handle internal / not internal
    if (json.containsKey("internal")) {
      link.setInternal(true);
    } else {
      link.setInternal(false);
    }

    // Do the tags
    link.getTags().clear();
    List<String> tags = getTags(json);
    if (tags != null && tags.size() > 0) {
      link.getTags().addAll(tags);
    }

    // Update the link
    try {
      link = linksService.updateLink(link);
    } catch (AccessDeniedException e) {
      String message = "You don't have permission to update that link";

      status.setCode(Status.STATUS_FORBIDDEN);
      status.setMessage(message);
      model.put(PARAM_MESSAGE, message);
      return model;
    }

    // Generate an activity for the change
    addActivityEntry("updated", link, site, req, json);

    // Build the model
    model.put(PARAM_MESSAGE, "Node " + link.getNodeRef() + " updated");
    model.put("link", link);
    model.put("site", site);
    model.put("siteId", site.getShortName());

    // All done
    return model;
  }
  @Override
  protected Map<String, Object> executeImpl(
      SiteInfo site,
      String pageTitle,
      WebScriptRequest req,
      JSONObject json,
      Status status,
      Cache cache) {
    Map<String, Object> model = new HashMap<>();

    // Grab the version string
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    String versionId = templateVars.get("versionId");
    if (versionId == null) {
      String error = "No versionId supplied";
      throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }

    // Try to find the page
    WikiPageInfo page = wikiService.getWikiPage(site.getShortName(), pageTitle);
    if (page == null) {
      String message = "The Wiki Page could not be found";
      status.setCode(Status.STATUS_NOT_FOUND);
      status.setMessage(message);

      // Return an empty string though
      model.put(PARAM_CONTENT, "");
      return model;
    }

    // Fetch the version history for the node
    VersionHistory versionHistory = null;
    Version version = null;
    try {
      versionHistory = versionService.getVersionHistory(page.getNodeRef());
    } catch (AspectMissingException e) {
    }

    if (versionHistory == null) {
      // Not been versioned, return an empty string
      model.put(PARAM_CONTENT, "");
      return model;
    }

    // Fetch the version by either ID or Label
    Matcher m = LABEL_PATTERN.matcher(versionId);
    if (m.matches()) {
      // It's a version label like 2.3
      try {
        version = versionHistory.getVersion(versionId);
      } catch (VersionDoesNotExistException e) {
      }
    } else {
      // It's a version ID like ed00bac1-f0da-4042-8598-45a0d39cb74d
      // (The ID is usually part of the NodeRef of the frozen node, but we
      //  don't assume to be able to just generate the full NodeRef)
      for (Version v : versionHistory.getAllVersions()) {
        if (v.getFrozenStateNodeRef().getId().equals(versionId)) {
          version = v;
        }
      }
    }

    // Did we find the right version in the end?
    String contents;
    if (version != null) {
      ContentReader reader =
          contentService.getReader(version.getFrozenStateNodeRef(), ContentModel.PROP_CONTENT);
      if (reader != null) {
        contents = reader.getContentString();
      } else {
        // No content was stored in the version history
        contents = "";
      }
    } else {
      // No warning of the missing version, just return an empty string
      contents = "";
    }

    // All done
    model.put(PARAM_CONTENT, contents);
    model.put("page", page);
    model.put("site", site);
    model.put("siteId", site.getShortName());
    return model;
  }
Exemplo n.º 13
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);
  }
Exemplo n.º 14
0
  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;
  }