/** {@inheritDoc} */
  public void undeleteFile(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId)
      throws RepositoryException {
    Node fileToUndeleteNode = session.getNodeByIdentifier(fileId.toString());
    String trashFileIdNodePath = fileToUndeleteNode.getParent().getPath();
    String origParentFolderPath =
        getOriginalParentFolderPath(session, pentahoJcrConstants, fileToUndeleteNode, false);

    String absDestPath =
        origParentFolderPath + RepositoryFile.SEPARATOR + fileToUndeleteNode.getName();

    if (session.itemExists(absDestPath)) {
      RepositoryFile file =
          JcrRepositoryFileUtils.nodeToFile(
              session,
              pentahoJcrConstants,
              pathConversionHelper,
              lockHelper,
              (Node) session.getItem(absDestPath));
      throw new RepositoryFileDaoFileExistsException(file);
    }

    session.move(fileToUndeleteNode.getPath(), absDestPath);
    session.getItem(trashFileIdNodePath).remove();
  }
  private Node getFrozenNode(final String label) throws RepositoryException {
    try {
      final Session session = getSession();

      final Node frozenNode = session.getNodeByIdentifier(label);

      final String baseUUID = getNode().getIdentifier();

      /*
       * We found a node whose identifier is the "label" for the version.  Now
       * we must do due dilligence to make sure it's a frozen node representing
       * a version of the subject node.
       */
      final Property p = frozenNode.getProperty("jcr:frozenUuid");
      if (p != null) {
        if (p.getString().equals(baseUUID)) {
          return frozenNode;
        }
      }
      /*
       * Though a node with an id of the label was found, it wasn't the
       * node we were looking for, so fall through and look for a labeled
       * node.
       */
    } catch (final ItemNotFoundException ex) {
      /*
       * the label wasn't a uuid of a frozen node but
       * instead possibly a version label.
       */
    }
    return null;
  }
 @Override
 protected Node nodeWithId(String id, Session session) throws RepositoryException {
   try {
     return session.getNodeByIdentifier(id);
   } catch (ItemNotFoundException infe) {
     throw new NotFoundException(infe.getMessage(), infe);
   }
 }
  @Test
  public void testProperUUID() throws ItemNotFoundException, RepositoryException {
    SlingHttpServletRequest request = mock(SlingHttpServletRequest.class);
    HtmlResponse response = new HtmlResponse();

    ResourceResolver resolver = mock(ResourceResolver.class);

    String uuid = "cafede-cafede-cafede-cafede-cafede";
    Resource resource = mock(Resource.class);

    // The tagnode
    Node tagNode = new MockNode("/path/to/tag");
    tagNode.setProperty(SLING_RESOURCE_TYPE_PROPERTY, FilesConstants.RT_SAKAI_TAG);
    tagNode.setProperty(FilesConstants.SAKAI_TAG_NAME, "urban");

    // The file we want to tag.
    Node fileNode = mock(Node.class);
    when(fileNode.getPath()).thenReturn("/path/to/file");
    NodeType type = mock(NodeType.class);
    when(type.getName()).thenReturn("foo");
    when(fileNode.getMixinNodeTypes()).thenReturn(new NodeType[] {type});
    Property tagsProp = mock(Property.class);
    MockPropertyDefinition tagsPropDef = new MockPropertyDefinition(false);
    Value v = new MockValue("uuid-to-other-tag");
    when(tagsProp.getDefinition()).thenReturn(tagsPropDef);
    when(tagsProp.getValue()).thenReturn(v);
    when(fileNode.getProperty(FilesConstants.SAKAI_TAGS)).thenReturn(tagsProp);
    when(fileNode.hasProperty(FilesConstants.SAKAI_TAGS)).thenReturn(true);

    // Stuff to check if this is a correct request
    when(session.getNodeByIdentifier(uuid)).thenReturn(tagNode);
    RequestParameter uuidParam = mock(RequestParameter.class);
    when(resolver.adaptTo(Session.class)).thenReturn(session);
    when(resource.adaptTo(Node.class)).thenReturn(fileNode);
    when(uuidParam.getString()).thenReturn(uuid);
    when(request.getResource()).thenReturn(resource);
    when(request.getResourceResolver()).thenReturn(resolver);
    when(request.getRequestParameter("key")).thenReturn(uuidParam);
    when(request.getRemoteUser()).thenReturn("john");

    // Actual tagging procedure
    Session adminSession = mock(Session.class);
    when(adminSession.getItem(fileNode.getPath())).thenReturn(fileNode);
    ValueFactory valueFactory = mock(ValueFactory.class);
    Value newValue = new MockValue("uuid-of-tag");
    when(valueFactory.createValue(Mockito.anyString(), Mockito.anyInt()))
        .thenReturn(newValue)
        .thenReturn(newValue);
    when(adminSession.getValueFactory()).thenReturn(valueFactory).thenReturn(valueFactory);
    when(slingRepo.loginAdministrative(null)).thenReturn(adminSession);

    when(adminSession.hasPendingChanges()).thenReturn(true);
    operation.doRun(request, response, null);

    assertEquals(200, response.getStatusCode());
    verify(adminSession).save();
    verify(adminSession).logout();
  }
 /** {@inheritDoc} */
 public String getOriginalParentFolderPath(
     final Session session,
     final PentahoJcrConstants pentahoJcrConstants,
     final Serializable fileId)
     throws RepositoryException {
   return JcrStringHelper.pathDecode(
       getOriginalParentFolderPath(
           session, pentahoJcrConstants, session.getNodeByIdentifier(fileId.toString()), false));
 }
 public JCRNodeWrapper getNodeByUUID(String providerKey, String uuid)
     throws ItemNotFoundException, RepositoryException {
   JCRStoreProvider provider = sessionFactory.getProviders().get(providerKey);
   if (provider == null) {
     throw new ItemNotFoundException(uuid);
   }
   Session session = getProviderSession(provider);
   Node n = session.getNodeByIdentifier(uuid);
   return provider.getNodeWrapper(n, this);
 }
  @Test
  public void testNextWithReference() throws Exception {
    when(mockValue.getType()).thenReturn(PropertyType.REFERENCE);
    when(mockValue.getString()).thenReturn("uuid");
    when(mockSession.getNodeByIdentifier("uuid")).thenReturn(mockNode);
    when(mockGraphSubjects.getSubject(mockNode.getPath()))
        .thenReturn(ResourceFactory.createResource("http://localhost:8080/xyz"));
    final QuerySolution solution = testObj.next();

    assertEquals("http://localhost:8080/xyz", solution.get("a").asResource().getURI());
  }
  protected RepositoryFileAcl internalUpdateAcl(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId,
      final RepositoryFileAcl acl)
      throws RepositoryException {
    Node node = session.getNodeByIdentifier(fileId.toString());
    if (node == null) {
      throw new RepositoryException(
          Messages.getInstance()
              .getString(
                  "JackrabbitRepositoryFileAclDao.ERROR_0001_NODE_NOT_FOUND",
                  fileId.toString())); // $NON-NLS-1$
    }
    String absPath = node.getPath();
    AccessControlManager acMgr = session.getAccessControlManager();
    AccessControlList acList = getAccessControlList(acMgr, absPath);

    // clear all entries
    AccessControlEntry[] acEntries = acList.getAccessControlEntries();
    for (int i = 0; i < acEntries.length; i++) {
      acList.removeAccessControlEntry(acEntries[i]);
    }

    JcrRepositoryFileAclUtils.setAclMetadata(
        session,
        absPath,
        acList,
        new AclMetadata(acl.getOwner().getName(), acl.isEntriesInheriting()));

    // add entries to now empty list but only if not inheriting; force user to start with clean
    // slate
    if (!acl.isEntriesInheriting()) {
      for (RepositoryFileAce ace : acl.getAces()) {
        Principal principal = null;
        if (RepositoryFileSid.Type.ROLE == ace.getSid().getType()) {
          principal = new SpringSecurityRolePrincipal(ace.getSid().getName());
        } else {
          principal = new SpringSecurityUserPrincipal(ace.getSid().getName());
        }
        acList.addAccessControlEntry(
            principal,
            permissionConversionHelper.pentahoPermissionsToPrivileges(
                session, ace.getPermissions()));
      }
    }
    acMgr.setPolicy(absPath, acList);
    session.save();
    return getAcl(fileId);
  }
  public void testConcurrentSessionMove() throws RepositoryException {

    testRootPath = testRootNode.getPath();
    Node aa = testRootNode.addNode("a").addNode("aa");
    Node b = testRootNode.addNode("b");
    testRootNode.getSession().save();

    String aaId = aa.getIdentifier();
    String bId = b.getIdentifier();

    Session session1 = getHelper().getReadWriteSession();
    Session session2 = getHelper().getReadWriteSession();

    // results in /b/a/aa
    session1.move(testRootPath + "/a", testRootPath + "/b/a");
    assertEquals(testRootPath + "/b/a/aa", session1.getNodeByIdentifier(aaId).getPath());

    // results in a/aa/b
    session2.move(testRootPath + "/b", testRootPath + "/a/aa/b");
    assertEquals(testRootPath + "/a/aa/b", session2.getNodeByIdentifier(bId).getPath());

    session1.save();

    // path should not have changed after save.
    assertEquals(testRootPath + "/a/aa/b", session2.getNodeByIdentifier(bId).getPath());

    try {
      session2.save();
      fail("Save should have failed. Possible cyclic persistent path created.");
    } catch (InvalidItemStateException e) {
      // expect is a ex caused by a StaleItemStateException with "has been modified externally"
      if (!(e.getCause() instanceof StaleItemStateException)) {
        throw e;
      }
    }
  }
 protected Value convertToJcrValue(PropertyType graphType, Object graphValue)
     throws RepositoryException {
   if (graphValue == null) return null;
   switch (graphType) {
     case NAME:
     case PATH:
     case UUID:
     case URI:
     case STRING:
     case OBJECT:
       String stringValue = factories.getStringFactory().create(graphValue);
       return jcrValueFactory.createValue(stringValue);
     case BOOLEAN:
       Boolean booleanValue = factories.getBooleanFactory().create(graphValue);
       return jcrValueFactory.createValue(booleanValue.booleanValue());
     case DECIMAL:
       BigDecimal decimalValue = factories.getDecimalFactory().create(graphValue);
       return jcrValueFactory.createValue(decimalValue);
     case DOUBLE:
       Double doubleValue = factories.getDoubleFactory().create(graphValue);
       return jcrValueFactory.createValue(doubleValue);
     case LONG:
       Long longValue = factories.getLongFactory().create(graphValue);
       return jcrValueFactory.createValue(longValue);
     case DATE:
       Calendar calValue = factories.getDateFactory().create(graphValue).toCalendar();
       return jcrValueFactory.createValue(calValue);
     case BINARY:
       Binary binary = factories.getBinaryFactory().create(graphValue);
       try {
         binary.acquire();
         javax.jcr.Binary jcrBinary = jcrValueFactory.createBinary(binary.getStream());
         return jcrValueFactory.createValue(jcrBinary);
       } finally {
         binary.release();
       }
     case WEAKREFERENCE:
     case REFERENCE:
       boolean isWeak = graphType == PropertyType.WEAKREFERENCE;
       String identifier = factories.getStringFactory().create(graphValue);
       Node node = session.getNodeByIdentifier(identifier);
       return jcrValueFactory.createValue(node, isWeak);
   }
   assert false;
   return null;
 }
  private RepositoryFileAcl toAcl(
      final Session session, final PentahoJcrConstants pentahoJcrConstants, final Serializable id)
      throws RepositoryException {

    Node node = session.getNodeByIdentifier(id.toString());
    if (node == null) {
      throw new RepositoryException(
          Messages.getInstance()
              .getString(
                  "JackrabbitRepositoryFileAclDao.ERROR_0001_NODE_NOT_FOUND",
                  id.toString())); // $NON-NLS-1$
    }
    String absPath = node.getPath();
    AccessControlManager acMgr = session.getAccessControlManager();
    AccessControlList acList = getAccessControlList(acMgr, absPath);

    RepositoryFileSid owner = null;
    String ownerString = getOwner(session, absPath, acList);

    if (ownerString != null) {
      // for now, just assume all owners are users; only has UI impact
      owner =
          new RepositoryFileSid(
              JcrTenantUtils.getUserNameUtils().getPrincipleName(ownerString),
              RepositoryFileSid.Type.USER);
    }

    RepositoryFileAcl.Builder aclBuilder = new RepositoryFileAcl.Builder(id, owner);

    aclBuilder.entriesInheriting(isEntriesInheriting(session, absPath, acList));

    List<AccessControlEntry> cleanedAcEntries =
        JcrRepositoryFileAclUtils.removeAclMetadata(
            Arrays.asList(acList.getAccessControlEntries()));

    for (AccessControlEntry acEntry : cleanedAcEntries) {
      if (!acEntry
          .getPrincipal()
          .equals(
              new SpringSecurityRolePrincipal(
                  JcrTenantUtils.getTenantedRole(tenantAdminAuthorityName)))) {
        aclBuilder.ace(toAce(session, acEntry));
      }
    }
    return aclBuilder.build();
  }
 /**
  * Find the existing node given the location.
  *
  * @param location the location of the node, which must have a {@link Location#getPath() path}
  *     and/or {@link Location#getUuid() UUID}
  * @return the existing node; never null
  * @throws RepositoryException if there is an error working with the session
  * @throws PathNotFoundException if the node could not be found by its path
  */
 public Node node(Location location) throws RepositoryException {
   Node root = session.getRootNode();
   UUID uuid = location.getUuid();
   if (uuid != null) {
     try {
       return session.getNodeByIdentifier(uuid.toString());
     } catch (ItemNotFoundException e) {
       if (!location.hasPath()) {
         String msg = JcrConnectorI18n.unableToFindNodeWithUuid.text(getSourceName(), uuid);
         throw new PathNotFoundException(
             location, factories.getPathFactory().createRootPath(), msg);
       }
       // Otherwise, try to find it by its path ...
     }
   }
   if (location.hasPath()) {
     Path relativePath = location.getPath().relativeToRoot();
     ValueFactory<String> stringFactory = factories.getStringFactory();
     String relativePathStr = stringFactory.create(relativePath);
     try {
       return root.getNode(relativePathStr);
     } catch (javax.jcr.PathNotFoundException e) {
       // Figure out the lowest existing path ...
       Node node = root;
       for (Path.Segment segment : relativePath) {
         try {
           node = node.getNode(stringFactory.create(segment));
         } catch (javax.jcr.PathNotFoundException e2) {
           String pathStr = stringFactory.create(location.getPath());
           Path lowestPath = factories.getPathFactory().create(node.getPath());
           throw new PathNotFoundException(
               location,
               lowestPath,
               JcrConnectorI18n.nodeDoesNotExist.text(
                   getSourceName(), session.getWorkspace().getName(), pathStr));
         }
       }
     }
   }
   // Otherwise, we can't find the node ...
   String msg =
       JcrConnectorI18n.unableToFindNodeWithoutPathOrUuid.text(getSourceName(), location);
   throw new IllegalArgumentException(msg);
 }
 /** {@inheritDoc} */
 public void deleteFile(
     final Session session,
     final PentahoJcrConstants pentahoJcrConstants,
     final Serializable fileId)
     throws RepositoryException {
   Node fileToDeleteNode = session.getNodeByIdentifier(fileId.toString());
   // move file to .trash subfolder named with the UUID of the file to delete
   Node trashFileIdNode = getOrCreateTrashFileIdNode(session, pentahoJcrConstants, fileId);
   trashFileIdNode.setProperty(pentahoJcrConstants.getPHO_DELETEDDATE(), Calendar.getInstance());
   trashFileIdNode.setProperty(
       pentahoJcrConstants.getPHO_ORIGPARENTFOLDERPATH(),
       pathConversionHelper.absToRel(fileToDeleteNode.getParent().getPath()));
   // origName only stored in order to do a jcr:like query later on the node name; fn:name() can
   // only do equals
   trashFileIdNode.setProperty(pentahoJcrConstants.getPHO_ORIGNAME(), fileToDeleteNode.getName());
   session.move(
       fileToDeleteNode.getPath(),
       trashFileIdNode.getPath() + RepositoryFile.SEPARATOR + fileToDeleteNode.getName());
 }
