Ejemplo n.º 1
0
  /**
   * Create a link to a file. There is no need to call a session.save, the change is persistent.
   *
   * @param fileNode The node that represents the file. This node has to be retrieved via the normal
   *     user his {@link Session session}. If the userID equals {@link UserConstants.ANON_USERID} an
   *     AccessDeniedException will be thrown.
   * @param linkPath The absolute path in JCR where the link should be placed.
   * @param slingRepository The {@link SlingRepository} to use to login as an administrative.
   * @return The newly created node.
   * @throws AccessDeniedException When the user is anonymous.
   * @throws RepositoryException Something else went wrong.
   */
  public static boolean createLink(Node fileNode, String linkPath, SlingRepository slingRepository)
      throws AccessDeniedException, RepositoryException {
    Session session = fileNode.getSession();
    String userId = session.getUserID();
    if (UserConstants.ANON_USERID.equals(userId)) {
      throw new AccessDeniedException();
    }

    boolean hasMixin =
        JcrUtils.hasMixin(fileNode, REQUIRED_MIXIN) && fileNode.canAddMixin(REQUIRED_MIXIN);
    // If the fileNode doesn't have the required referenceable mixin, we need to set it.
    if (!hasMixin) {
      // The required mixin is not on the node.
      // Set it.
      Session adminSession = null;
      try {
        adminSession = slingRepository.loginAdministrative(null);

        // Grab the node via the adminSession
        String path = fileNode.getPath();
        Node adminFileNode = (Node) adminSession.getItem(path);
        if (!hasMixin) {
          adminFileNode.addMixin(REQUIRED_MIXIN);
        }

        if (adminSession.hasPendingChanges()) {
          adminSession.save();
        }
      } finally {
        if (adminSession != null) {
          adminSession.logout();
        }
      }
    }

    // Now that the file is referenceable, it has a uuid.
    // Use it for the link.
    // Grab the (updated) node via the user's session id.
    fileNode = (Node) session.getItem(fileNode.getPath());

    // Create the link
    Node linkNode = JcrUtils.deepGetOrCreateNode(session, linkPath);
    if (!"sling:Folder".equals(linkNode.getPrimaryNodeType().getName())) {
      // sling folder allows single and multiple properties, no need for the mixin.
      if (linkNode.canAddMixin(REQUIRED_MIXIN)) {
        linkNode.addMixin(REQUIRED_MIXIN);
      }
    }
    linkNode.setProperty(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, RT_SAKAI_LINK);
    linkNode.setProperty(SAKAI_LINK, fileNode.getIdentifier());

    // Save link.
    if (session.hasPendingChanges()) {
      session.save();
    }

    return true;
  }