Exemple #14
0
  /**
   * Writes all the properties for a linked node.
   *
   * @param node
   * @param write
   * @throws JSONException
   * @throws RepositoryException
   */
  public static void writeLinkNode(Node node, Session session, JSONWriter write)
      throws JSONException, RepositoryException {
    write.object();
    // Write all the properties.
    ExtendedJSONWriter.writeNodeContentsToWriter(write, node);
    // permissions
    writePermissions(node, session, write);

    // Write the actual file.
    if (node.hasProperty(SAKAI_LINK)) {
      String uuid = node.getProperty(SAKAI_LINK).getString();
      write.key("file");
      try {
        Node fileNode = session.getNodeByIdentifier(uuid);
        writeFileNode(fileNode, session, write);
      } catch (ItemNotFoundException e) {
        write.value(false);
      }
    }

    write.endObject();
  }
 // returns encoded path
 private String getOriginalParentFolderPath(
     final Session session,
     final PentahoJcrConstants pentahoJcrConstants,
     final Node trashFileNode,
     final boolean relative)
     throws RepositoryException {
   if (trashFileNode.getParent().hasProperty(pentahoJcrConstants.getPHO_ORIGPARENTFOLDERPATH())) {
     String relPath =
         trashFileNode
             .getParent()
             .getProperty(pentahoJcrConstants.getPHO_ORIGPARENTFOLDERPATH())
             .getString();
     return relative ? relPath : pathConversionHelper.relToAbs(relPath);
   } else {
     // legacy mode
     final String prefix = session.getNamespacePrefix(PentahoJcrConstants.PHO_NS);
     String originalParentFolderId =
         trashFileNode.getParent().getParent().getName().substring(prefix.length() + 1);
     String absPath = session.getNodeByIdentifier(originalParentFolderId).getPath();
     return relative ? pathConversionHelper.absToRel(absPath) : absPath;
   }
 }
 private String getReturnValue(Object returnObject) {
   if (returnObject == null) {
     return null;
   }
   if (returnObject instanceof Document) {
     Document document = (Document) returnObject;
     StringBuilder sb = new StringBuilder();
     sb.append("document[uuid=");
     sb.append(document.getIdentity());
     if (document.getIdentity() != null) {
       sb.append(",path='");
       try {
         sb.append(session.getNodeByIdentifier(document.getIdentity()).getPath());
       } catch (RepositoryException e) {
         sb.append("error:").append(e.getMessage());
       }
     }
     sb.append("']");
     return sb.toString();
   } else {
     return returnObject.toString();
   }
 }
  @Test
  public void testWriteLinkNode() throws JSONException, RepositoryException, IOException {
    Session session = mock(Session.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer w = new PrintWriter(baos);
    JSONWriter write = new JSONWriter(w);
    SiteService siteService = mock(SiteService.class);

    Node node = new MockNode("/path/to/link");
    node.setProperty(FilesConstants.SAKAI_LINK, "uuid");
    node.setProperty("foo", "bar");
    Node fileNode = createFileNode();
    when(session.getNodeByIdentifier("uuid")).thenReturn(fileNode);

    FileUtils.writeLinkNode(node, session, write, siteService);
    w.flush();
    String s = baos.toString("UTF-8");
    JSONObject j = new JSONObject(s);

    assertEquals("/path/to/link", j.getString("jcr:path"));
    assertEquals("bar", j.getString("foo"));
    assertFileNodeInfo(j.getJSONObject("file"));
  }
Exemple #18
0
 /**
  * Resolves a Node given one of three possible passed parameters: 1) A fully qualified path to a
  * Node (e.g. "/foo/bar/baz"), 2) a Node's UUID, or 3) the PoolId from a ContentPool.
  *
  * @param pathOrIdentifier One of three possible parameters: 1) A fully qualified path to a Node
  *     (e.g. "/foo/bar/baz"), 2) a Node's UUID, or 3) the PoolId from a ContentPool.
  * @param resourceResolver
  * @return If the Node cannot be resolved, <code>null</code> will be returned.
  * @throws IllegalArgumentException
  */
 public static Node resolveNode(
     final String pathOrIdentifier, final ResourceResolver resourceResolver) {
   if (pathOrIdentifier == null || "".equals(pathOrIdentifier)) {
     throw new IllegalArgumentException("Passed argument was null or empty");
   }
   if (resourceResolver == null) {
     throw new IllegalArgumentException("Resource resolver cannot be null");
   }
   Node node = null;
   try {
     if (pathOrIdentifier.startsWith("/")) { // it is a path specification
       Resource r = resourceResolver.resolve(pathOrIdentifier);
       if (r != null) {
         node = r.adaptTo(Node.class);
       }
     } else {
       // Not a full resource path, so try the two flavors of ID.
       Session session = resourceResolver.adaptTo(Session.class);
       // First, assume we have a UUID and try to resolve
       try {
         node = session.getNodeByIdentifier(pathOrIdentifier);
       } catch (RepositoryException e) {
         log.debug("Swallowed exception; i.e. normal operation: {}", e.getLocalizedMessage(), e);
       }
       if (node == null) {
         log.warn("Unable to Tag Content Pool at this time, tried {} ", pathOrIdentifier);
         // must not have been a UUID; resolve via poolId
         // final String poolPath = CreateContentPoolServlet.hash(pathOrIdentifier);
         // node = session.getNode(poolPath);
       }
     }
   } catch (Throwable e) {
     log.error(e.getLocalizedMessage(), e);
   }
   return node;
 }
  private ModelResource createModelResource(Node node) throws RepositoryException {
    ModelResource resource =
        new ModelResource(
            ModelId.fromPath(node.getParent().getPath()),
            ModelType.valueOf(node.getProperty("vorto:type").getString()));
    resource.setDescription(node.getProperty("vorto:description").getString());
    resource.setDisplayName(node.getProperty("vorto:displayname").getString());
    resource.setCreationDate(node.getProperty("jcr:created").getDate().getTime());
    if (node.hasProperty("vorto:author")) {
      resource.setAuthor(node.getProperty("vorto:author").getString());
    }

    if (node.hasProperty("vorto:references")) {
      Value[] referenceValues = node.getProperty("vorto:references").getValues();
      if (referenceValues != null) {
        ModelReferencesHelper referenceHelper = new ModelReferencesHelper();
        for (Value referValue : referenceValues) {
          String nodeUuid = referValue.getString();
          Node referencedNode = session.getNodeByIdentifier(nodeUuid);
          referenceHelper.addModelReference(
              ModelId.fromPath(referencedNode.getParent().getPath()).getPrettyFormat());
        }
        resource.setReferences(referenceHelper.getReferences());
      }
    }

    PropertyIterator propIter = node.getReferences();
    while (propIter.hasNext()) {
      Property prop = propIter.nextProperty();
      Node referencedByFileNode = prop.getParent();
      final ModelId referencedById = ModelId.fromPath(referencedByFileNode.getParent().getPath());
      resource.getReferencedBy().add(referencedById);
    }

    return resource;
  }
  public void testConcurrentWorkspaceMove() throws RepositoryException {

    testRootPath = testRootNode.getPath();
    testRootNode.addNode("b");
    Node aa = testRootNode.addNode("a").addNode("aa");
    testRootNode.getSession().save();

    String aaId = aa.getIdentifier();

    Session session1 = getHelper().getReadWriteSession();
    Session session2 = getHelper().getReadWriteSession();

    // results in /b/a/aa
    session1.getWorkspace().move(testRootPath + "/a", testRootPath + "/b/a");
    assertEquals(testRootPath + "/b/a/aa", session1.getNodeByIdentifier(aaId).getPath());

    // try to move b into a/aa (should fail as the above move is persisted
    try {
      session2.getWorkspace().move(testRootPath + "/b", testRootPath + "/a/aa/b");
      fail("Workspace.move() should not have succeeded. Possible cyclic path created.");
    } catch (PathNotFoundException e) {
      // expected.
    }
  }
Exemple #21
0
  @Test
  public void testObjectGraphWithUriProperty() throws RepositoryException {
    final Container object = containerService.findOrCreate(session, "/graphObject");
    final Resource graphSubject = subjects.reverse().convert(object);

    object.updateProperties(
        subjects,
        "PREFIX some: <info:some#>\n"
            + "INSERT { <"
            + graphSubject
            + "> some:urlProperty "
            + "<"
            + graphSubject
            + "> } WHERE {}",
        object.getTriples(subjects, PROPERTIES));

    final String prefix = session.getWorkspace().getNamespaceRegistry().getPrefix("info:some#");
    final String propertyName = prefix + ":urlProperty";
    final String referencePropertyName = getReferencePropertyName(propertyName);

    assertTrue(getJcrNode(object).hasProperty(referencePropertyName));
    assertFalse(getJcrNode(object).hasProperty(propertyName));

    assertEquals(
        getJcrNode(object),
        session.getNodeByIdentifier(
            getJcrNode(object)
                .getProperty(prefix + ":urlProperty_ref")
                .getValues()[0]
                .getString()));

    object.updateProperties(
        subjects,
        "PREFIX some: <info:some#>\n"
            + "DELETE { <"
            + graphSubject
            + "> some:urlProperty "
            + "<"
            + graphSubject
            + "> } WHERE {}",
        object.getTriples(subjects, PROPERTIES));

    assertFalse(getJcrNode(object).hasProperty(referencePropertyName));
    assertFalse(getJcrNode(object).hasProperty(propertyName));

    object.updateProperties(
        subjects,
        "PREFIX some: <info:some#>\n"
            + "INSERT DATA { <"
            + graphSubject
            + "> some:urlProperty <"
            + graphSubject
            + ">;\n"
            + "       some:urlProperty <info:somewhere/else> . }",
        object.getTriples(subjects, PROPERTIES));

    assertTrue(getJcrNode(object).hasProperty(referencePropertyName));
    assertTrue(getJcrNode(object).hasProperty(propertyName));

    assertEquals(1, getJcrNode(object).getProperty(prefix + ":urlProperty_ref").getValues().length);
    assertEquals(
        getJcrNode(object),
        session.getNodeByIdentifier(
            getJcrNode(object)
                .getProperty(prefix + ":urlProperty_ref")
                .getValues()[0]
                .getString()));
  }
  public JCRNodeWrapper getNodeByUUID(final String uuid, final boolean checkVersion)
      throws ItemNotFoundException, RepositoryException {

    if (sessionCacheByIdentifier.containsKey(uuid)) {
      return sessionCacheByIdentifier.get(uuid);
    }
    RepositoryException originalEx = null;
    for (JCRStoreProvider provider : sessionFactory.getProviderList()) {
      if (!provider.isInitialized()) {
        logger.debug(
            "Provider "
                + provider.getKey()
                + " / "
                + provider.getClass().getName()
                + " is not yet initialized, skipping...");
        continue;
      }
      if (provider instanceof JackrabbitStoreProvider && JCRContentUtils.isNotJcrUuid(uuid)) {
        // not a valid UUID, probably a VFS node
        continue;
      }
      try {
        Session session = getProviderSession(provider);
        if (session instanceof JahiaSessionImpl
            && getUser() != null
            && sessionFactory.getCurrentAliasedUser() != null
            && sessionFactory.getCurrentAliasedUser().equals(getUser())) {
          ((JahiaSessionImpl) session).toggleThisSessionAsAliased();
        }
        Node n = session.getNodeByIdentifier(uuid);
        JCRNodeWrapper wrapper = provider.getNodeWrapper(n, this);
        if (getUser() != null
            && sessionFactory.getCurrentAliasedUser() != null
            && !sessionFactory.getCurrentAliasedUser().equals(getUser())) {
          JCRTemplate.getInstance()
              .doExecuteWithUserSession(
                  sessionFactory.getCurrentAliasedUser().getUsername(),
                  session.getWorkspace().getName(),
                  getLocale(),
                  new JCRCallback<Object>() {
                    public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                      return session.getNodeByUUID(uuid, checkVersion);
                    }
                  });
        }
        if (checkVersion && (versionDate != null || versionLabel != null)) {
          wrapper = getFrozenVersionAsRegular(n, provider);
        }
        sessionCacheByIdentifier.put(uuid, wrapper);
        sessionCacheByPath.put(wrapper.getPath(), wrapper);

        return wrapper;
      } catch (ItemNotFoundException ee) {
        // All good
        if (originalEx == null) {
          originalEx = ee;
        }
      } catch (UnsupportedRepositoryOperationException uso) {
        logger.debug(
            "getNodeByUUID unsupported by : "
                + provider.getKey()
                + " / "
                + provider.getClass().getName());
        if (originalEx == null) {
          originalEx = uso;
        }
      } catch (RepositoryException ex) {
        if (originalEx == null) {
          originalEx = ex;
        }
        logger.warn(
            "repository exception : "
                + provider.getKey()
                + " / "
                + provider.getClass().getName()
                + " : "
                + ex.getMessage());
      }
    }
    if (originalEx != null) {
      if (originalEx instanceof ItemNotFoundException) {
        throw originalEx;
      } else {
        throw new ItemNotFoundException(uuid, originalEx);
      }
    }

    throw new ItemNotFoundException(uuid);
  }
  protected void setUp() throws Exception {
    super.setUp();

    VersionManager versionManager = versionableNode.getSession().getWorkspace().getVersionManager();
    String path = versionableNode.getPath();
    version = versionManager.checkin(path);
    versionManager.checkout(path);
    version2 = versionManager.checkin(path);
    versionManager.checkout(path);
    rootVersion = versionManager.getVersionHistory(path).getRootVersion();

    // build a second versionable node below the testroot
    try {
      versionableNode2 = createVersionableNode(testRootNode, nodeName2, versionableNodeType);
    } catch (RepositoryException e) {
      fail("Failed to create a second versionable node: " + e.getMessage());
    }
    try {
      wSuperuser = getHelper().getSuperuserSession(workspaceName);
    } catch (RepositoryException e) {
      fail(
          "Failed to retrieve superuser session for second workspace '"
              + workspaceName
              + "': "
              + e.getMessage());
    }

    // test if the required nodes exist in the second workspace if not try to clone them
    try {
      testRootNode.getCorrespondingNodePath(workspaceName);
    } catch (ItemNotFoundException e) {
      // clone testRoot
      wSuperuser.getWorkspace().clone(superuser.getWorkspace().getName(), testRoot, testRoot, true);
    }

    try {
      versionableNode.getCorrespondingNodePath(workspaceName);
    } catch (ItemNotFoundException e) {
      // clone versionable node
      wSuperuser
          .getWorkspace()
          .clone(
              superuser.getWorkspace().getName(),
              versionableNode.getPath(),
              versionableNode.getPath(),
              true);
    }

    try {
      versionableNode2.getCorrespondingNodePath(workspaceName);
    } catch (ItemNotFoundException e) {
      // clone second versionable node
      wSuperuser
          .getWorkspace()
          .clone(
              superuser.getWorkspace().getName(),
              versionableNode2.getPath(),
              versionableNode2.getPath(),
              true);
    }

    try {
      // set node-fields (wTestRoot, wVersionableNode, wVersionableNode2)
      // and check versionable nodes out.
      wTestRoot = (Node) wSuperuser.getItem(testRootNode.getPath());

      wVersionableNode = wSuperuser.getNodeByIdentifier(versionableNode.getIdentifier());
      wVersionableNode
          .getSession()
          .getWorkspace()
          .getVersionManager()
          .checkout(wVersionableNode.getPath());

      wVersionableNode2 = wSuperuser.getNodeByIdentifier(versionableNode2.getIdentifier());
      wVersionableNode2
          .getSession()
          .getWorkspace()
          .getVersionManager()
          .checkout(wVersionableNode2.getPath());

    } catch (RepositoryException e) {
      fail("Failed to setup test environment in workspace: " + e.toString());
    }

    // create persistent versionable CHILD-node below wVersionableNode in workspace 2
    // that is not present in the default workspace.
    try {
      wVersionableChildNode =
          createVersionableNode(wVersionableNode, nodeName4, versionableNodeType);
    } catch (RepositoryException e) {
      fail("Failed to create versionable child node in second workspace: " + e.getMessage());
    }

    // create a version of the versionable child node
    VersionManager wVersionManager =
        wVersionableChildNode.getSession().getWorkspace().getVersionManager();
    String wPath = wVersionableChildNode.getPath();
    wVersionManager.checkout(wPath);
    wChildVersion = wVersionManager.checkin(wPath);
    wVersionManager.checkout(wPath);
  }
  /** {@inheritDoc} */
  public void permanentlyDeleteFile(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId)
      throws RepositoryException {
    Assert.notNull(fileId);
    Node fileNode = session.getNodeByIdentifier(fileId.toString());
    // guard against using a file retrieved from a more lenient session inside a more strict session
    Assert.notNull(fileNode);

    // see if anything is referencing this node; if yes, then we cannot delete it as a
    // ReferentialIntegrityException
    // will result
    Set<RepositoryFile> referrers = new HashSet<RepositoryFile>();
    PropertyIterator refIter = fileNode.getReferences();
    if (refIter.hasNext()) {
      while (refIter.hasNext()) {
        // for each referrer property, march up the tree until we find the file node to which the
        // property belongs
        RepositoryFile referrer =
            getReferrerFile(session, pentahoJcrConstants, refIter.nextProperty());
        if (referrer != null) {
          referrers.add(referrer);
        }
      }
      if (!referrers.isEmpty()) {
        RepositoryFile referee =
            JcrRepositoryFileUtils.nodeToFile(
                session, pentahoJcrConstants, pathConversionHelper, lockHelper, fileNode);
        throw new RepositoryFileDaoReferentialIntegrityException(referee, referrers);
      }
    }

    // technically, the node can be deleted while it is locked; however, we want to avoid an
    // orphaned lock token;
    // delete
    // it first
    if (fileNode.isLocked()) {
      Lock lock = session.getWorkspace().getLockManager().getLock(fileNode.getPath());
      // don't need lock token anymore
      lockHelper.removeLockToken(session, pentahoJcrConstants, lock);
    }

    // if this file was non-permanently deleted, delete its containing folder too
    IPentahoSession pentahoSession = PentahoSessionHolder.getSession();
    String tenantId = (String) pentahoSession.getAttribute(IPentahoSession.TENANT_ID_KEY);
    String trashFolder =
        ServerRepositoryPaths.getUserHomeFolderPath(
                new Tenant(tenantId, true), PentahoSessionHolder.getSession().getName())
            + RepositoryFile.SEPARATOR
            + FOLDER_NAME_TRASH;
    Node parent = fileNode.getParent();

    purgeHistory(fileNode, session, pentahoJcrConstants);

    if (fileNode.getPath().startsWith(trashFolder)) {
      // Remove the file and then the wrapper foler
      fileNode.remove();
      parent.remove();
    } else {
      fileNode.remove();
    }
  }
  protected RepositoryFileAcl internalUpdateAcl(
      final Session session,
      final PentahoJcrConstants pentahoJcrConstants,
      final Serializable fileId,
      final RepositoryFileAcl acl)
      throws RepositoryException {
    if (isKioskEnabled()) {
      throw new RuntimeException(
          Messages.getInstance()
              .getString("JcrRepositoryFileDao.ERROR_0006_ACCESS_DENIED")); // $NON-NLS-1$
    }

    DefaultPermissionConversionHelper permissionConversionHelper =
        new DefaultPermissionConversionHelper(session);
    Node node = session.getNodeByIdentifier(fileId.toString());
    if (node == null) {
      throw new RepositoryException(
          Messages.getInstance()
              .getString(
                  "JackrabbitRepositoryFileAclDao.ERROR_0001_NODE_NOT_FOUND",
                  fileId.toString())); // $NON-NLS-1$
    }
    String absPath = node.getPath();
    AccessControlManager acMgr = session.getAccessControlManager();
    AccessControlList acList = getAccessControlList(acMgr, absPath);

    // clear all entries
    AccessControlEntry[] acEntries = acList.getAccessControlEntries();
    for (int i = 0; i < acEntries.length; i++) {
      acList.removeAccessControlEntry(acEntries[i]);
    }

    JcrRepositoryFileAclUtils.setAclMetadata(
        session,
        absPath,
        acList,
        new AclMetadata(acl.getOwner().getName(), acl.isEntriesInheriting()));

    // add entries to now empty list but only if not inheriting; force user to start with clean
    // slate
    boolean adminPrincipalExist = false;
    ITenant principalTenant = null;
    if (!acl.isEntriesInheriting()) {
      for (RepositoryFileAce ace : acl.getAces()) {
        Principal principal = null;
        if (RepositoryFileSid.Type.ROLE == ace.getSid().getType()) {
          String principalName =
              JcrTenantUtils.getRoleNameUtils().getPrincipleName(ace.getSid().getName());
          if (tenantAdminAuthorityName.equals(principalName)) {
            adminPrincipalExist = true;
          }
          principal =
              new SpringSecurityRolePrincipal(
                  JcrTenantUtils.getTenantedRole(ace.getSid().getName()));
        } else {
          principal =
              new SpringSecurityUserPrincipal(
                  JcrTenantUtils.getTenantedUser(ace.getSid().getName()));
        }
        acList.addAccessControlEntry(
            principal,
            permissionConversionHelper.pentahoPermissionsToPrivileges(
                session, ace.getPermissions()));
      }
      if (!adminPrincipalExist) {
        if (acl.getAces() != null && acl.getAces().size() > 0) {
          principalTenant =
              JcrTenantUtils.getRoleNameUtils().getTenant(acl.getAces().get(0).getSid().getName());
        }

        if (principalTenant == null || principalTenant.getId() == null) {
          principalTenant = JcrTenantUtils.getTenant();
        }

        List<RepositoryFilePermission> permissionList = new ArrayList<RepositoryFilePermission>();
        permissionList.add(RepositoryFilePermission.ALL);
        Principal adminPrincipal =
            new SpringSecurityRolePrincipal(
                JcrTenantUtils.getRoleNameUtils()
                    .getPrincipleId(principalTenant, tenantAdminAuthorityName));
        acList.addAccessControlEntry(
            adminPrincipal,
            permissionConversionHelper.pentahoPermissionsToPrivileges(
                session, EnumSet.copyOf(permissionList)));
      }
    }
    acMgr.setPolicy(absPath, acList);
    session.save();
    return getAcl(fileId);
  }